Forum Discussion
Rudrabhadra
Jan 23, 2023Brass Contributor
Understanding the code
Hi Goodmorning
Appreciate if someone could help me understand the code (found from some website)
The last 4 lines of code highlighted in red. Please guide what it does.
Thanks ...
Sub MergeExcelFiles()
Dim fnameList, fnameCurFile As Variant
Dim countFiles, countSheets As Integer
Dim wksCurSheet As Worksheet
Dim wbkCurBook, wbkSrcBook As Workbook
fnameList = Application.GetOpenFilename(FileFilter:="Microsoft Excel Workbooks (*.xls;*.xlsx;*.xlsm),*.xls;*.xlsx;*.xlsm", Title:="Choose Excel files to merge", MultiSelect:=True)
If (vbBoolean <> VarType(fnameList)) Then
If (UBound(fnameList) > 0) Then
countFiles = 0
countSheets = 0
GetOpenFileName with MultiSelect:=True can return two completely different types of values:
- If the user selects one or more files and clicks Open, it returns an array of string values. Each item of the array is the path + filename of one of he selected files. VarType(fNameList) will be vbArray+vbString.
- If the user clicks Cancel, it returns the Boolean value False. VarType(fNameList) will be vbBoolean.
So the line If (vbBoolean <> VarType(fnameList)) Then checks that fNameList is not a Boolean, i.e. it must be an array.
The next line If (UBound(fnameList) > 0) Then will only be executed if the user clicked Open. It checks that the fNameList array has more than 0 items. This line is actually not necessary, if the user clicked Open they have selected at least one file.
I assume that the code below that loops through the selected file names, opens each workbook in turn, then loops through the sheets of the workbook. The lines
countFiles = 0
countSheets = 0
initialize the count of files (workbooks) and of sheets to 0.
GetOpenFileName with MultiSelect:=True can return two completely different types of values:
- If the user selects one or more files and clicks Open, it returns an array of string values. Each item of the array is the path + filename of one of he selected files. VarType(fNameList) will be vbArray+vbString.
- If the user clicks Cancel, it returns the Boolean value False. VarType(fNameList) will be vbBoolean.
So the line If (vbBoolean <> VarType(fnameList)) Then checks that fNameList is not a Boolean, i.e. it must be an array.
The next line If (UBound(fnameList) > 0) Then will only be executed if the user clicked Open. It checks that the fNameList array has more than 0 items. This line is actually not necessary, if the user clicked Open they have selected at least one file.
I assume that the code below that loops through the selected file names, opens each workbook in turn, then loops through the sheets of the workbook. The lines
countFiles = 0
countSheets = 0
initialize the count of files (workbooks) and of sheets to 0.
- RudrabhadraBrass ContributorThanks for your response and your guidance.