VBA Declare Assign Workbook Object to a Variable in Excel. We can declare and assign any object to a variable. You can use Set statement to assign Workbook Object to a variable. Declared and assigned variable can be used in an entire procedure or macro.
Let us see the following example. Here ‘oWorkbook’ is a declared Workbook object. It helps to assign Workbook Variable to an object in Excel VBA.
'VBA Declare Assign Workbook object to a Variable in Excel Sub VBA_declare_Assign_Workbook_Variable() 'Variable declaration Dim oWorkbook As Workbook Dim sFilePath As String 'Assign File Path to string variable sFilePath = "D:\VBAF1\VBA Functionsa.xlsm" 'Assign Object variable to a value Set oWorkbook = Workbooks.Open(sFilePath) End Sub
In the above example ‘oWorkbook’ is an workbook object assigned to variable. And ‘sFilePath’ represents the Workbook name.
Here are the instructions to use above macro procedure in Visual basic editor.
- Open Visual Basic Editor(VBE) by clicking Alt +F11
- Go to code window by clicking F7
- Copy above specified macro or procedure
- Paste above copied code in code window
- Run macro by clicking F5 or Run command
- You can see output on the screen
- Find above output screenshot of the specified procedure.
You may also like the related Workbook Object articles.