+ Reply to Thread
Results 1 to 4 of 4

Basic Worksheet object creation

Hybrid View

  1. #1
    Registered User
    Join Date
    01-31-2008
    Posts
    3

    Basic Worksheet object creation

    Hi all -

    I am using Excel 2003 and have a very simple (in theory) macro that is supposed to display the name of the active sheet in a message box:

    Public Sub DisplayActiveSheetName()
        Dim worksheet1 As Excel.Worksheet
        worksheet1 = ThisWorkbook.ActiveSheet
        MsgBox ("The name of the active sheet is: " & worksheet1.Name)
    End Sub
    This code resides in a Module.
    When running this code, I receive the Run-time error '91' that the

        worksheet1 = ThisWorkbook.ActiveSheet
    line "Object Variable or With block variable not set."

    Any advice would be appreciated.

    Thanks!

  2. #2
    Forum Expert royUK's Avatar
    Join Date
    11-18-2003
    Location
    Derbyshire,UK
    MS-Off Ver
    Xp; 2007; 2010
    Posts
    26,200
    You need to use Set like this

    Option Explicit
    
    Public Sub DisplayActiveSheetName()
        Dim worksheet1 As Excel.Worksheet
        Set worksheet1 = ThisWorkbook.ActiveSheet
        MsgBox "The name of the active sheet is: " & worksheet1.Name
    End Sub
    Hope that helps.

    RoyUK
    --------
    For Excel Tips & Solutions, free examples and tutorials why not check out my web site

    Free DataBaseForm example

  3. #3
    Registered User
    Join Date
    01-31-2008
    Posts
    3
    Thanks!

    I'm new to VB, coming from a C/C++ background. Unfortunately navigating the msdn for info on Set in VB has been quite fruitless, probably because it's so basic - Can you explain the difference between using Set and a normal assignment? Does the Set command create a reference to the assigned object, as opposed to a copy? If so, why doesn't my previous code work, and just act inefficiently?



    Thanks again

  4. #4
    Forum Expert royUK's Avatar
    Join Date
    11-18-2003
    Location
    Derbyshire,UK
    MS-Off Ver
    Xp; 2007; 2010
    Posts
    26,200
    Basically you need to use Set with a Worksheet, Workbook or Range object - anything that you can actually write a value into. A String or numeric variable such as Long you don't use it.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1