将工作表导出为 CSV

Export worksheet to CSV

我想导出一个作品sheet 以 CSV 格式存储,以便我们可以回头参考并仔细检查数据集。我在A列中输出了整个sheet的代码,我希望工作sheet在工作sheet中输出。谁能帮帮我?

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

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

我已经很久没有使用直接输出写入文件了,但我相信错误就在这里:

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 (Carriage Return, Line Feed)。因此,所有内容都在一栏中结束。要修复您现有的代码,我会尝试这样做:

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

不过,我相信做这样的事情会容易得多*注意,代码是我头脑中的,没有完全调试

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 中的单个 sheet 保存为 .CSV 文件。它会自动删除 NewBook 中所有多余的 sheet,因为 .CSV 不支持多个 sheet(这就是为什么你必须复制新的 Before:= Sheet1工作簿。

一旦你确认一切都按预期工作,取消注释这两行 Application.DisplayAlerts 以禁用任何警告 Excel 想要弹出关于丢失额外的 sheets 等.