Home » excel » vba – Export column range to text file from different worksheet

vba – Export column range to text file from different worksheet

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am trying to get a macro to copy the data from the range of A1 to the last cell with data in column A in my second worksheet. This code will output the file to the same destination as the excel workbook, but the file is empty and I’m unsure why. It is currently exporting as a .txt, and I want it as a .prox, but I’m not sure if changing the output name to “ExportedData.prox” will affect the data

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
How to&Answers:

Try this (untested):

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