I am struggling to pass a srcFile
variable from one sub to another. I would like to do the following:
1) load source file from my local path in loadFile() sub
2) Set srcFile as my source data workbook
3) I would like to call processWorkbook in my Main program so that it will take my srcFile, pass it to the Sub and do some actions on each worksheet of that file.
Apologies if I did not express myself clearly.
Sub Main()
Call loadFile
Call processWorkbook(srcFile)
End Sub
' _____________________________________________________
Sub loadFile()
Dim wrk As Worksheet
Dim trg As Worksheet
Dim Path As String
Dim srcFile As Workbook
Set wrk = Workbooks("Banks.xlsm").Sheets("Control")
Set trg = Workbooks("Banks.xlsm").Sheets("Output")
trg.Cells.ClearContents
Path = wrk.Cells(1, 2).Value 'file path
Set srcFile = Workbooks.Open(Path, ReadOnly:=False)
End Sub
' _____________________________________________________
Sub processWorkbook(wrk)
Dim sht As Worksheet
For Each sht In wrk.Sheets
Call anotherSub
Next sht
End Sub
The simplest way to do this is to declare a Workbook object in Sub Main
and populate it from loadFile
. There would be two ways this could be done: 1) Pass the Workbook object to loadFile by reference, or 2) Set the object from loadFile as an object.
I believe the second will be easier for you to understand, so I've used that to modify your code, as below.
Note that for this to work it was necessary to change loadFile
to be a function, rather than a sub. (A function returns something.) Also, I removed the Call
keyword from your code as this is no longer needed / used.
Sub Main()
Dim srcFile As Workbook
Set srcFile = loadFile
processWorkbook srcFile
End Sub
'_____________________________________________________
Function loadFile() as Workbook
Dim wrk As Worksheet
Dim trg As Worksheet
Dim Path As String
Dim srcFile As Workbook
Set wrk = Workbooks("Banks.xlsm").Sheets("Control")
Set trg = Workbooks("Banks.xlsm").Sheets("Output")
trg.Cells.ClearContents
Path = wrk.Cells(1, 2).Value 'file path
Set srcFile = Workbooks.Open(Path, ReadOnly:=False)
Set loadFile = srcFile
End Function
'_____________________________________________________
Sub processWorkbook(wrk)
Dim sht As Worksheet
For Each sht In wrk.Sheets
Call anotherSub
Next sht
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.