如何在选择 txt 进行输出后另存为对话框



所以,这是我当前的代码,基本上只是获取 excel 工作表的值并将其放入.txt文件中。 它只是在 \temp 中打开/创建一个文本文件,然后将其保存在那里。 我想在激活宏后弹出一个另存为对话框,我可以将文本文件保存在任何我想要的地方。提前感谢!

Sub ascii_datei_exportieren()

Open "c:temptext.txt" For Output As 1
For zeile = 2 To 4
Text = ""
For spalte = 2 To 3
Text = Text & CVar(Cells(zeile, spalte))
If spalte < 4 Then Text = Text & "|"
Next
Print #1, Text
Next
Close #1
End Sub

您可以使用Application.GetSaveAs文件名方法(Excel(

谢谢悉达多,在发布问题之前,我已经看过那个链接了。我只是不知道如何将它放入我的代码中以便它工作。– Dani2507 16分钟前

其实很简单。这是您正在尝试的(未经测试(吗?

Option Explicit
Sub Sample()
Dim fileSaveName As Variant
Dim zeile As Integer, spalte As Long
Dim sText As String
fileSaveName = Application.GetSaveAsFilename(fileFilter:="sText Files (*.txt), *.txt")
If fileSaveName <> False Then
Open fileSaveName For Output As 1
For zeile = 2 To 4
sText = ""
For spalte = 2 To 3
sText = sText & CVar(Cells(zeile, spalte))
If spalte < 4 Then sText = sText & "|"
Next
Print #1, sText
Next
Close #1
End If
End Sub

TIP:避免将Text用作变量。

试试这个,请。它使您的代码保持原样,并在Open ... for Output序列之前定义文件夹路径:

Option Explicit

Sub ascii_datei_exportieren()
Dim fileName As String, folderPath As String, zeile As Long
Dim text As String, spalte As Long
folderPath = GetFolderPath(ThisWorkbook.FullName) ' you can ommit the parameter
fileName = "text.txt"
Open folderPath & "" & fileName For Output As 1
For zeile = 2 To 4
text = ""
For spalte = 2 To 3
text = text & CVar(Cells(zeile, spalte))
If spalte < 4 Then text = text & "|"
Next
Print #1, text
Next
Close #1
End Sub
Private Function GetFolderPath(Optional strPath As String) As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
If strPath <> "" Then .InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolderPath = sItem
Set fldr = Nothing
End Function

通常,最好在模块顶部使用Option Explicit并正确标注所有变量的尺寸。这将为您节省许多潜在的未来问题......

或者,您可以使用下一个代码具有 SaveAs(用于文本文件(对话框:

Sub testDialogSaveAsText()
Dim fileSaveName As String, fileName As String
fileName = "text.txt"
fileSaveName = Application.GetSaveAsFilename(InitialFileName:=fileName, fileFilter:="Text Files (*.txt), *.txt")
If fileSaveName <> "" Then
MsgBox "Saved as " & fileSaveName
End If
End Sub

最新更新