【问题标题】:Excel to CSV print specific columns only using VBAExcel 到 CSV 仅使用 VBA 打印特定列
【发布时间】:2017-02-10 16:27:24
【问题描述】:

我有一个 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

【问题讨论】:

    标签: excel vba csv printing multiple-columns


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      我觉得比较简单:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-01
        • 1970-01-01
        • 2019-01-12
        • 2017-04-28
        • 1970-01-01
        • 2020-09-02
        • 2020-03-19
        • 2015-10-13
        相关资源
        最近更新 更多