如何使用VBA以CSV格式导出?

时间:2016-12-06 09:15:27

标签: vba excel-vba csv excel

我使用此功能以CSV格式导出数据范围:

Sub Fct_Export_CSV()
  Dim Value As String
  Dim size As Integer

  Value = ThisWorkbook.Path & "\Export_" & Sheets(1).range("B20").Value & ".csv"
  chemincsv = Value

  Worksheets("Database").Select
  Dim Plage As Object, oL As Object, oC As Object, Tmp As String, Sep$
  Sep = ";"
  size = Worksheets("Database").range("B" & Rows.Count).End(xlUp).Row
  Set Plage = ActiveSheet.range("A1:G" & size)

  Open chemincsv For Output As #1
  For Each oL In Plage.Rows
    Tmp = ""
    For Each oC In oL.Cells
      Tmp = Tmp & CStr(oC.Text) & Sep
    Next
    Print #1, Tmp
  Next
  Close

  MsgBox "OK! Export to " & Value
End Sub

出口有效,但我也有一个";"在每一行的末尾。

示例导出CSV:

  

文件夹;树;组;姓;名字; sAMAccountName赋;规则;
  夹; TREE; DL-FOLDER-R;约翰; TOTO; JTOT; R;

我在哪里修改此VBA脚本以生成没有&#34 ;;"的CSV;在末尾 ?
我的目标:

  

文件夹;树;组;姓;名字; sAMAccountName赋;规则
  夹; TREE; DL-FOLDER-R;约翰; TOTO; JTOT; R

2 个答案:

答案 0 :(得分:3)

有多种方法可以实现这一目标。 例如。如果迭代是最后一个,你可以在Tmp = Tmp & CStr(oC.Text) & Sep中放置一个if条件来不附加sep。

另一种方法是使用左功能。如果不修改你的大部分代码,我认为这将是一个很好的方法。 这是一个示例代码(havnt尝试过):

Sub Fct_Export_CSV()
  Dim Value As String
  Dim size As Integer

  Value = ThisWorkbook.Path & "\Export_" & Sheets(1).range("B20").Value & ".csv"
  chemincsv = Value

  Worksheets("Database").Select
  Dim Plage As Object, oL As Object, oC As Object, Tmp As String, Sep$
  Sep = ";"
  size = Worksheets("Database").range("B" & Rows.Count).End(xlUp).Row
  Set Plage = ActiveSheet.range("A1:G" & size)

  Open chemincsv For Output As #1
  For Each oL In Plage.Rows
    Tmp = ""
    For Each oC In oL.Cells
      Tmp = Tmp & CStr(oC.Text) & Sep
    Next


'take one less than length of the string number of characters from left, that would eliminate the trailing semicolon
    Tmp = left(Tmp, Len(Tmp)-1)

    Print #1, Tmp
  Next
  Close



  MsgBox "OK! Export to " & Value
End Sub

在最后一个print语句之前添加了一行代码,应该可行。 lemme知道。

答案 1 :(得分:0)

如果您使用以分号设置为本地分隔符的计算机,则可以将工作表另存为csv并指定Local:=True

Worksheets("Database").SaveAs Filename:=Value, FileFormat:=xlCSV, Local:=True