【问题标题】:Exporting lists and saving them as .CSV file导出列表并将其保存为 .CSV 文件
【发布时间】:2019-03-11 02:20:11
【问题描述】:

我发现这段代码极大地帮助了我的工作。不过,我想对它进行更多的定制,但在我的一生中,我无法让它工作。我完全没有编码知识,所以我想我可以从这个社区获得一些帮助。

我想包含一些内容,以便在保存文件时以 .CSV 文件格式保存。我的代码如下所示。

Sub Test()
  Dim wb As Workbook
  Dim ThisSheet As Worksheet
  Dim NumOfColumns As Integer
  Dim RangeToCopy As Range
  Dim RangeOfHeader As Range        'data (range) of header row
  Dim WorkbookCounter As Integer
  Dim RowsInFile                    'how many rows (incl. header) in new files?

  Application.ScreenUpdating = False

  'Initialize data
  Set ThisSheet = ThisWorkbook.ActiveSheet
  NumOfColumns = ThisSheet.UsedRange.Columns.Count
  WorkbookCounter = 1
  RowsInFile = 101                   'as your example, just 1000 rows per file

  'Copy the data of the first row (header)
  Set RangeOfHeader = ThisSheet.Range(ThisSheet.Cells(1, 1), ThisSheet.Cells(1, NumOfColumns))

  For p = 2 To ThisSheet.UsedRange.Rows.Count Step RowsInFile - 1
    Set wb = Workbooks.Add

  'Paste the header row in new file
    RangeOfHeader.Copy wb.Sheets(1).Range("A1")

  'Paste the chunk of rows for this file
    Set RangeToCopy = ThisSheet.Range(ThisSheet.Cells(p, 1), ThisSheet.Cells(p + RowsInFile - 2, NumOfColumns))
    RangeToCopy.Copy wb.Sheets(1).Range("A2")

  'Save the new workbook, and close it
    wb.SaveAs ThisWorkbook.Path & "\file " & WorkbookCounter
    wb.Close

  'Increment file counter
    WorkbookCounter = WorkbookCounter + 1
  Next p

  Application.ScreenUpdating = True
  Set wb = Nothing
End Sub

【问题讨论】:

  • 尝试在将文件另存为 CSV 的同时录制宏,然后尝试将其合并到此代码中。如果您有问题,请回复您尝试过的代码,并说明您遇到的任何错误

标签: excel vba csv export


【解决方案1】:

Juan,如果我理解,您唯一的目标是保存为 CSV。如果是这种情况,除了 SaveAs 方法中缺少第二个参数外,您所拥有的一切都是正确的;这是FileFormat

例如:

Sub SaveAsCSV()

Dim wb As Workbook

Set wb = ThisWorkbook

Application.DisplayAlerts = False
wb.SaveAs ThisWorkbook.Path & "\" & "name1", xlCSV
Application.DisplayAlerts = True

End Sub

【讨论】:

  • 嘿,感谢您为我回答这个问题。为了澄清,我发布的代码每 101 行从主文件中吐出单独的工作簿,但它们以 .xlsx 格式吐出,我希望它们以 .csv 格式吐出。抱歉,如果这是您给我的,我只是不确定将代码粘贴到模块的哪个位置...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2018-04-29
  • 2018-01-02
相关资源
最近更新 更多