填充单元格时,我在几个单元格的 运行 之后收到运行时错误 13

when populating cells I get a Runtime error 13 after running for a few cells

我正在尝试构建一个代码,以帮助我根据另一个工作表中的 2 个不同表格使用团队名称填充列表。

前 10 个单元格的代码实际上运行得很好,然后我突然收到运行时错误 13“类型不匹配”,我不知道它出了什么问题

我的密码是

Sub populateteam()

Dim wsAkasaka As Worksheet
Dim wsList As Worksheet

Set wsAkasaka = ThisWorkbook.Worksheets("Akasaka")
Set wsList = ThisWorkbook.Worksheets("All Japan")

Dim consultant As String
Dim manager As String
Dim team As String

consultant = wsAkasaka.Range("b" & (ActiveCell.Row)).Value
manager = Application.VLookup(consultant, wsList.Range("a13:c200"), 3, False)
team = Application.VLookup(manager, wsList.Range("E2:F11"), 2, False)

If IsEmpty(ActiveCell.Value) Then
ActiveCell.Value = team
ActiveCell.Offset(1, 0).Select

End If


End Sub

如果有人能告诉我为什么会这样,我该如何解决。

问题是您定义变量 As String,如果您的 VLookup returns 出现错误(如果 VLookup 找不到任何东西),则此错误无法转换为 String 并且您会得到 不匹配错误 .

因此我推荐如下:

' your code here …

Dim consultant As String
consultant = wsAkasaka.Range("b" & (ActiveCell.Row)).Value

Dim manager As Variant
manager = Application.VLookup(consultant, wsList.Range("a13:c200"), 3, False)

If IsError(manager) Then  ' check if consultant was found, if not exit
    MsgBox "Consultant """ & consultant & """ not found."
    Exit Sub
End If

Dim team As Variant
team = Application.VLookup(manager, wsList.Range("E2:F11"), 2, False)

If IsError(team) Then  ' check if manager was found, if not exit
    MsgBox "Manager """ & manager & """ not found."
    Exit Sub
End If

' your code here …