+ Reply to Thread
Results 1 to 3 of 3

Thread: Selecting all cells in a worksheet using commandbutton

  1. #1
    Registered User
    Join Date
    06-01-2011
    Location
    norway
    MS-Off Ver
    Excel 2003
    Posts
    6

    Selecting all cells in a worksheet using commandbutton

    Something strange (at least for me).
    When I record a macro that selects all the cells in a workbook and clear all content the code looks like this:
    Sub Macro14()
     Sheets("Values to EIS").Select
     Cells.Select
        Selection.ClearContents
    End Sub
    This works fine. However when I have the same code inside a commandobutton it fails and gives me the error code "application-defined or object defined error". Anyone that knows why and how this can be done correct? I want this to be done within the commandbutton code.

    The code that fails looks like:
    Private Sub CommandButton2_Click()
        Sheets("Values to EIS").Select
       Cells.Select
        Selection.ClearContents
    End Sub

  2. #2
    Valued Forum Contributor vikas.bhandari's Avatar
    Join Date
    04-07-2006
    Location
    Delhi, India
    MS-Off Ver
    Office 2000,2003,2007 All Three
    Posts
    233

    Re: Selecting all cells in a worksheet using commandbutton

    I would do this :

    
    Private Sub Commandbutton1_Click()
        Dim sht As Worksheet
        
        Set sht = Worksheets("YourSheetName")
        sht.Cells.ClearContents
    End Sub

    This would work anytime, anywhere in your workbook.

    Thanks,
    Vikas

  3. #3
    Forum Guru romperstomper's Avatar
    Join Date
    11-04-2008
    Location
    Apparently I can't say
    MS-Off Ver
    Apparently I can't say
    Posts
    8,274

    Re: Selecting all cells in a worksheet using commandbutton

    As you aren't reusing the variable, you can just use:
    Sub Macro14()
     Sheets("Values to EIS").Cells.ClearContents
    End Sub
    or even:
    Sub Macro14()
     Sheets("Values to EIS").Usedrange.ClearContents
    End Sub

+ 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.2.0