I want to pass two objects (one open workbook and other a table) from sub procedure to userform. I have made both of them global before the sub.
- When I write just the two public declarations before Sub (they are set inside Sub),works good within Sub but when the userform initializes, it throws the error "Object variable or with block variable not set"
Public N As Workbook
Public E As ListObject
Sub...
- I tried to set these two objects before Sub, the Sub doesn't run, throws compile error, "Invalid outside procedure"
Public N As Workbook
Set N = Workbooks.Open(ThisWorkbook.Sheets("New").Range("A1").Text)
Public E As ListObject
Set E = N.Sheets(1).ListObjects(1)
Sub...
How to pass object variables from Sub procedures to Userforms? Currently the only solution I see is to set the objects in both the Sub procedure and the Userform.
Public
variable, for the scope you described, must be declared on top of a standard module (in the declarations area). Then, it must be set in a Sub. After having a value it can be called from the UserForm code. – FaneDuruPrivate
at the user form module level and define it during the form initializationSet wb = Workbooks("MyWorkbook")
. You can also create public variables in the form and initialized them from the standard module Sub (MyForm.wb = Workbooks("MyWorkbook")
. But if you need the specific workbook in many places, the way you tried looks the most appropriate. – FaneDuruIf N is Nothing then set N = Workbooks("MyWorkbook.xlsx")
. Or make aPublic Sub
in a standard module and call it:Sub VarInitialization()
Set N = Workbooks(ThisWorkbook.Sheets("New").Range("A1").Text)
Set E = N.Sheets(1).ListObjects(1)
End Sub
. And use this variant in the next way:If N is Nothing then VarInitialization
. – FaneDuru