manish449
manish449

Reputation: 541

VBA write a column to a text file formatted by another column

I have two columns of data.

file,category
a,1
b,1
c,1
d,2
e,2
f,2
g,3
h,3
i,3

I want to print the first column to a text file which is formatted by the second column.

eg.

category 1
a
b
c
category 2
d
e
f
category 3
g
h
i 

Any help appreciated.

Upvotes: 0

Views: 1282

Answers (1)

Gary's Student
Gary's Student

Reputation: 96773

This works with your posted data:

Sub testlist3()
    Open "C:\TestFolder\testlist" & Format(Now(), "_yyyy-mm-dd_hh-mm") & ".lst" For Output As #1
    Dim N As Long, L As Long
    N = Cells(Rows.Count, "A").End(xlUp).Row
    Print #1, "catagory " & Cells(1, "B").Value
    Print #1, Cells(1, "A").Value
    For L = 2 To N
        If Cells(L, "B").Value <> Cells(L - 1, "B").Value Then
            Print #1, "catagory " & Cells(L, "B").Value
        End If
        Print #1, Cells(L, "A").Value
    Next L
    Close #1
    MsgBox "done"
End Sub

Upvotes: 1

Related Questions