Excel VBA:运行时错误';13';尝试在列中循环时类型不匹配

Excel VBA:运行时错误';13';尝试在列中循环时类型不匹配,vba,Vba,大家早上好 我被难住了,为什么我在尝试使用For-each循环通过列a时会得到类型不匹配 Sub timeStart() Dim s As Worksheet Dim anchor As Range Dim i As Variant i = 2 Set s = Workbooks("ER911 CALLBACKS SHEET").Sheets("Time Log") For Each i In s.Range("A:A") If s.Cells(i, 1).Value = ""

大家早上好

我被难住了,为什么我在尝试使用For-each循环通过列a时会得到类型不匹配

Sub timeStart()
Dim s As Worksheet
Dim anchor As Range
Dim i As Variant

 i = 2

Set s = Workbooks("ER911 CALLBACKS SHEET").Sheets("Time Log")

For Each i In s.Range("A:A")
    If s.Cells(i, 1).Value = "" Then 'ERROR OCCURS HERE
        s.Cells(i, 1) = Date
        s.Cells(i, 1).Offset(0, 1) = InputBox("What is your name?")
        s.Cells(i, 1).Offset(0, 2) = InputBox("What program are you calling on?")
        s.Cells(i, 1).Offset(0, 3) = Time()

        Exit For


    End If
Next i
结束Sub

您的问题在这里:

For Each i In s.Range("A:A")
在这种情况下,每个
i
都是一个范围对象,表示序列中的下一个单元格

但是,您正试图将range对象用作
s.Cells(i,1)
中的一行。因此,您应该只使用您创建的范围对象:

For Each i In s.Range("A:A")
    If i.Value = "" Then 'ERROR OCCURS HERE
        i = Date
        i.Offset(0, 1) = InputBox("What is your name?")
        i.Offset(0, 2) = InputBox("What program are you calling on?")
        i.Offset(0, 3) = Time()    
        Exit For
    End If
Next i
如前所述,将
i
定义为一个范围会更安全,首先
Dim i作为范围
,然后您将确保始终正确使用i。然后,您需要删除
i=2
行,因为它不需要,实际上会导致不同的类型不匹配错误

另一个建议是将
i
重命名为更容易理解的名称,这样在6个月后阅读此代码时,我所代表的内容就会立即变得清晰。

只需简单地:

For i = 1 to N ' N = whatever the last row you wish to be
    If s.Cells(i, 1) = "" Then 
。。。等等


。。。等等

也应该使用
Dim i作为范围
谢谢您的建议。它现在正在工作。我得到一个424错误(需要对象),但当我设置I=s.cells(2,1)时,它就像一个符咒一样工作。@AlexK。我确实将dim I作为变体更改为dim I作为范围。
Dim rX as range
For Each rX in s.Range("A:A") ' WARNING! there are too many cells here in the column, BTW
    If rX = "" Then