Posts on this page


Saturday, June 21, 2014

Although Excel VBA does not have Thisworksheet object, we can utilize ActiveSheet and Me, instead.

You may easily find out ThisWorkbook, ActiveWorkbook and ActiveSheet Object when you code excel VBA, but there is no ThisWorksheet Object.

Instead you should use Activesheet Object when you code in the standard module.
Following code is for check the value of Activesheet Object. Use it in the standard module.

If you want to use the word ThisWorksheet itself, you can use Set statement to keep contents of Activesheet before it changes by selecting another sheet, for example.

The code below will prompt sheet name before and after Activesheet is changed.

Sub testActiveSheet
   Set ThisWorksheet = ActiveSheet
   Msgbox "ActiveSheet is " & ActiveSheet.Name
   Msgbox "ThisWorksheet is " & ThisWorksheet.Name

   ActiveSheet.Next.Activate

   Msgbox "ActiveSheet is " & ActiveSheet.Name
   Msgbox "ThisWorksheet is " & ThisWorksheet.Name
End Sub

When you code on sheet module, you may use Me keyword. Me indicates the scope which code runs itself, Me.Name is still Sheet1 even after Activesheet is changed from Sheet1 to Sheet2(if following code is in Sheet1 module).

In addition, Me keyword can be used only in class module, Me keyword in standard module will fire error.

Sub testMe
   Set ThisWorksheet = ActiveSheet
   Msgbox "ActiveSheet is " & ActiveSheet.Name
   Msgbox "ThisWorksheet is " & ThisWorksheet.Name

   Msgbox "Me is " & Me.Name

   ActiveSheet.Next.Activate

   Msgbox "ActiveSheet is " & ActiveSheet.Name
   Msgbox "ThisWorksheet is " & ThisWorksheet.Name

   Msgbox "Me is " & Me.Name
End Sub