Results 1 to 6 of 6

VBA to check for active sheet then execute following code

Threaded View

  1. #1
    Forum Contributor Pierce Quality's Avatar
    Join Date
    07-29-2013
    Location
    USA
    MS-Off Ver
    Excel 2010
    Posts
    221

    VBA to check for active sheet then execute following code

    Hi All,

    Im having a little trouble with getting this code to work correctly and was wondering if someone could point me in the right direction.
    Here is the code that I am using:

    Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    With Range("A1:I" & Cells(Rows.Count, 2).End(xlUp).Row)
        .Sort Key1:=.Cells(1, 2), Order1:=xlAscending, _
              Key2:=.Cells(1, 7), Order2:=xlAscending, Header:=xlYes
        Cells(.Rows.Count + 1, 1).Select
    End With
    End Sub
    Which works great as is. Basically it sorts my data, then selects the first empty cell when the user saves the workbook.
    However, now I have more than one sheet in the book, so if the user is on another sheet then saves the book he starts getting errors.
    So I wanted to get the sort to only execute if Sheet1 is active, and heres what I added:

    Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    If ActiveSheet.Name = "Sheet1" Then
    With Range("A1:I" & Cells(Rows.Count, 2).End(xlUp).Row)
        .Sort Key1:=.Cells(1, 2), Order1:=xlAscending, _
              Key2:=.Cells(1, 7), Order2:=xlAscending, Header:=xlYes
        Cells(.Rows.Count + 1, 1).Select
    
    End With
    
    End If
    
    End Sub
    Which will save the book but doesnt perform the sort or cell selection after.
    Any help with this would be greatly appreciated, thanks!
    Last edited by Pierce Quality; 11-12-2013 at 11:19 AM.

Thread Information

Users Browsing this Thread

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

Similar Threads

  1. Code to clear check box fails to execute
    By brharrii in forum Excel Programming / VBA / Macros
    Replies: 5
    Last Post: 06-18-2013, 03:51 PM
  2. Need to check if worksheet exists and execute code
    By chiidzzz in forum Excel Programming / VBA / Macros
    Replies: 9
    Last Post: 09-25-2012, 08:55 PM
  3. Need code to check for duplicates of active cell
    By davekippen in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 08-21-2011, 09:38 AM
  4. Code will only execute from one sheet
    By kirsty in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 05-12-2011, 07:07 PM
  5. Need VBA sheet code to execute when a row is delete
    By mikeburg in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 09-11-2006, 12:46 PM

Tags for this Thread

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