Based on what I gather from the description, the problem is the following.
The aim is to copy the content of the first sheet of three workbooks in a specified folder only containing these three workbooks into known workbook to sheets named after the letters following the last underscore.
This is actually not one problem, but three problems: find the workbooks, derive the correct sheet from the name and copy the content.
You have already dealt with the last problem, but in a not very generic way. The answers linked in the comments can help you with this further. However, since you are only concerned with the values, I would recommend to copy via an array.
Private Sub CopyValues(ByVal sourceRange As Excel.Range, ByVal targetRange As Excel.Range)
Dim copyArray as Variant
copyArray = sourceRange.Value
targetRange.Value = copyArray
End Sub
To get the name for the target sheet, you can use the VBA atring functions; in particular InstrRev
Right
and Split
could be usefult. I will leave it to you to figure out a way to define a function Private Function TargetSheetName(ByVal sourceWorkbookName As String)
.
Using this information, you do the following.
Private Sub CopyFirstSheet(ByVal sourceWorkbook As Excel.Workbook, ByVal targetWorkbook As Excel.Workbook)
Dim sourceRange As Excel.Range
Set sourceRange = CopyRange(sourceWorkbook.Worksheets(1)
Dim targetSheetName As String
targetSheetName = TargetSheetName(targetWorkbook.Name)
Dim targetRange As Excel.Range
Set targetRange = targetWorkbook.Worksheets(targetSheetName).Range("A2")
End Sub
Here Private Function CopyRange(ByVal sourceWorksheet As Excle.WorkSheet) As Excel.Range
is a function describing how you determine the copy range given the source worksheet.
Finally, there is the problem of finding the source workbooks. In the comments, it was suggested to use Dir
. However, I would like to suggest a more readable approach. Unless you work on a Mac, you can refernce the library _Microsoft Scripting Runtime` under Tools->Refreences. This gives you access to the Scripting.FileSystemObject. You can use it as follows.
Private Sub CopyFromFolder(ByVal sourcePath As String, ByVal targetWorkbook As Excel.Workbook)
Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
Dim file As Scripting.File
For Each file in fso.GetFolder(path).Files
Dim sourceWorkbook As Excel.Workbook
Set sourceWorkbook = Application.Workbooks.Open path & file.Name
CopyFirstSheet sourceWorkbook, targetWorkbook
sourceWorkbook.Close SaveChanges:=False
Next
End Sub
This assumes that only the three workbooks are in the folder. Otherwise, some more logic will be required.
I hope this is of help regarding the specific problem and in general on how to split such a problem into smaller problem that can be dealt with in separate procedures or functions.