I've got an excel macro that will open through all files in a folder and run some code, The problem is the files in the folder are either .xlsx or .csv.
The part of the code I'm using is as below.
I have to change the code manually to
and run the macro twice.
Is there a way to get the macro to open both xlsx and csv files?
Thanks.
Below is the code I'm using
The part of the code I'm using is as below.
Code:
fileName = Dir(folderPath & "*.xlsx")
I have to change the code manually to
Code:
fileName = Dir(folderPath & "*.csv")
Is there a way to get the macro to open both xlsx and csv files?
Thanks.
Below is the code I'm using
Code:
Sub SearchAndCompileData()
Dim keyword As String
Dim folderPath As String
Dim fileName As String
Dim wb As Workbook
Dim ws As Worksheet
Dim file As String
Dim arrData() As Variant
Dim i As Long
Dim lastRow As Long
keyword = InputBox("Enter search keyword")
If keyword = "" Then Exit Sub
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select Folder"
.Show
If .SelectedItems.Count = 0 Then Exit Sub
folderPath = .SelectedItems(1) & "\"
End With
Set ws = ThisWorkbook.ActiveSheet
lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
i = lastRow + 1
fileName = Dir(folderPath & "*.xlsx")
Do While fileName <> ""
Set wb = Workbooks.Open(folderPath & fileName)
Set ws = wb.Worksheets(1)
For Each cell In ws.Range("B1:B" & ws.Cells(ws.Rows.Count, "B").End(xlUp).Row)
If cell.Value = keyword Then
ws.Range("C" & cell.Row).Copy Destination:=ThisWorkbook.ActiveSheet.Range("C" & i)
ws.Range("D" & cell.Row).Copy Destination:=ThisWorkbook.ActiveSheet.Range("D" & i)
i = i + 1
End If
Next cell
wb.Close SaveChanges:=False
fileName = Dir
Loop
MsgBox "Search and compilation completed."
End Sub
Last edited: