I apologize in advance, I have very little excel-VB experience.
I currently have two modules that: goes to the specified file path, tries to find the parent folder. Next, treat each file as an object, and iterate through all of the items and puts them into an array. The macro will then try to open each excel file **in the folder** and copy from the relevant range (or sheet) specified in the folder and paste it into a newly created spreadsheet. The code works, but I would like it to only accept ONE excel file from either a path put in a cell or a variable and not a folder. As it is, it will open an entire folder and copy all the excel files over to another sheet.
Instead of modifying the file path in the macro and finding all the files in that folder, I would like to use a series of file paths (or just 1 if not possible) from cells in Column A. Is it possible to put each single file from the specified path into the array instead? The quick fix I can think of is to: change the rootFolder array to only accept the specified file. Could someone tell me how to go about doing that?
Option Explicit
Private myFiles() As String
Private Fnum As Long
Function Get_File_Names(MyPath As String, Subfolders As Boolean, _
ExtStr As String, myReturnedFiles As Variant) As Long
Dim Fso_Obj As Object, RootFolder As Object
Dim SubFolderInRoot As Object, file As Object
'Use Right to check the rightmost char
'Append a slash at the end if needed
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'Create FileSystemObject object
Set Fso_Obj = CreateObject("Scripting.FileSystemObject")
Erase myFiles()
Fnum = 0
'Test if the folder exists and set RootFolder
If Fso_Obj.FolderExists(MyPath) = False Then
Exit Function
End If
Set RootFolder = Fso_Obj.GetFolder(MyPath)
'Fill the array(myFiles)with the list of Excel files in the folder(s)
'Loop through the files in the RootFolder
For Each file In RootFolder.Files
If LCase(file.Name) Like LCase(ExtStr) Then
Fnum = Fnum + 1
ReDim Preserve myFiles(1 To Fnum)
myFiles(Fnum) = MyPath & file.Name
End If
Next file
'Loop through the files in the Sub Folders if SubFolders = True
If Subfolders Then
Call ListFilesInSubfolders(OfFolder:=RootFolder, FileExt:=ExtStr)
End If
myReturnedFiles = myFiles
Get_File_Names = Fnum
End Function
Sub ListFilesInSubfolders(OfFolder As Object, FileExt As String)
Dim SubFolder As Object
Dim fileInSubfolder As Object
For Each SubFolder In OfFolder.Subfolders
ListFilesInSubfolders OfFolder:=SubFolder, FileExt:=FileExt
For Each fileInSubfolder In SubFolder.Files
If LCase(fileInSubfolder.Name) Like LCase(FileExt) Then
Fnum = Fnum + 1
ReDim Preserve myFiles(1 To Fnum)
myFiles(Fnum) = SubFolder & "\" & fileInSubfolder.Name
End If
Next fileInSubfolder
Next SubFolder
End Sub
Function RDB_Last(choice As Integer, rng As Range)
' 1 = last row
' 2 = last column
' 3 = last cell
Dim lrw As Long
Dim lcol As Integer
Select Case choice
Case 1:
On Error Resume Next
RDB_Last = rng.Find(What:="*", _
after:=rng.Cells(1), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
Case 2:
On Error Resume Next
RDB_Last = rng.Find(What:="*", _
after:=rng.Cells(1), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
Case 3:
On Error Resume Next
lrw = rng.Find(What:="*", _
after:=rng.Cells(1), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
On Error Resume Next
lcol = rng.Find(What:="*", _
after:=rng.Cells(1), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
On Error Resume Next
RDB_Last = rng.Parent.Cells(lrw, lcol).Address(False, False)
If Err.Number > 0 Then
RDB_Last = rng.Cells(1).Address(False, False)
Err.Clear
End If
On Error GoTo 0
End Select
End Function
'Call the Function "Get_File_Names" to fill a array with all file names
'There are three arguments that we can change
'MyPath = the folder where the files are
'Subfolders = True if you want to include subfolders
'ExtStr = file extension of the files you want to merge
'Use .xl for all
'Do not touch this line:myReturnedFiles:=myFiles
'FileNameInA = use True to add the path/file name in the A column of the combined sheet
'PasteAsValues = use True to paste as values
'SourceShName = sheet name, if "" it will use the SourceShIndex and if "all" it copy from all worksheets
'SourceShIndex = to avoid problems with different sheet names use the index (1 is the first worksheet)
'SourceRng = Range you want to copy. Ex:Specifying a range "A:F" will copy all cells with data in these six columns
'StartCell = Enter the first cell and the macro will copy from that cell to the last cell on the worksheet
'If StartCell = "" then it uses the SourceRng instead.
Sub RDB_Merge_Data()
Dim myFiles As Variant
Dim myCountOfFiles As Long
myCountOfFiles = Get_File_Names( _
MyPath:="C:\Users\", _
Subfolders:=False, _
ExtStr:="*.xl*", _
myReturnedFiles:=myFiles)
If myCountOfFiles = 0 Then
MsgBox "Could not find the files."
Exit Sub
End If
Get_Data _
FileNameInA:=False, _
PasteAsValues:=True, _
SourceShName:="all", _
SourceShIndex:=1, _
SourceRng:="A3:U120", _
StartCell:="", _
myReturnedFiles:=myFiles
End Sub
Sub RDB_Merge_Data_Browse()
Dim myFiles As Variant
Dim myCountOfFiles As Long
Dim oApp As Object
Dim oFolder As Variant
Set oApp = CreateObject("Shell.Application")
'Browse to the folder
Set oFolder = oApp.BrowseForFolder(0, "Select folder", 512)
If Not oFolder Is Nothing Then
myCountOfFiles = Get_File_Names( _
MyPath:=oFolder.Self.Path, _
Subfolders:=False, _
ExtStr:="*.xl*", _
myReturnedFiles:=myFiles)
If myCountOfFiles = 0 Then
MsgBox "No files that match the ExtStr in this folder"
Exit Sub
End If
Get_Data _
FileNameInA:=True, _
PasteAsValues:=True, _
SourceShName:="", _
SourceShIndex:=1, _
SourceRng:="A1:G1", _
StartCell:="", _
myReturnedFiles:=myFiles
End If
End Sub
' Note: Don't change this macro below.
' Only edit and run the RDB_Merge_Data above.
Sub Get_Data(FileNameInA As Boolean, PasteAsValues As Boolean, SourceShName As String, _
SourceShIndex As Integer, SourceRng As String, StartCell As String, myReturnedFiles As Variant)
Dim SourceRcount As Long
Dim SourceRange As Range, destrange As Range
Dim mybook As Workbook, BaseWks As Worksheet
Dim rnum As Long, CalcMode As Long
Dim SourceSh As Variant
Dim sh As Worksheet
Dim I As Long
'Change ScreenUpdating, Calculation and EnableEvents for improved performance, enable again when done.
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
'Add a new workbook with one sheet named "Combined Sheet"
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
BaseWks.Name = "Combined Sheet"
'Set start row for the Data
rnum = 1
'Check if we use a named sheet or the index
If SourceShName = "" Then
SourceSh = SourceShIndex
Else
SourceSh = SourceShName
End If
'Loop through all files in the array(myFiles)
For I = LBound(myReturnedFiles) To UBound(myReturnedFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(myReturnedFiles(I))
On Error GoTo 0
If Not mybook Is Nothing Then
If LCase(SourceShName) <> "all" Then
'Set SourceRange and check if it is a valid range
On Error Resume Next
'Dummy Proofing
If StartCell <> "" Then
With mybook.Sheets(SourceSh)
Set SourceRange = .Range(StartCell & ":" & RDB_Last(3, .Cells))
'Test if the row of the last cell >= then the row of the StartCell
If RDB_Last(1, .Cells) < .Range(StartCell).Row Then
Set SourceRange = Nothing
End If
End With
Else
With mybook.Sheets(SourceSh)
Set SourceRange = Application.Intersect(.UsedRange, .Range(SourceRng))
End With
End If
If Err.Number > 0 Then
Err.Clear
Set SourceRange = Nothing
Else
'if SourceRange use all columns then skip this file
If SourceRange.Columns.Count >= BaseWks.Columns.Count Then
Set SourceRange = Nothing
End If
End If
On Error GoTo 0
If Not SourceRange Is Nothing Then
'Error Checking: see if there enough rows to paste the data
SourceRcount = SourceRange.Rows.Count
If rnum + SourceRcount >= BaseWks.Rows.Count Then
MsgBox "Sorry there are not enough rows in the sheet to paste"
mybook.Close savechanges:=False
BaseWks.Parent.Close savechanges:=False
GoTo ExitTheSub
End If
'Set the destination cell
If FileNameInA = True Then
Set destrange = BaseWks.Range("B" & rnum)
With SourceRange
BaseWks.Cells(rnum, "A"). _
Resize(.Rows.Count).Value = myReturnedFiles(I)
End With
Else
Set destrange = BaseWks.Range("A" & rnum)
End If
'Copy/paste the data
If PasteAsValues = True Then
With SourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = SourceRange.Value
Else
SourceRange.Copy destrange
End If
rnum = rnum + SourceRcount
End If
'Close the workbook without saving
mybook.Close savechanges:=False
Else
'Loop through all sheets in mybook
For Each sh In mybook.Worksheets
'Set SourceRange and check if it is a valid range
On Error Resume Next
If StartCell <> "" Then
With sh
Set SourceRange = .Range(StartCell & ":" & RDB_Last(3, .Cells))
If RDB_Last(1, .Cells) < .Range(StartCell).Row Then
Set SourceRange = Nothing
End If
End With
Else
With sh
Set SourceRange = Application.Intersect(.UsedRange, .Range(SourceRng))
End With
End If
If Err.Number > 0 Then
Err.Clear
Set SourceRange = Nothing
Else
'if SourceRange use almost all columns then skip this file
If SourceRange.Columns.Count > BaseWks.Columns.Count - 2 Then
Set SourceRange = Nothing
End If
End If
On Error GoTo 0
If Not SourceRange Is Nothing Then
'Check if there enough rows to paste the data
SourceRcount = SourceRange.Rows.Count
If rnum + SourceRcount >= BaseWks.Rows.Count Then
MsgBox "Sorry there are not enough rows in the sheet to paste"
mybook.Close savechanges:=False
BaseWks.Parent.Close savechanges:=False
GoTo ExitTheSub
End If
'Set the destination cell
If FileNameInA = True Then
Set destrange = BaseWks.Range("C" & rnum)
With SourceRange
BaseWks.Cells(rnum, "A"). _
Resize(.Rows.Count).Value = myReturnedFiles(I)
BaseWks.Cells(rnum, "B"). _
Resize(.Rows.Count).Value = sh.Name
End With
Else
Set destrange = BaseWks.Range("A" & rnum)
End If
'Copy/paste the data
If PasteAsValues = True Then
With SourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = SourceRange.Value
Else
SourceRange.Copy destrange
End If
rnum = rnum + SourceRcount
End If
Next sh
'Close the workbook without saving
mybook.Close savechanges:=False
End If
End If
'Open the next workbook
Next I
'Set the column width in the new workbook
BaseWks.Columns.AutoFit
ExitTheSub:
'Restore ScreenUpdating, Calculation and EnableEvents now that we are done
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
Display More