Hi..
How about Browsing for the Folder using a Browse Dialogue...
Private Sub CommandButton1_Click()
Dim Crit1 As String, myFolder As String
Dim LastRow As Long, LastRow2 As Long, i As Long
Dim myRange
Application.DisplayAlerts = False
Application.ScreenUpdating = False
LastRow = Sheets("Dept").Range("A" & Rows.Count).End(xlUp).Row
Continue:
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
If (.SelectedItems.Count = 0) Then Exit Sub
myFolder = .SelectedItems(1)
End With
For i = 2 To LastRow
Crit1 = Sheets("Dept").Cells(i, 1).Value
Sheets("Data").Range("A1:C" & LastRow).AutoFilter Field:=1, Criteria1:=Crit1
On Error GoTo ErrHand
Application.Workbooks.Open (myFolder & "\" & Crit1 & ".xlsx")
Workbooks(Crit1 & ".xlsx").Sheets("Sheet1").UsedRange.ClearContents
LastRow2 = Workbooks(Crit1 & ".xlsx").Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
Set myRange = Workbooks("Dept queries.xlsm").Sheets("Data").Range("A2:C" & Workbooks("Dept queries.xlsm").Sheets("Data").Cells(Rows.Count, "A").End(xlUp).Row).SpecialCells(xlCellTypeVisible)
myRange.Copy Destination:=Workbooks(Crit1 & ".xlsx").Sheets("Sheet1").Cells(LastRow2 + 1, 1)
Workbooks(Crit1 & ".xlsx").Close SaveChanges:=True
Next i
If Sheets("Data").AutoFilterMode Then Sheets("Data").AutoFilterMode = False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Sheets("Dept").Cells(4, 6).Value = myFolder
MsgBox "Data Has Been Copied!"
ErrHand:
Select Case Err.Number
Case 1004
msg = "Error: " & Err.Number & vbCrLf & Err.Description
MsgBox msg, vbOKOnly, "Incorrect Folder Selected"
Err.Clear
GoTo Continue
Resume Next
End Select
End Sub
Note: It will also store the most recent folder selection in your Dept sheet..
Bookmarks