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

Excel VBA图表动态X轴:日期区间筛选报错(运行时错误13)排查

问题解决:VBA运行时错误13(类型不匹配)修复

错误原因分析

  1. 字符串拼接语法错误:你在引用列范围时,错误地把变量endDateNumber2写在了字符串常量内部,VBA无法识别这个变量,导致传递给Columns的参数是无效文本,触发类型不匹配。
  2. 误用FormulaR1C1属性:FormulaR1C1是用来设置单元格公式的属性,不是用来定位列范围的,直接调用Columns即可。
  3. 日期输入处理不严谨:直接将InputBox返回的字符串赋值给Date类型变量,若用户输入格式不符合要求,会提前触发错误,应该先验证再转换。
  4. 缺失起始日期前的列隐藏逻辑:当前代码只处理了结束日期之后的列,未处理起始日期之前的列,无法完整实现区间外列隐藏的需求。

修正后的代码

Sub LWA_Erzeugen()
    Dim startDateStr As String
    Dim endDateStr As String
    Dim startDate As Date
    Dim endDate As Date
    Dim startDateNumber As Long
    Dim endDateNumber As Long
    Dim startColNum As Long
    Dim endColNum As Long
    Dim productionSheet As Worksheet
    
    ' 初始化工作表对象,避免重复引用
    Set productionSheet = ThisWorkbook.Sheets("B2 PV Production")
    
    ' 获取用户输入的日期字符串
    startDateStr = InputBox("Start-Datum eingeben (mm.dd.yyyy):")
    endDateStr = InputBox("End-Datum eingeben (mm.dd.yyyy):")
    
    ' 验证并转换日期
    If Not IsDate(startDateStr) Or Not IsDate(endDateStr) Then
        MsgBox "Ungültiges Datumformat! Bitte verwenden Sie mm.dd.yyyy.", vbExclamation
        Exit Sub
    End If
    
    startDate = CDate(startDateStr)
    endDate = CDate(endDateStr)
    
    ' 写入验证后的日期到单元格
    Range("I2").Value = startDate
    Range("J2").Value = endDate
    
    ' 先取消所有列隐藏
    Unhide_Contiguous_Columns
    
    ' 获取计算后的日期对应列号(根据你的逻辑从K2读取)
    startDateNumber = ThisWorkbook.Sheets("B1 PV Application").Range("K2").Value ' 假设K2对应起始日期的列偏移
    endDateNumber = ThisWorkbook.Sheets("B1 PV Application").Range("K2").Value   ' 根据实际逻辑调整,这里假设你有对应起始的单元格
    
    ' 计算实际要隐藏的列范围(保留你的原逻辑+3)
    startColNum = startDateNumber + 3
    endColNum = endDateNumber + 3
    
    ' 隐藏起始日期之前的列(从B列到起始列的前一列)
    If startColNum > 2 Then ' B列是第2列,避免误隐藏B列
        productionSheet.Columns("B:R1C" & (startColNum - 1)).EntireColumn.Hidden = True
    End If
    
    ' 隐藏结束日期之后的列(从结束列的下一列到HT列)
    If endColNum < 320 Then ' 320对应HT列的列号
        productionSheet.Columns("R1C" & (endColNum + 1) & ":HT").EntireColumn.Hidden = True
    End If
End Sub

Sub Unhide_Contiguous_Columns()
    ThisWorkbook.Sheets("B2 PV Production").Range("B:HT").EntireColumn.Hidden = False
End Sub

关键修正点说明

  • 字符串正确拼接:用"R1C" & 变量 & ":R1C320"的形式,让VBA正确解析变量值生成合法的范围字符串。
  • 移除无效属性:直接通过Columns方法引用列范围,不再误用FormulaR1C1。
  • 日期输入验证:先获取字符串,用IsDate验证后再转换为Date类型,避免格式错误导致崩溃。
  • 完整区间隐藏:补充了起始日期前的列隐藏逻辑,确保只有用户指定区间内的列显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 04:38:13