VBA thisworkbook in Excel
ThisWorkbook property returns a Workbook object that represents a workbook where the code is executing.
This returns a Read-Only object.
Thisworkbook property can be used to to refer to the workbook that contains your macro code.
Thisworkbook property is the only way to refer to an add-in workbook from inside the add-in itself.
To understand the above point, while creating an Add-in, the workbook's name may change, so by using "Thisworkbook", the same workbook is always referenced irrespective of its name.
The following example illustates this property:
- Sub thiswrkbook()
- ThisWorkbook.Sheets(1).Range("K10") = "test"
- ThisWorkbook.Sheets(1).Range("K11") = "test"
- ThisWorkbook.Sheets(1).Range("K12") = "test"
- ThisWorkbook.Sheets(1).Range("K13") = "test"
- ThisWorkbook.Sheets(1).Range("K14") = "test"
- ThisWorkbook.Sheets(1).Range("K15") = "test"
- MsgBox "All values in K set through ThisWorkbook property"
- For i = 10 To 15
- ThisWorkbook.Sheets(1).Range("K" & CStr(i)) = ""
- Next i
- End Sub
A screenshot from the editor is as shown below:
The output is as shown below: