下标超出范围(错误9)

时间:2013-09-11 11:21:53

标签: excel-vba vba excel

SourceBook = ActiveWorkbook.Name

SourceSheet = Workbooks(SourceBook).Worksheets(2).Name

If Workbooks(SourceBook).Sheets(SourceSheet).Range("B10") = "SM" Then
    Workbooks(SourceBook).Worksheets(SourceSheet).Range("D11:D3000,K11:K3000,N11:AC3000,CX11:CX3000,DD11:DD3000").Select
    Selection.Copy

当我输入上面的代码时,我得到了结果。 但后来,当我输入代码时,

ElseIf Workbooks(SourceWorkbook).Sheets(SourceSheet).Range("B1") = "Status" Then
    MsgBox ("okay....")

显示"Subscript out of range (Error 9)".

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

你有一个错字。它应该是SourceBook而不是SourceWorkbook

这也是一种非常复杂的做事方式。试试这个。

Sub Sample()
    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = ActiveWorkbook '<~~ OR ThisWorkbook?
    Set ws = wb.Sheets(2)     

    If ws.Range("B10").Value = "SM" Then
        ws.Range("D11:D3000,K11:K3000,N11:AC3000,CX11:CX3000,DD11:DD3000").Copy
    ElseIf ws.Range("B1").Value = "Status" Then
        MsgBox ("okay....")
    End If
End Sub