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

Excel自动填充表格VBA日期异常求助:日期始终显示1/1/1900

问题分析与解决方案

核心问题

日期显示为1/1/1900本质是Excel将空值/零值解析为默认起始日期。结合你的代码,主要有两个原因:

  • 合并单元格取值逻辑不严谨:合并单元格的实际值仅存储在左上角单元格,直接取Range("A9").Value可能因单元格状态问题返回空值;
  • 数据写入位置错误:代码硬编码写入Daily Report的A2:B2,而非你找到的下一行,同时序号生成逻辑与数据写入完全脱节。

修正后的VBA代码

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim completedRange As Range
    Dim reportSheet As Worksheet
    Dim nextRow As Long
    
    ' 定义监控的合并单元格区域(A9:H9)
    Set completedRange = Me.Range("A9:H9")
    Set reportSheet = ThisWorkbook.Sheets("Daily Report")
    
    ' 确定Daily Report下一个空行的行号
    nextRow = reportSheet.Cells(reportSheet.Rows.Count, "A").End(xlUp).Row
    ' 如果A2为空,从第2行开始;否则从下一行开始
    If nextRow < 2 Or IsEmpty(reportSheet.Cells(nextRow, "A")) Then
        nextRow = 2
    Else
        nextRow = nextRow + 1
    End If
    
    ' 仅当修改的单元格在监控区域内时执行操作
    If Not Intersect(Target, completedRange) Is Nothing Then
        Application.EnableEvents = False
        
        ' 从合并单元格安全取值(合并区域左上角单元格存储实际值)
        Dim sourceDate As Variant
        sourceDate = completedRange.MergeArea.Cells(1).Value
        
        ' 写入日期到Daily Report的对应行
        If IsDate(sourceDate) Then
            reportSheet.Cells(nextRow, "A").Value = sourceDate
            ' 设置目标单元格为日期格式(确保显示正确)
            reportSheet.Cells(nextRow, "A").NumberFormat = "yyyy/mm/dd" ' 可根据需求调整格式
        End If
        
        ' 写入其他数据
        reportSheet.Cells(nextRow, "B").Value = Me.Range("C9").Value
        reportSheet.Cells(nextRow, "C").Value = Me.Range("E9").Value
        reportSheet.Cells(nextRow, "D").Value = Me.Range("G9").Value
        
        ' 生成序号(可选,如果需要序号列)
        If nextRow > 2 Then
            reportSheet.Cells(nextRow, "E").Value = reportSheet.Cells(nextRow - 1, "E").Value + 1
        Else
            reportSheet.Cells(nextRow, "E").Value = 1
        End If
        
        Application.EnableEvents = True
    End If
End Sub

关键修改说明

  • 合并单元格取值优化:使用completedRange.MergeArea.Cells(1).Value确保从合并区域的实际存储单元格取值,避免空值问题;
  • 动态写入行:通过nextRow确定每次写入的目标行,不再硬编码覆盖A2,实现数据累加;
  • 日期校验与格式设置:增加IsDate判断确保写入的是有效日期,同时强制设置目标单元格的日期格式,避免显示异常;
  • 序号逻辑修正:将序号生成与数据行对应,避免序号与数据脱节。

额外排查建议

  • 检查Completed Daily Tasks工作表的A9单元格(合并区域左上角)是否确实存储了日期值,而非仅在视觉上显示;
  • 确保Daily Report的A列单元格格式设置为日期类型,而非文本或常规。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 11:17:41