Martin
Martin

Reputation: 11

Excel/VBA Why do I get run time error 438 using public variables of workbook and worksheet

I'm trying to learn some VBA and in my current project I wanted to learn about using different sub routines so I created a sub to open a CSV file. I wanted to be able to reference the workbook/worksheet in other sub routines so I defined the variables as public. This works fine on it's own and the message box shows the expected values for bankWS and bankWS

Public bankWB As Workbook 
Public bankWS As Worksheet 

Sub OpenCSV()
filepath = "C:\" 
csvfile = "file.csv" 
Workbooks.Open Filename:=filepath & csvfile 
Set bankWB = ActiveWorkbook 
Set bankWS = ActiveSheet 
MsgBox "Active WB is " & bankWB.Name & " Active WS is " & bankWS.Name 
End Sub

But when I try to reference these variables from a different sub I get run time error 438 Object doesn't support this property or Method.

Sub Main()
Call OpenCSV
MsgBox "Active WB is " & bankWB
MsgBox " Active WS is " & bankWS
End Sub

I thought the whole point of defining the variable globally was that I would be able to use it outside of the subroutine.

Reading around this error I see that often it occurs when the code is trying to use a particular object (eg worksheet.something) but I think I'm duplicating the msgbox command that worked fine within the sub. I'm stuck now and can't find out what have I done wrong. I would like to understand, why this error occurs?

Regards

Upvotes: 0

Views: 1136

Answers (1)

Gary's Student
Gary's Student

Reputation: 96753

Sub Main()
Call OpenCSV
MsgBox "Active WB is " & bankWB.Name
MsgBox " Active WS is " & bankWS.Name
End Sub

Upvotes: 0

Related Questions