在VBA中添加基本循环时会出现types不匹配

我有一个基本的If ElseIf语句,我试图循环几百行。 If / Else语句本身的工作,直到我尝试和循环(我已经包括下面)。 当我运行它,它给我一个运行时错误“13”型不匹配。 我最初设置MyCell作为一个String直到我有这个错误出现。 然后我认为设置MyCell作为Variant我可以避免这种情况,但它仍然返回RTE 13。

 Sub code_reassign() Dim Count As Integer Dim MyCell As Variant Count = 1 Do While Count < 10 MyCell = ActiveCell.Value If MyCell = "Busycotypus canaliculatus" Then ActiveCell.Offset(0, -1).Value = "N106" ElseIf MyCell = "Busycon carica" Then ActiveCell.Offset(0, -1).Value = "N104" ElseIf MyCell = "Busycon perversum" Or "Busycon sinistrum" Then ActiveCell.Offset(0, -1).Value = "N103" ElseIf MyCell = "Busycotypus spiratus" Then ActiveCell.Offset(0, -1).Value = "N107" Else End If ActiveCell.Offset(1, 0).Select Count = Count + 1 Loop End Sub 

我仍然是VBA的超级新手,但在工作中已经陷入了深度。 我正在尽我所能,在晚上在家学习基本知识,努力追上。 任何有关为什么循环正在创build一个不匹配的问题的洞察力将不胜感激。

更改

 ElseIf MyCell = "Busycon perversum" Or "Busycon sinistrum" Then 

 ElseIf MyCell = "Busycon perversum" Or MyCell = "Busycon sinistrum" Then 

使用Or时需要完整的expression式。

因为你是新的,使用。select这可能是一个很好的阅读,当你有时间: 如何避免使用在Excel中selectVBAmacros

@ Sobigen的答案是一个很好的答案,但如果循环失败,我的预感是Count是一个保留字。 将variablesCount更改为其他值。

Sobigen的答案应该解决不匹配错误。 这里有一些帮助清理这些代码。 每当我有超过2或3个条件,我发现Select CaseIf/ElseIf/ElseIf更可取。 您的里程可能会有所不同,但是我发现阅读和解读更容易,尤其是当您有Or条件时, Case开关将允许多个值。

另外,既然你有一个已知的循环,没有理由使用Do While而不是For ... Next

 Sub code_reassign() Dim i As Integer Dim MyCell As Range Set MyCell = ActiveCell For i = 1 to 10 Select Case MyCell.Value Case "Busycotypus canaliculatus" MyCell.Offset(0, -1).Value = "N106" Case "Busycon carica" MyCell.Offset(0, -1).Value = "N104" Case "Busycon perversum", "Busycon sinistrum" MyCell.Offset(0, -1).Value = "N103" Case "Busycotypus spiratus" MyCell.Offset(0, -1).Value = "N107" End Select Set MyCell = MyCell.Offset(1, 0) Loop End Sub