2012-10-02 132 views
1

由于某些原因,当我执行下面的代码时,出现'Runtime 13'错误。For循环中运行时错误13

Dim N_1 As Variant 

Worksheets("Trucks").Activate 
Range("G9").Activate 

Do Until ActiveCell.Value = "" 
ActiveCell.Offset(1, 0).Select 
If ActiveCell.Value = "" Then Exit Do 
Loop 

ActiveCell.Offset(-1, 0).Select 
N_1 = Range(ActiveCell, "G9") 

With CreateObject("scripting.dictionary") 
    .comparemode = vbTextCompare 
    For Each v1 In N_1 
     If Not IsEmpty(v1) Then 
      If Not .exists(v1) Then .Add v1, Nothing 
     End If 
    Next 
    z1 = .keys 
End With 

回答

0

Range(...)返回一个对象类型,从而Set必须使用:

Set N_1 = Range(ActiveCell, "G9")


虽然Range(...)并返回一个对象类型,将其分配给Variant而不使用Set产生2D变体该范围内单元格值的数组。这适用于For Each v1 in N_1部分和IsEmpty(v1)部分。

因此,我不是100%肯定,为什么你在第一时间(假设v1z1也被宣布为Variant)得到了错误13。事实上,如果你使用Set,你还必须改变你的循环,其填充使用的v1.Value而不只是v1

字典如果您在随后使用N_1并期望它是一个Range对象,然后这可以解释的事情,但如上所解释的代码,如果一切都被声明为Variant运行对我来说OK:

Excel screenshot showing the code from the question running without errors

+0

美丽,感谢堆! – Delta

+0

其实,我不确定这个答案对你有帮助。我会在编辑中解释 – barrowc