将列范围导出到不同工作表中的文本文件

时间:2017-03-15 00:33:23

标签: vba excel-vba excel

我正在尝试使用宏来将数据从A1范围复制到最后一个单元格,并在第二个工作表中使用A列中的数据。此代码将文件输出到与excel工作簿相同的目标,但该文件为空,我不确定原因。它目前以.txt的形式导出,我希望它作为.prox,但我不确定将输出名称更改为“ExportedData.prox”是否会影响数据

Sub OpenTextFile()

Dim FilePath As String
Dim LastRow As Long
Dim CellData As String
Dim WS2 As Worksheet
Dim WS1 As Worksheet


Set WS1 = Worksheets(1)
Set WS2 = Worksheets(2)

WS2.Activate

FilePath = ThisWorkbook.Path & "\" & "ExportedData.txt"
LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

Open FilePath For Output As #1
For i = 1 To LastRow
CellData = ActiveCell(i).Value
Print #1, CellData
Next i
Close #1

WS1.Activate

MsgBox "Done", vbMsgBoxSetForeground

End Sub

1 个答案:

答案 0 :(得分:3)

试试这个(未经测试):

Sub OpenTextFile()

    Dim FilePath As String
    Dim LastRow As Long
    Dim CellData As String
    Dim WS2 As Worksheet
    Dim WS1 As Worksheet


    Set WS1 = Worksheets(1)
    Set WS2 = Worksheets(2)

    FilePath = ThisWorkbook.Path & "\" & "ExportedData.prox"
    LastRow = WS2.UsedRange.SpecialCells(xlCellTypeLastCell).Row

    Open FilePath For Output As #1
    For i = 1 To LastRow
        CellData = WS2.Cells(i, 1).Value '<< assumes ColA is being exported
        Print #1, CellData
    Next i
    Close #1

    WS1.Activate

    MsgBox "Done", vbMsgBoxSetForeground

End Sub