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

VBA隐藏工作表列宏出现Run-time error '13'类型不匹配问题求助

解决VBA宏的Run-time error '13'类型不匹配问题

错误原因

你遇到的类型不匹配错误,是因为代码里直接把Range对象(InputRng)和单元格的值(c.Value)做相等判断了。VBA没法直接将一个Range对象和单元格的数值/文本进行比较,必须先取出Range对象的实际值。

修正方案

需要修改两处代码:

  1. 空值判断逻辑:原代码中If InputRng = "" Then同样犯了对象和值直接比较的错误,要改成判断单元格的值是否为空。
  2. 列匹配逻辑:将If c.Value = InputRng Then改为比较两个单元格的实际值。

另外可以优化代码效率:提前把选中单元格的值存到变量里,避免遍历每个单元格时都重复访问Range对象。

修正后的完整代码

Sub HideColumnsSheets()
    Dim ws As Worksheet
    Dim InputRng As Range
    Dim c As Range
    Dim xTitleId As String
    Dim targetValue As Variant '新增变量存储目标值
    
    xTitleId = "Choose the cell you want to hide columns in all visible unprotected sheets in this workbook, based on the value of that cell."
    Set InputRng = Application.Selection
      
    Set InputRng = Application.InputBox("Select one cell :", xTitleId, InputRng.Address, Type:=8)
    
    '修正空值判断:检查单元格值是否为空
    If IsEmpty(InputRng.Value) Or InputRng.Value = "" Then
        MsgBox "Because the selected cell is empty, the macro was not executed."
        GoTo 900 'Stop the macro because cell is empty
    End If
    
    targetValue = InputRng.Value '提前存储目标值,提升效率
    
    For Each ws In ActiveWorkbook.Worksheets
        If ws.Visible = False Or ws.ProtectContents = True Then GoTo 100 
        'If the sheet is hidden or protected go to next sheet
        For Each c In ws.UsedRange.Cells
            '修正比较逻辑:用目标值和当前单元格值比较
            If c.Value = targetValue Then
                c.EntireColumn.Hidden = True
            End If
        Next c
100:
    Next ws
   
900:

End Sub

额外说明

  • 用IsEmpty判断单元格是否真正为空(比如未输入任何内容的单元格),再补充判断InputRng.Value = ""可以覆盖单元格被设置为空文本的情况。
  • 提前存储targetValue能减少对Range对象的重复调用,在数据量大的工作表中能明显提升宏的运行速度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:52:33