I am creating a function that reads column titles from two excel files and then place those column titles in checkboxes so the user can check which columns he will work with
Subscript out of Range error arises in these circumstances when the specified sheetname does not exist in that workbooks Worksheets
collection.
I notice you have two open workbooks specified by:
Workbooks.Open Filename:=SPathName & "\" & SFilename
Workbooks.Open Filename:=JPathName & "\" & JFilename
However, both of your worksheet assignments refer only to the ActiveWorkbook
.
The cause of the error is certainly that SheetName2
does not exist in the ActiveWorkbok
(which is specified by JFilename
)
Especially when working with multiple books or worksheets, it is always preferable to avoid using Activate/Select methods-- otherwise you need to keep track of which workbook/worksheet/etc. is "Active", and that makes for spaghetti code and lots of unnecessary calls to the .Activate
method.
I know that SheetName1
exists in JFilename
, and I am assuming that SheetName2
exist in the workbook SFileName
.
Instead, define two Workbook
variables:
Dim wb1 as Workbook
Dim wb2 as Workbook
Assign the results of the Workbooks.Open
method to these workbooks:
Set wb2 = Workbooks.Open(Filename:=SPathName & "\" & SFilename)
Set wb1 = Workbooks.Open(Filename:=JPathName & "\" & JFilename)
Now, wb1
is the "Active" workbook, so with the worksheet assignments:
Set wks1 = wb1.Worksheets(SheetName1)
And later for the Sheetname2
:
Set wks2 = wb2.Worksheets(Sheetname2)
Otherwise, there is a typo in your worksheet names or the string parameters you're sending to this function. Doublecheck/debug that the value of SheetName2
is correct and that it exists.