Search code examples
excelvbafiletextfile-writing

How to write to a text file from 2 non connected ranges in VBA


I'm trying to use a VBA code to write a range of data from my spreadsheet into a txt file that I will import into a statistical program such as STATA.

The first column of the range I want to write is, for example, "A1:A25". The second column will be user selected range, for example, "C1:C25"

The code I have tried so far will only work if the two columns are next to each other (columns A and B). If they are not connected (columns A and C) then the file writes both column A and column C into one long column of data into the txt file instead of two columns.

This is the code I have tried so far.

Sub testwrite()

Dim rng1 As Range
Dim rng2 As Range
Dim newRng As Range
path = ActiveWorkbook.path

    Set rng1 = ActiveSheet.Range("A1:A25")
    Set rng2 = Application.InputBox("Select a column of data", "Obtain Range Object", Type:=8)

    Set rng = Union(rng1, rng2)
    
    Dim check As String
    Dim c As Range, r As Range
    Dim output As String
    For Each r In rng.Rows
        For Each c In r.Cells
            output = output & "," & c.Value
        Next c
        output = output & vbNewLine
    Next r
    Open path & "\text_data3.txt" For Output As #1
    Print #1, output
    Close
End Sub

Solution

  • If this is column A & C

    A  |  C
    =======
    1     A
    2     B
    3     C
    

    and the output you are looking for is

    1,A
    2,B
    3,C
    

    You do not want to use union, you will loop through one range then the other. You can just loop through the ranges for your desired output.

    Sub testwrite()
    
    Dim rng1 As Range
    Dim rng2 As Range
    Dim newRng As Range
    Dim Path As String
    Dim r As Variant
    Dim i As Integer
    Dim rows As Integer
    
    Path = ActiveWorkbook.Path
    
    Set rng1 = ActiveSheet.Range("A2:A25")
    Set rng2 = Application.InputBox("Select a column of data", "Obtain Range Object", Type:=8)
    rows = rng1.Count
    Dim output As String
    
    For i = 1 To rows Step 1
        output = output & rng1.rows(i).Value & "," & rng2.rows(i).Value & vbCrLf
    Next i
    
    Open Path & "\text_data3.txt" For Output As #1
    Print #1, output
        Close
    End Sub