You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA跨工作表匹配数据时触发Type Mismatch错误求助

解决VBA类型不匹配错误:你误用了And运算符

嘿,我一眼就瞅出问题所在了——你把逻辑运算符And用错地方啦!这就是触发"Type Mismatch"错误的根源。

错误原因解析

在VBA里,And是用来连接条件判断表达式的(比如If A=1 And B=2 Then...),但你现在把它当成了串联执行语句的工具。你的代码写法相当于让VBA去计算「sh2.Range("C" & x + 3).Value = sh1.Range("A" & x).Value这个赋值操作的结果」和「sh2.Range("D" & x + 3) = "OWNER"这个赋值操作的结果」的逻辑与,但赋值语句返回的是被赋予的值(可能是文本、数字等),和And要求的布尔值(True/False)类型不匹配,自然就报错了。

修正后的代码

我们可以用两种方式修复这个语法问题:

方式1:用冒号分隔同一行的多个执行语句

Sub ind_access_report()
 Dim lastrow As Long ' 行号用Long类型更合适,避免Variant的性能问题
 Dim sh1 As Worksheet
 Dim sh2 As Worksheet
 Dim x As Long
 Dim iName As String
 Set sh1 = ActiveWorkbook.Sheets("Sheet1")
 Set sh2 = ActiveWorkbook.Sheets("Sheet2")
 iName = sh2.Range("A2").Value
 lastrow = sh1.Cells(Rows.Count, "A").End(xlUp).Row
 
 For x = 2 To lastrow
    ' 用冒号分隔多个执行语句,替代错误的And
    If sh1.Range("C" & x).Value = iName Then 
        sh2.Range("C" & x + 3).Value = sh1.Range("A" & x).Value: sh2.Range("D" & x + 3) = "OWNER"
    End If
    If sh1.Range("D" & x).Value = iName Then 
        sh2.Range("C" & x + 3).Value = sh1.Range("A" & x).Value: sh2.Range("D" & x + 3) = "BACKUP"
    End If
    If sh1.Range("E" & x).Value = iName Then 
        sh2.Range("C" & x + 3).Value = sh1.Range("A" & x).Value: sh2.Range("D" & x + 3) = "BACKUP"
    End If
 Next x
End Sub

方式2:使用块级If...End If结构(更易读,推荐)

这种写法代码结构更清晰,后续维护也更方便:

Sub ind_access_report()
 Dim lastrow As Long
 Dim sh1 As Worksheet
 Dim sh2 As Worksheet
 Dim x As Long
 Dim iName As String
 Set sh1 = ActiveWorkbook.Sheets("Sheet1")
 Set sh2 = ActiveWorkbook.Sheets("Sheet2")
 iName = sh2.Range("A2").Value
 lastrow = sh1.Cells(Rows.Count, "A").End(xlUp).Row
 
 For x = 2 To lastrow
    If sh1.Range("C" & x).Value = iName Then
        sh2.Range("C" & x + 3).Value = sh1.Range("A" & x).Value
        sh2.Range("D" & x + 3) = "OWNER"
    End If
    
    If sh1.Range("D" & x).Value = iName Then
        sh2.Range("C" & x + 3).Value = sh1.Range("A" & x).Value
        sh2.Range("D" & x + 3) = "BACKUP"
    End If
    
    If sh1.Range("E" & x).Value = iName Then
        sh2.Range("C" & x + 3).Value = sh1.Range("A" & x).Value
        sh2.Range("D" & x + 3) = "BACKUP"
    End If
 Next x
End Sub

额外优化建议

  • 把lastrow和x的类型从Variant改成Long:因为Excel的行号是整数,用Long类型更高效,也避免不必要的类型转换。
  • 可以考虑给单元格引用加上Value(比如sh2.Range("D" & x + 3).Value = "OWNER"),虽然VBA会默认读取/写入Value属性,但显式写出来更清晰。

内容的提问来源于stack exchange,提问作者Rhyfelwr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:52:21