我有一个基本的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的新手,但在工作中被抛到深处。我尽我所能,晚上在家学习基础知识,努力追赶。任何关于循环为什么会产生不匹配问题的见解都将受到高度赞赏。
答案 0 :(得分:1)
更改
ElseIf MyCell = "Busycon perversum" Or "Busycon sinistrum" Then
到
ElseIf MyCell = "Busycon perversum" Or MyCell = "Busycon sinistrum" Then
使用Or时需要完整的表达式。
因为你是新手并且正在使用。选择这个,如果你有时间,这可能是一个很好的阅读: How to avoid using Select in Excel VBA macros
答案 1 :(得分:0)
@Sobigen的答案很好但是如果循环失败,我的预感是Count
是一个保留字。将变量Count
更改为其他内容。
答案 2 :(得分:0)
Sobigen的答案应该解决Mismatch错误。这里有一些帮助来清理这段代码。每当我有超过2或3个条件时,我发现Select Case
优于If/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