2016-01-30 181 views
0

在執行下面的腳本時,我無法擺脫run time error 9VBA錯誤(9)下標超出範圍

我想要做的就是從表2搜索特定單元格的值,並在表1

這裏找到它的單元格區域是我的腳本:

Public output() As Variant 
Sub james() 
Dim J As Object 
Dim c As Object 

Sheet2.Activate 
ReDim ouput(3) 
Set J = Cells(1, 1) 

output(1) = J.Offset(0, 5).Value 
output(2) = J.Offset(30, 5).Value 
output(3) = J.Offset(60, 5).Value 

Sheet1.Activate 
Range("B7:B86").Select 
For Each c In Selection 
If c.Value = "output(1)" Then 
    Exit For 
End If 
Next c 
Rows(c.Row).Select 

End Sub 
+2

數組的索引從0開始,而不是1。第一個元素是'output(0)' – SearchAndResQ

+0

如果您很難繞過基於零的索引系統,請使用[Option Base 1](https://msdn.microsoft.com/en-us/library/ office/gg251511.aspx)放在模塊代碼表的聲明區域中。另請參閱[LBound](https://msdn.microsoft.com/en-us/library/t9a7w1ac(v = vs.90).aspx)和[UBound](https://msdn.microsoft.com/zh-cn/ -us/library/office/gg278658.aspx)函數。 – Jeeped

回答

0

@SearchAndResQ是沒錯,如果你想你的陣列從1開始,你有兩個選擇:在你的模塊開始

使用Option Base 1,或Redim output(1 to 3)

此外,你會想改變你的If語句:

If c.Value = output(1) then 

總而言之,這是一個更好版本的代碼:

Public output() As Variant 

Sub james() 
Dim J As Range 
Dim c As Range 

ReDim ouput(1 to 3) 
Set J = Sheet2.Cells(1, 1) 

output(1) = J.Offset(0, 5).Value 
output(2) = J.Offset(30, 5).Value 
output(3) = J.Offset(60, 5).Value 

For Each c In Sheet1.Range("B7:B86") 
    If c.Value = output(1) Then 
     Exit For 
    End If 
Next c 

Rows(c.Row).Select 

End Sub