I am really new to VBA and I have just been learning the basics and the VBA language recently from Youtube and communities such as these. Therefore, any help will be really appreciated!
I am trying to consolidate excel worksheets from different excel workbooks into a main excel workbook. The excel workbooks are all found in the same file. However, they are named differently and I only have the partial names for the excel workbooks e.g. "ABG_RSPB_xxxxx-yyyy".
I will have a main workbook in the folder consolidating the data from all the different workbook and worksheets. Each workbook where the data is extracted from only has one worksheet and the template in each worksheet is the same. They have the same headers as well. All the workbooks are csv format. However the worksheets have partial names as well (the worksheet will have the same name as the workbook it is in).
Currently, I have a macro that provides a similar function however, it can't extract workbooks and worksheets with partial names.
Any help to amend the macro such that it can extract from partial workbooks and worksheets will be deeply appreciated. Thank you!
Current code:
Sub consolidation ()
Set mainWB = ActiveWorkbook
Dim mainPath As String
mainPath = ThisWorkbook.Path
Dim mainRowstart As Integer
mainRowstart = 2
Dim mainRC As Integer
mainRC = lastRow ("Consolidated Trades", "A") + 1
If mainRC < mainRowStart Then
mainRC = mainRowStart
EndIf
Dim fso As Object
Dim folder As Object
Dim files As Object
Set fso = CreateObject ("Scripting.FileSystemObject")
Set folderPaths = fso.getfolder (mainPath)
set filePaths = folderPath.files
Dim curFile As String
Dim curPath As String
Dim curRC As Integer
Dim curWSName As String
curWSName = ""
For Each filePath In filePaths
curPath = filePath
curFile = Split (curPath, "\")(UBound(Split(curPath, "\")))
If Left (curFile, 1) <> "~" Then
If curFile <> "ABG_RSPB_xxxxx=yyy.csv" Then
If Right (curFile, Len ("ABG_RSPB_xxxxx=yyy.xlsm")) = "ABG_RSPB_xxxxx=yyy.xlsm" Or _ Right (curFile, Len("ABG_RSPB_xxxxx=yyy.xls")) = "ABG_RSPB_xxxxx=yyy.xls" Then
Workbooks.Open Filename: = curPath
Workbooks (curFile).Activate
For Each ws In Worksheets
If ws.Name = "ABG_RSPB_xxxxx=yyy.csv" Then
curWSName = ws.Name
End If
Next Ws
curRC = lastRow(CurWSName, "A")
mainWB.Activate
mainRC = lastrow("Consolidated Trades", "A") + 1
If curRC >= 2 Then
mainWB.Worksheets("Consolidated Trades").Range("A" & mainRC & ":U: & mainRC + curRC - 2).Value = _ Workbooks(curFile).Worksheets(curWSName).Range("A2:U" & curRC).Value
mainWB.Worksheets("Consolidated Trades").Range("V" & mainRC).Value = curFile & "with" & curRC -1 & "Rows of Data"
EndIf
Workbooks(curFile).Close
EndIf
EndIf
EndIf
NextfilePath
MsgBox "Process Complete"
End Sub
Worksheets(1)
will always work fine with a CSV file (since there are never more than 1 worksheet when a CSV is opened in Excel) – Tim Williams