简体   繁体   English

VBA下标超出范围和Excel的默认变量

[英]VBA subscript out of range and Excel's default variables

This is my first post on here and I have very little formal training in coding, so this is probably a very easy problem. 这是我在这里的第一篇文章,而且我几乎没有编码方面的正规培训,因此这可能是一个非常简单的问题。

I'm running into an error 9, VBA Subscript out of range, when running macros defined by the code below. 运行下面的代码定义的宏时,我遇到错误9,VBA下标超出范围。 Specifically, it is the Sub Select_Last() function. 具体来说,它是Sub Select_Last()函数。 Excel does not like the subsequent expression, however if this is used on its own in a separate Excel file then it works fine. Excel不喜欢其后的表达式,但是,如果在单独的Excel文件中单独使用它,则可以正常工作。

I think the problem is that Excel's default variable (Activesheet etc) are conflicting with each other. 我认为问题在于Excel的默认变量(Activesheet等)彼此冲突。 But I am not sure how to remedy this. 但是我不确定该如何解决。 The other subs work fine. 其他潜艇工作正常。 Can anyone help? 有人可以帮忙吗? Thank you. 谢谢。

Public lastsheet As String

Sub Select_Last()
   Sheets(lastsheet).Select
End Sub

Sub Protect()
   For i = 1 To Sheets.Count
      Sheets(i).Protect
   Next i
End Sub

Sub UnProtect()
   For i = 1 To Sheets.Count
      Sheets(i).UnProtect
   Next i
End Sub

Sub SelectUnlockedCells()
   Dim WorkRng As Range
   Dim OutRng As Range
   Dim Rng As Range
   On Error Resume Next
   Set WorkRng = Application.ActiveSheet.UsedRange
   Application.ScreenUpdating = False

   For Each Rng In WorkRng
     If Rng.Locked = False Then
        If OutRng.Count = 0 Then
          Set OutRng = Rng
        Else
          Set OutRng = Union(OutRng, Rng)
        End If
     End If
   Next
   If OutRng.Count > 0 Then OutRng.Select
     Application.ScreenUpdating = True
   End Sub

The other functions work OK. 其他功能正常。

Consider: 考虑:

Public lastsheet As String

Sub Select_Last()
    lastsheet = Sheets(Sheets.Count).Name
    Sheets(lastsheet).Select
End Sub

The key issue is to assign a value to a variable before using it. 关键问题是在使用变量之前为其分配值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM