【发布时间】:2017-05-06 14:31:06
【问题描述】:
我想知道是否有人可以帮助我。
使用我在网上找到的脚本作为“基础”,我编写了下面的查询。
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?
Dim fNameAndPath As Variant
fNameAndPath = Application.GetOpenFilename(Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub
Workbooks.Open Filename:=fNameAndPath
Application.ScreenUpdating = False
'Initialize data
Set ThisSheet = ActiveWorkbook.Worksheets(1)
NumOfColumns = ThisSheet.UsedRange.Columns.Count
WorkbookCounter = 1
RowsInFile = 50 '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
Application.ScreenUpdating = False
With wb
.SaveAs Filename:=fNameAndPath & "\File " & WorkbookCounter, FileFormat:=xlCSV
wb.Close False
Application.DisplayAlerts = True
End With
'Increment file counter
WorkbookCounter = WorkbookCounter + 1
Next p
Application.ScreenUpdating = True
Set wb = Nothing
End Sub
脚本的目的是获取一个“主”文件并将其拆分为较小的文件,并将它们保存为 CSV。
With wb
.SaveAs Filename:=fNameAndPath & "\File " & WorkbookCounter, FileFormat:=xlCSV
wb.Close False
Application.DisplayAlerts = True
End With
我要做的是使用原始文件名作为新创建的文件名的一部分创建保存新创建的文件,然后关闭所有文件。
能否提供一些关于我哪里出错的指导?
非常感谢和亲切的问候
克里斯
【问题讨论】: