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:

  1. Sub thiswrkbook()
  2. ThisWorkbook.Sheets(1).Range("K10") = "test"
  3. ThisWorkbook.Sheets(1).Range("K11") = "test"
  4. ThisWorkbook.Sheets(1).Range("K12") = "test"
  5. ThisWorkbook.Sheets(1).Range("K13") = "test"
  6. ThisWorkbook.Sheets(1).Range("K14") = "test"
  7. ThisWorkbook.Sheets(1).Range("K15") = "test"
  8. MsgBox "All values in K set through ThisWorkbook property"
  9. For i = 10 To 15
  10. ThisWorkbook.Sheets(1).Range("K" & CStr(i)) = ""
  11. Next i
  12. End Sub

A screenshot from the editor is as shown below:

excel vba thisworkbook

The output is as shown below:

excel vba thisworkbook

 

You can find similar Excel Questions and Answer hereunder

1) Vba code to password protect workbook in Excel

2) How to do workbook protection with VBA in Excel

3) I want to automatically run a procedure whenever I close my WorkBook so that it is in a known state - how can I achieve that?

4) Calling a macro from another workbook in Excel

5) How to protect your workbook in Excel

6) I want to automatically run an initialization procedure whenever I open my WorkBook so that it is ready for use - how can I achieve that?

7) I have a WorkBook that loads a form automatically when it is opened. In Excel, how can I suppress the form from loading on file open when required?

8) How can I save a WorkSheet as a new WorkBook using VBA?

9) How do I disable the right click option for users in my WorkBook?

10) How do you close, save, open files and do other operations in the workbook in VBA

 

Here the previous and next chapter