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

VBA运行时错误91/13求助:公式生成日期查找宏报错

VBA查找今日日期代码错误修复

错误原因分析

  • 运行时错误91:targetcell是Range对象,赋值时必须使用Set关键字,原代码直接赋值导致对象变量未初始化。
  • 运行时错误13:FindString被定义为Date类型,但你用CLng(Date)给它赋值(返回长整型),类型不匹配;另外若单元格内容非日期,CLng(targetcell)也会触发类型不匹配。
  • 其他潜在问题:Counter未声明,LR使用Double类型(行号应为整数,改用Long更合适),Activate和Select属于冗余操作,会降低代码运行效率。

修正后的代码

Sub FindTodayDate()
    Dim ws As Worksheet
    Dim FindString As Long               ' 今日日期转长整型
    Dim target As Long
    Dim targetcell As Range
    Dim found As Boolean
    Dim LR As Long
    Dim Counter As Long                  ' 声明循环变量

    ' 将今日日期转为长整型,规避格式匹配问题
    FindString = CLng(Date)
    found = False

    For Each ws In ThisWorkbook.Worksheets
        If ws.Name <> "Dashboard" And ws.Name <> "Template" Then
            ' 精准获取B列最后一行(避免整列遍历浪费资源)
            LR = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
            
            For Counter = 1 To LR
                Set targetcell = ws.Cells(Counter, 2)
                ' 先判断单元格是否为日期类型,防止触发类型错误
                If IsDate(targetcell.Value) Then
                    target = CLng(targetcell.Value)
                    If target = FindString Then
                        ' 定位目标单元格,若无需选中可去掉.Activate
                        ws.Cells(Counter, 1).Activate
                        found = True
                        Exit For
                    End If
                End If
            Next Counter

            If found Then Exit For
        End If
    Next ws
End Sub

额外优化说明

  • 改用ws.Cells(ws.Rows.Count, "B").End(xlUp).Row获取最后一行,比SpecialCells(xlCellTypeLastCell)更准确,不会受空白行干扰。
  • 增加IsDate(targetcell.Value)判断,过滤非日期单元格,彻底避免类型不匹配错误。
  • 若不需要手动选中单元格,可直接删除.Activate语句,直接对目标单元格进行后续操作,代码运行更高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 18:23:26