我有多个.CSV文件保存我的数据。我正在尝试将它们合并到一个主工作表中。
宏在打开系列中的第一个.CSV文件后停止。它不会出错。
我仍然需要编写大量的代码,比如标识特定的列和行,并从每个表中获取特定的数据。
我有这个设置作为模板。
我把代码转移到一个新的工作簿,它仍然没有给我任何给予。
Option Explicit
Private Sub CommandButton1_Click()
mergeData
End Sub
Sub mergeData()
On Error GoTo ErrHandler
Application.ScreenUpdating = False
' Our FileSystem Objects.
Dim objFs As Object
Dim objFolder As Object
Dim file As Object
'Show a pop up to select a folder.
Dim sPath As String
sPath = chooseFolder()
Set objFs = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFs.GetFolder(sPath) ' The folder path.
Dim iCnt As Integer
iCnt = 1
' Loop through all the files in the folder.
For Each file In objFolder.Files
Dim objSrc As Workbook ' The source.
Set objSrc = Workbooks.Open(file.Path, True, True)
Dim iTotalRows As Integer ' The total used range in the source file.
iTotalRows = objSrc.Worksheets("Sheet1").UsedRange.Rows.Count
Dim iTotalCols As Integer ' Now, get the total columns in the source.
iTotalCols = objSrc.Worksheets("Sheet1").UsedRange.Columns.Count
Dim iRows, iCols As Integer
' Read data from source and copy in the master file.
For iRows = 1 To iTotalRows
For iCols = 1 To iTotalCols
Application.Workbooks(1).ActiveSheet.Cells(iRows, iCols) = _
objSrc.Worksheets("Sheet1").Cells(iRows, iCols)
' Note: It will read data in "Sheet1" of the source file.
Next iCols
Next iRows
iRows = 0
' Get the name of the file (I'll name the active sheet with the filename).
Dim sSheetName As String
sSheetName = Replace(objSrc.Name, ".csv", "") ' Assuming the files are .xlsx files.
' Close the source file (the file from which its copying the data).
objSrc.Close False
Set objSrc = Nothing
With ActiveWorkbook
.ActiveSheet.Name = sSheetName ' Rename the sheet.
iCnt = iCnt + 1
If iCnt > .Worksheets.Count Then
' Create or add a new sheet after the last sheet.
.Sheets.Add After:=.Worksheets(.Worksheets.Count)
End If
.Worksheets(iCnt).Activate ' Go to the next sheet.
End With
Next
ErrHandler:
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
' Open file dialog box to select a folder.
Function chooseFolder() As String
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.Filters.Clear
.Title = "Select an Excel File"
.Filters.Add "Excel Files", "*.csv?", 1
.AllowMultiSelect = True
Dim sPath As String
If .Show = True Then
chooseFolder = fd.InitialFileName ' Get the folder path.
End If
End With
End Function
字符串
1条答案
按热度按时间8dtrkrch1#
将CSV文件复制到新工作簿
字符串