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

Excel加班工作表需求:实现最新加班记录置顶追加功能

Excel加班记录置顶解决方案

需求说明

  • 从右侧指定单元格复制姓名对应的加班总时长(小时/分钟)到记录区
  • 新添加的记录始终位于记录区顶部,再次添加时旧记录自动下移
  • 首次添加时若记录区无数据,直接将记录放在顶部
  • 避免剪切粘贴导致的顶部单元格内容覆盖问题

实现步骤

1. 插入宏按钮

打开Excel的「开发工具」选项卡,点击「插入」→ 选择「按钮(窗体控件)」,在工作表合适位置绘制按钮,指定新宏(命名为AddOvertimeRecord)。

2. 编写VBA代码

右键点击按钮选择「查看代码」,粘贴以下代码(根据你的实际单元格位置修改对应参数):

Sub AddOvertimeRecord()
    ' 定义变量
    Dim recordStartRow As Integer
    Dim nameCell As Range
    Dim timeCell As Range
    Dim targetRange As Range
    
    ' 配置参数:根据你的实际单元格修改
    Set nameCell = ThisWorkbook.Sheets("Sheet1").Range("D2") ' 右侧姓名单元格
    Set timeCell = ThisWorkbook.Sheets("Sheet1").Range("E2") ' 右侧总时长单元格
    recordStartRow = 2 ' 记录区起始行(A2为第一条记录,A1是表头)
    
    ' 检查姓名和时长单元格是否为空
    If nameCell.Value = "" Or timeCell.Value = "" Then
        MsgBox "请先填写姓名和加班时长!", vbExclamation
        Exit Sub
    End If
    
    With ThisWorkbook.Sheets("Sheet1")
        ' 检查记录区首行是否有数据
        If .Cells(recordStartRow, 1).Value = "" Then
            ' 首次添加:直接写入数据
            .Cells(recordStartRow, 1).Value = Date ' 当前日期
            .Cells(recordStartRow, 2).Value = nameCell.Value
            .Cells(recordStartRow, 3).Value = timeCell.Value
        Else
            ' 插入新行到记录区顶部
            .Rows(recordStartRow).Insert Shift:=xlDown
            ' 写入新记录
            .Cells(recordStartRow, 1).Value = Date
            .Cells(recordStartRow, 2).Value = nameCell.Value
            .Cells(recordStartRow, 3).Value = timeCell.Value
        End If
    End With
    
    ' 清空右侧输入单元格(可选)
    nameCell.Value = ""
    timeCell.Value = ""
End Sub

3. 代码说明

  • 自动获取当前日期作为记录日期
  • 先检查输入单元格是否为空,避免空记录
  • 检测记录区首行状态:空则直接写入,非空则插入新行后写入,确保新记录始终置顶
  • 可选清空输入单元格,方便下次录入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 01:37:29