Excel到CSV仅使用VBA打印特定列
我有一个Excel电子表格,它有多列(A-G),信息在第1-26行。我正在尝试使用VBA脚本将CSV文件中的a列和D列转换为a列和B列。我已经能够将a列和D列转换为正确的位置(a列,第1-26行),但D列最终位于D列和第27-52行 将excel中的D列移动到CSV中的B列时,我缺少了什么?任何帮助都将不胜感激!请参见下面我的当前代码:Excel到CSV仅使用VBA打印特定列,excel,vba,csv,printing,multiple-columns,Excel,Vba,Csv,Printing,Multiple Columns,我有一个Excel电子表格,它有多列(A-G),信息在第1-26行。我正在尝试使用VBA脚本将CSV文件中的a列和D列转换为a列和B列。我已经能够将a列和D列转换为正确的位置(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 A
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
我尽可能地简化了代码
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
我认为这更简单:
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