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

我有一个Excel电子表格有多个列(AG)与信息在行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 

我认为这更简单:

 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 

我尽可能简化了代码。

 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