Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export column range to text file from different worksheet

Tags:

excel

vba

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
like image 401
Molar Bear Avatar asked Mar 03 '26 22:03

Molar Bear


1 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
like image 86
Tim Williams Avatar answered Mar 05 '26 21:03

Tim Williams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!