Excel到CSV仅使用VBA打印特定列

时间:2017-02-10 16:27:25

标签: excel vba csv printing multiple-columns

我有一个Excel电子表格,其中包含多列(A-G),其中包含1-26行的信息。我正在尝试使用VBA脚本将列A和D转换为CSV文件到列A和B.我已经能够转换列A和D,并且A位于正确的位置(列A,行1-26但是,列D最终在列D和行27-52中结束。

将Excel中的D列移到CSV中的B列时,我错过了什么?任何帮助将不胜感激!请参阅下面的我当前的代码:

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 个答案:

答案 0 :(得分:1)

我尽可能简化了代码。

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

答案 1 :(得分:0)

我认为这更简单:

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