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

VBA生成00:00-23:59时间表时出现小时覆盖问题求助

解决VBA生成时间表时数据被覆盖的问题

问题原因

你的代码外层循环遍历小时,但内层循环每次都从第1行开始写入数据,每循环一个小时就会覆盖前一小时的第1-60行,最终只会保留最后一次循环(24小时)的结果。另外原代码的小时范围是1-24,不符合00:00到23:59的需求,分钟从1-60也不准确(分钟应为0-59)。

修正后的代码

Sub uhrzeit()
    Dim i As Integer
    Dim stunde As Integer
    Dim startRow As Integer ' 记录每小时的起始行
    
    For stunde = 0 To 23 ' 覆盖00到23小时
        startRow = stunde * 60 + 1 ' 计算当前小时对应的起始行
        For i = 0 To 59 ' 覆盖00到59分钟
            Cells(startRow + i, 1) = stunde ' 写入小时
            Cells(startRow + i, 2) = i ' 写入分钟
        Next i
    Next stunde
End Sub

进阶优化(生成标准时间格式)

如果需要直接生成hh:mm格式的时间值,而非分开的小时和分钟数字,可以用TimeSerial函数实现:

Sub uhrzeit()
    Dim i As Integer
    Dim stunde As Integer
    Dim rowNum As Integer
    
    rowNum = 1
    For stunde = 0 To 23
        For i = 0 To 59
            Cells(rowNum, 1) = TimeSerial(stunde, i, 0)
            rowNum = rowNum + 1
        Next i
    Next stunde
    ' 设置单元格显示为hh:mm格式
    Columns(1).NumberFormat = "hh:mm"
End Sub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 01:12:35