Excel to CSV print specific columns only using VBA

2019-09-07 03:42发布

I have an Excel spreadsheet that has multiple columns (A-G) with information in rows 1-26. I am trying to use a VBA script to convert only columns A and D to the CSV file to columns A and B. I have been able to convert columns A and D and A is in the correct position (column A, rows 1-26), but column D ends up in column D and rows 27-52.

What am I missing to move column D in excel to column B in the CSV? Any help would be greatly appreciated! See my current code below:

Dim file As Integer 
Dim filepath As Variant 
Dim filename As Variant 
Dim Row As Integer 
Dim Col As Integer 
Dim Data1 As String 
Dim Data2 As String 
Dim Line As String 
Dim LineValues() As Variant 
Dim OutputFileNum As Integer 
Dim PathName As String 
Dim SheetValues() As Variant 

file = FreeFile 
filepath = "C:\Users\berniea\" 
filename = filepath & "Options" & ".csv" 
Open filename For Output As #file 

SheetValues = Sheets("Features").Range("A1:H26").Value 
Redim LineValues(1 To 8) 

For Row = 2 To 26 
    For Col = 1 To 1 
        LineValues(Col) = SheetValues(Row, Col) 
    Next 
    Data1 = Join(LineValues, ",") 
    Print #file, Data1 
Next 

SheetValues = Sheets("Features").Range("A1:H26").Value 
Redim LineValues(1 To 8) 

For Row = 2 To 26 
    For Col = 4 To 4 
        LineValues(Col) = SheetValues(Row, Col) 
    Next 
    Data2 = Join(LineValues, ",") 
    Print #file, Data2 
Next 

Close #file 

End Sub

2条回答
手持菜刀,她持情操
2楼-- · 2019-09-07 04:14

I think it is more simple:

Dim text As String
file = FreeFile
filepath = "C:\Users\berniea\"
filename = filepath & "Options" & ".csv"
Open filename For Output As #file
For Row = 2 To 26
text = text + Cells(Row, 1) & "," & Cells(Row, 4) & vbNewLine
Next Row
Print #file, text
Close #file
查看更多
贪生不怕死
3楼-- · 2019-09-07 04:16

I simplified the code for you as much as possible.

Sub ColsAD()
    Dim file As Integer: file = FreeFile
    Open "C:\Users\berniea\Options.csv" For Output As #file

    Dim row As Long, line As String
    For row = 2 To 26
        With Sheets("Features")
             line = .Cells(row, 1) & "," & .Cells(row, 4)
        End With
        Print #file, line
    Next
    Close #file
End Sub
查看更多
登录 后发表回答