Vba 从Excel范围写入文本文件
我正在尝试使用Excel VBA将范围写入文本文件。我正在使用我发现的以下脚本:Vba 从Excel范围写入文本文件,vba,excel,Vba,Excel,我正在尝试使用Excel VBA将范围写入文本文件。我正在使用我发现的以下脚本: Sub VBA_write_to_a_text_file_from_Excel_Range() Dim iCntr Dim strFile_Path As String strFile_Path = "C:\temp\test.txt" Open strFile_Path For Output As #1 For iCntr = 1 To 10 Print #
Sub VBA_write_to_a_text_file_from_Excel_Range()
Dim iCntr
Dim strFile_Path As String
strFile_Path = "C:\temp\test.txt"
Open strFile_Path For Output As #1
For iCntr = 1 To 10
Print #1, Range("A" & iCntr)
Next iCntr
Close #1
End Sub
我想选择保存文件的路径。我发现了一段代码摘录,但如何将其添加到上面的代码中,使其正常工作
fPath = Application.GetSaveAsFilename(FileFilter:="Text Files (*.txt), *.txt", Title:="Save As")
If fPath = "" Then Exit Sub '//user cancelled
您可以使用如下所示的代码
fpath = Application.GetSaveAsFilename(FileFilter:="Text Files (*.txt), *.txt", Title:="Save As")
If fpath <> "" Then
Dim iCntr
Dim strFile_Path As String
strFile_Path = fpath
Open strFile_Path For Output As #1
For iCntr = 1 To 10
Print #1, Range("A" & iCntr)
Next iCntr
Close #1
End If
fpath=Application.GetSaveAsFilename(文件过滤器:=“文本文件(*.txt),*.txt”,标题:=“另存为”)
如果是fpath“”,则
暗中心
将strFile\u路径设置为字符串
strFile_Path=fpath
打开输出为#1的strFile_路径
对于iCntr=1到10
打印#1,范围(“A”和iCntr)
下一个iCntr
关闭#1
如果结束
这样做怎么样
'Excel VBA Write to Text File:
Sub WriteToTextFile()
Dim FilePath As String
Dim CellData As String
Dim LastCol As Long
Dim LastRow As Long
LastCol = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column
LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
CellData = ""
FilePath = Application.DefaultFilePath & "\auth.csv"
Open FilePath For Output As #1
For i = 1 To LastRow
For j = 1 To LastCol
If j = LastCol Then
CellData = CellData + Trim(ActiveCell(i, j).Value)
Else
CellData = CellData + Trim(ActiveCell(i, j).Value) + ","
End If
Next j
Write #1, CellData
Next i
Close #1
MsgBox ("Done")
End Sub
您不需要同时使用strFile_Path和fPath变量:只需选择并使用其中一个变量,即tanks June7和Biju John@用户3598756您可以展示您的建议吗?只需将所有出现的
strFile\u Path
替换为fpath
(或相反,由您选择),然后删除strFile\u Path=fpath
语句