+ Reply to Thread
Results 1 to 2 of 2

run time error 9, subscript out of range

  1. #1

    run time error 9, subscript out of range

    Someone please help me with this. When I run this script, it works
    fine with some of the sheets but then gives the error for some. It
    stops at the For loop and says "subscript out of range".
    Sub lock_protect()
    Dim pass
    Dim sheet_name
    pass = "hiacsc"
    sheet_name = InputBox("Enter the sheet name")
    Dim cell As Range
    For Each cell In Sheets(sheet_name).UsedRange.Cells
    If cell.HasFormula = True Then
    If cell.MergeCells = True Then
    With cell.MergeArea
    .Locked = True
    End With
    Else
    cell.Locked = True
    End If
    End If
    Next cell
    Sheets(sheet_name).Protect (pass)
    MsgBox (sheet_name + " is protected now")
    End Sub


  2. #2
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258
    Hello Nasir,

    If the worksheet name the user enters does not exist, you will get this error. You can trap this error and alert the user that the worksheet name is invalid.

    Sub lock_protect()
    Dim pass
    Dim sheet_name
    Dim cell As Range
    Dim wks As Worksheet
    pass = "hiacsc"
    sheet_name = InputBox("Enter the sheet name")
    If sheet_name = "" Then Exit Sub
    On Error Resume Next
    Set wks = Sheets(sheet_name)
    If err.number <> 0 Then
    MsgBox "Error - invalid sheet name entered."
    Exit Sub
    End If
    For Each cell In wks.UsedRange.Cells
    If cell.HasFormula = True Then
    If cell.MergeCells = True Then
    With cell.MergeArea
    .Locked = True
    End With
    Else
    cell.Locked = True
    End If
    End If
    Next cell
    wks.Protect (pass)
    MsgBox (sheet_name + " is protected now")
    End Sub

    Sincerely,
    Leith Ross

+ 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