简体   繁体   English

VBA中If函数的下标超出范围

[英]Subscript out of range for If function in VBA

I'm doing a payroll application and I keep getting this message when trying to do an if function for a VBA script. 我正在做一个薪资应用程序,尝试为VBA脚本执行if函数时,我总是收到此消息。

Its the first line of the If statement that is giving me a hard time. 这是If语句的第一行,这让我很难受。

Sub PayPeriod()
    If Sheets("sheet30").Range("e17") = "1" Then 'ERROR HERE
        Sheets("Week 1").Select
    ElseIf Sheets("sheet30").Range("e17") = "2" Then
        Sheets("Week 2").Select
    ElseIf Sheets("sheet30").Range("e17") = "3" Then
        Sheets("Week 3").Select
    ElseIf Sheets("sheet30").Range("e17") = "4" Then
    End If
End Sub

Try using variables and declare them properly. 尝试使用变量并正确声明它们。 You need to qualify the sheet location. 您需要限定工作表位置。 Declare variables at the top, assign them the desired values once and then use the variable in your code. 在顶部声明变量,为它们分配一次所需的值,然后在代码中使用该变量。 This way, if sheet names or cell references change, you can quickly adjust the macro in just one place. 这样,如果工作表名称或单元格引用发生更改,则可以在一个位置快速调整宏。 (I've left the .Select statement in the example, but note that you hardly ever need to select elements to work with them. (我在示例中保留了.Select语句,但是请注意,您几乎不需要选择要使用的元素。

Option Explicit

Sub PayPeriod()

Dim ws As Worksheet
Dim rng As Range
Set ws = ThisWorkbook.Sheets("Sheet30")
Set rng = ws.Range("E17")

If rng = "1" Then
   ws.Range("Week1").Select

    [rest of your code]

End Sub

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

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