caherrmann
New Member
- Joined
- Oct 15, 2020
- Messages
- 3
- Office Version
- 365
- Platform
- Windows
Hi all,
I am very new to VBA and am stuck trying to edit code I already have written. Essentially, the code I have (below) was intended to loop through multiple files in a folder and pull certain data columns in from a specific worksheet. This worked fine for its original purpose, but was only pulling from one main sheet ("Example A" in the code below). I now need to rewrite the code so that it loops through the files and pulls data from two separate worksheets in each file (Example A and Example B). One thing to note is that not every file has both sheets (some have both, some have one or the other), so I guess I need to incorporate some code to help determine if the sheet even exists and if not, have the code move to the next file? Would appreciate any suggestions, thanks!
I am very new to VBA and am stuck trying to edit code I already have written. Essentially, the code I have (below) was intended to loop through multiple files in a folder and pull certain data columns in from a specific worksheet. This worked fine for its original purpose, but was only pulling from one main sheet ("Example A" in the code below). I now need to rewrite the code so that it loops through the files and pulls data from two separate worksheets in each file (Example A and Example B). One thing to note is that not every file has both sheets (some have both, some have one or the other), so I guess I need to incorporate some code to help determine if the sheet even exists and if not, have the code move to the next file? Would appreciate any suggestions, thanks!
VBA Code:
Dim MyFile As String, Str As String, MyDir As String, Wb As Workbook
Dim Rws As Long, Rng As Range
Set Wb = ThisWorkbook
MyDir = (file path name is here in my code)
MyFile = Dir(MyDir & "*.xlsx")
ChDir MyDir
Application.ScreenUpdating = 0
Application.DisplayAlerts = 0
Do While MyFile <> ""
Workbooks.Open (MyFile)
Worksheets ("Example A")
Rws = .Cells(Rows.Count, "A").End(xlUp).Row
Set Rng = Range(.Cells(9, 1), .Cells(Rws, 9)) 'columns TAMCN to source
Rng.Copy Wb.Worksheets("1a. Pull Data").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
ActiveWorkbook.Close True
End With
Application.DisplayAlerts = 1
MyFile = Dir()
Loop
End Sub
Last edited by a moderator: