0

I'm trying to create an Excel VBA script which will take 2 columns as input and output the values of into a text file.

e.g

A1: 123 B1: avenue

A2:231 B2: another lane

I'm after an output in a txt file that looks something like this:

House number: 123 Street name: avenue

----.

House number: 231 Street name: another lane

----.

Basically what i'm looking for is: "House number: "+A1+ " Street name: "+B2 "------"

I've got this to work with just 1 column however I'm stuck with adding a second.

Sub CreatetestScript()

    If Dir("C:\test.txt") <> "" Then
     Kill ("C:\test.txt")
    End If

    Sheets("test").Select
    Dim acolumn As String

    r = 2
    Do While Cells(r, 1) <> ""
        acolumn = Cells(r, 1).Value
        run (Cells(r, 1))
        r = r + 1
    Loop

End Sub
Sub run(ByVal acolumn As String)

Dim fileName As String
fileName = "C:\test.txt"

Open fileName For Append As #1

    Print #1, ""
    Print #1, "House Number = " + acolumn
    Print #1, "--------------"

Close #1

End Sub

Any help would be appreciated

1 Answer 1

1

You could go many directions with this, one way would be creating a bcolumn variable and setting it to the next cell's index in your row:

Sub CreatetestScript()

    If Dir("C:\test.txt") <> "" Then
     Kill ("C:\test.txt")
    End If

    Sheets("test").Select
    Dim acolumn As String
    Dim bColumn As String
    r = 2
    Do While Cells(r, 1) <> ""
        acolumn = Cells(r, 1).Value
        bColumn = Cells(r,2).value
        run (Cells(r, 1), Cells(r,2))
        r = r + 1
    Loop

End Sub
Sub run(ByVal acolumn As String, ByVal Bcolumn As String)

Dim fileName As String
fileName = "C:\test.txt"

Open fileName For Append As #1

    Print #1, ""
    Print #1, "House Number = " + acolumn
    Print #1, "--------------"
    Print #1, ","
    Print #1, "Street = " + Bcolumn
    Print #1, "--------------"
Close #1

End Sub

Your output may need formatted differently, but this should get you on track. For a little reusability, You could setup the function to take an array of these strings too.

Sign up to request clarification or add additional context in comments.

3 Comments

HI, Thanks for the answer, I get a compile error Argument not optional error message
I wasn't providing the new value to the run function. Please see my change and let me know if we're on the right track here :)
you're too fast. Just tried that. Thanks for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.