从Excel范围写入文本文件

时间:2017-03-25 18:42:21

标签: excel vba excel-vba

我尝试使用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 #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

2 个答案:

答案 0 :(得分:0)

您可以使用如下所示的代码

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

答案 1 :(得分:0)

这样做怎么样?

'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