将工作表导出为CSV

时间:2015-04-17 12:44:30

标签: excel excel-vba csv export export-to-csv vba

我想导出要存储为CSV的工作表,以便我们可以返回并仔细检查数据集。代码我输出了A列中的整个工作表,我希望工作表能够在工作表中输出。任何人都可以帮助我吗?

值得注意的是,表的宽度和长度都是可变的,因此是计数器。

Sub DataSets()

Dim shRefData As Worksheet, shInput As Worksheet
Set shRefData = ThisWorkbook.Sheets("ReferenceData")
Dim w, x, y, z As Integer
Dim filepath As String

filepath = ThisWorkbook.Path + "\"
w = 3
z = 1
x = 1

Open ThisWorkbook.Path + "\" + "Dataset" & Format(Now, "DDMMYY") & ".csv" For Output As #1

Do While shRefData.Cells(w, 1) <> ""
    w = w + 1
Loop
Do While shRefData.Cells(3, z) <> ""
    z = z + 1
Loop

For x = 1 To w
    For y = 1 To z
        Print #1, Cells(x, y)
        y = y + 1
    Next
    x = x + 1
Next

Close #1

End Sub

1 个答案:

答案 0 :(得分:1)

自从我使用直接输出写入文件以来,这是一段很长的时间,但我相信错误就在这里:

For x = 1 To w
  For y = 1 To z
    'this line is the issue:
    Print #1, Cells(x, y)
    y = y + 1
  Next
  x = x + 1
Next

我相信当你Print #1时,它会在打印后自动放入CRLF(回车,换行)。因此,一切都在一列中结束。要修复现有代码,我试试这个:

Dim out as string
For x = 1 To w
  out = ""
  For y = 1 To z
    'this builds a string of "value, value, value"
    out = out & Cells(x,y) & ", "
    y = y + 1
  Next
  Print #1, out
  x = x + 1
Next

但是,我相信做这样的事情会更容易 * note,我的头顶代码,没有完全调试

Sub DataSets()

  Dim shRefData As Worksheet
  Dim NewBook as Workbook
  DiM NewName as String

  Set shRefData = ThisWorkbook.Sheets("ReferenceData")
  NewName = ThisWorkbook.Path & "\" + "Dataset" & Format(Now, "DDMMYY") & ".csv"

  set NewBook = workbooks.add
  shRefData.copy Before:=NewBook.sheets(1)
  'Application.DisplayAlerts = False
  NewBook.SaveAs FileName:=NewName, FileFormat:=xlCSV
  'Application.DisplayAlerts = True
  NewBook.close
  set NewBook = Nothing

End Sub

这应该将NewBook中的单个工作表保存为.CSV文件。它会自动删除NewBook中的所有额外工作表,因为.CSV不支持多个工作表(这就是为什么你必须复制新工作簿的{1}} Sheet1。

一旦您确认所有内容都按预期工作,请取消注释两条Before:=行,以禁用Excel希望弹出的有关丢失额外工作表的任何警告等。