使用EXCEL的VBA宏命令来批量修改文件单元格里的批注

本文介绍了一个VBA宏,用于在Excel工作表Sheet1中,从第73行到第100行查找带有批注的单元格,自动更新批注中lastCell和ifArea的行号,每行增加4行。用户需在VB编辑器中编写并运行这段代码。
摘要由CSDN通过智能技术生成

作用说明:找到名为Sheet1的工作表里的第73行到第100行里所有包含有批注的单元格
把这些单元格的批注里的
lastCell=“AQ33” 替换成lastCell=“AQ37”(加4行)
ifArea =[“A16:A20”] 替换成ifArea =[“A20:A24”] (两个都加4行)

使用方法:点击:开发工具——VB编辑器 或者直接ALT+F11打开
点:插入——模块——把代码粘贴到编辑器里,点运行按钮即可运行

Sub 更新批注行数()
    Dim ws As Worksheet
    Dim cell As Range
    Dim commentText As String
    Dim newRowOffset As Long
    
    ' 设置要操作的工作表
    Set ws = ThisWorkbook.Sheets("Sheet1") '将“Sheet1”替换为你的工作表名称
    
    ' 设置插入新行的偏移量
    newRowOffset = 4
    
    ' 循环遍历工作表中的每个单元格
    For Each cell In ws.Rows("73:100").Cells
        ' 检查单元格是否有批注
        If Not cell.Comment Is Nothing Then
            ' 获取批注文本
            commentText = cell.Comment.text
            ' 使用正则表达式匹配批注中的行号并自动增加
            commentText = UpdateCommentText(commentText, newRowOffset)
            ' 将更新后的批注文本重新写入批注
            cell.Comment.text commentText
        End If
    Next cell
End Sub

Function UpdateCommentText(ByVal text As String, ByVal offset As Long) As String
    Dim regex As Object
    Set regex = CreateObject("VBScript.RegExp")
    
    regex.Global = True
    regex.IgnoreCase = True
    regex.Pattern = "lastCell=""[A-Z]+(\d+)"""
    
    Dim matches As Object
    Set matches = regex.Execute(text)
    
    If matches.Count > 0 Then
        Dim match As Object
        For Each match In matches
            Dim oldRow As Long
            oldRow = CLng(match.SubMatches(0))
            Dim newRow As Long
            newRow = oldRow + offset
            text = Replace(text, "lastCell=""AQ" & oldRow & """", "lastCell=""AQ" & newRow & """")
        Next match
    End If
    
    ' 更新 ifArea 的行号
    regex.Pattern = "ifArea =\[""A(\d+):AQ(\d+)""\]"
    Set matches = regex.Execute(text)
    
    If matches.Count > 0 Then
        For Each match In matches
            Dim oldStartRow As Long
            oldStartRow = CLng(match.SubMatches(0))
            Dim oldEndRow As Long
            oldEndRow = CLng(match.SubMatches(1))
            Dim newStartRow As Long
            newStartRow = oldStartRow + offset
            Dim newEndRow As Long
            newEndRow = oldEndRow + offset
            text = Replace(text, "ifArea =[""A" & oldStartRow & ":AQ" & oldEndRow & """]", "ifArea =[""A" & newStartRow & ":AQ" & newEndRow & """]")
        Next match
    End If
    
    Set regex = Nothing
    Set matches = Nothing
    
    UpdateCommentText = text
End Function


  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值