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

如何对比单元格值与ComboBox选项?解决运行时错误'13'类型不匹配

解决VBA运行时错误'13':类型不匹配

错误原因

触发错误的语句If Cells(C + 1, 1) Like ComboBox4 Then存在两个核心问题:

  • 直接调用ComboBox4时,实际引用的是控件对象本身,而非用户选中的值,正确写法应为ComboBox4.Value
  • Like运算符要求两侧操作数均为字符串类型,若Cells(C+1,1)存储的是数值,会因类型不匹配触发错误

修正后的代码

Private Sub UserForm_Initialize()
    ComboBox3.List = [ADMIN!e2:E1000].Value
    ComboBox4.List = [PRODUCTION!O6:O1000].Value
End Sub

Private Sub ACCEPTBUTTON_Click()
    Application.ScreenUpdating = False
    
    Dim wsProd As Worksheet
    Set wsProd = Worksheets("PRODUCTION")
    Dim targetRow As Long
    Dim matchValue As String
    
    ' 先判断组合框是否有选中值,避免空值错误
    If ComboBox4.Value = "" Then
        MsgBox "请先选择ComboBox4的选项"
        Application.ScreenUpdating = True
        Exit Sub
    End If
    matchValue = CStr(ComboBox4.Value)
    
    ' 遍历查找匹配行
    For targetRow = 1001 To 2 Step -1 ' 对应原代码C+1的范围
        ' 将单元格值转为字符串后再匹配
        If CStr(wsProd.Cells(targetRow, 1).Value) Like matchValue Then
            wsProd.Cells(targetRow, 1).EntireRow.Hidden = False
            ' 直接用找到的行号写入数据,避免依赖ActiveCell
            With wsProd
                .Range("AC" & targetRow).Value = TextBox1.Value
                .Range("AD" & targetRow).Value = TextBox2.Value
                .Range("AE" & targetRow).Value = TextBox3.Value
                .Range("AF" & targetRow).Value = TextBox4.Value
                .Range("AG" & targetRow).Value = TextBox5.Value
                .Range("AH" & targetRow).Value = TextBox6.Value
                .Range("AI" & targetRow).Value = TextBox7.Value
                .Range("AJ" & targetRow).Value = TextBox8.Value
                .Rows(targetRow).RowHeight = 16
            End With
            ' 若只需匹配第一个符合条件的行,可提前退出循环
            Exit For
        End If
    Next targetRow
    
    Unload Me
    Application.ScreenUpdating = True
End Sub

额外优化点

  • 去掉Activate和Select操作,直接通过工作表对象操作,提升代码稳定性与执行效率
  • 增加组合框空值判断,防止用户未选择选项就触发操作
  • 找到匹配行后直接使用该行号写入数据,不再依赖ActiveCell,避免选中状态变化导致的错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 04:50:22