ThisWorkbook vs ActiveWorkbook

February 14, 2012 by datapig Leave a reply »

Ganesh wrote into the DataPig hotline to ask:

“Mr. DataPig, Can you tell me what is the difference between ThisWorkbook and ActiveWorkbook?”

.

Anything for one of my 12 fans!

.

ThisWorkBook object refers to the workbook that the code is contained in. ActiveWorkBook object refers to the workbook that is currently active.

Most times, they will refer to the same workbook. But if the workbook running the code is not the active workbook then they will point to different objects.

.

Take this example code, where I’m deleting all but the active worksheet.

For Each ws In ThisWorkbook.Worksheets
If ws.Name <> ThisWorkbook.ActiveSheet.Name Then
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws

In this case, I don’t want to risk deleting sheets in other workbooks, so I use ThisWorkBook.

.

I hope that clears it up Ganesh; thanks for the question.

Now I’m craving chocolate ganache.

Advertisement

3 Responses

  1. noone says:

    That code will not work.
    You have to insert a line between line 1 and 2 with the code
    ws.Activate

  2. noone says:

    Although it WILL work if the last sheet in the workbook is activated at the start. But not if any of the others are…

  3. jon says:

    Some macros being launched from visual basic editor, i use this snippet to ensure i’m not overwriting a workbook that was manually misactivated

    Public Function bExecute() As Boolean
    ‘ Vérifier que le classeur appelant soit actif.
    ‘ Checking is calling workbook is the active one.
    bExecute = (ThisWorkbook.Name = ActiveWorkbook.Name)
    End Function

    sub demo
    If Not bExecute Then end
    … continue
    end sub

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy this password:

* Type or paste password here:

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>