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

Excel循环宏行计数器未更新问题求助

修复Excel宏:遍历工作表时行计数不更新的问题

你的宏出现行计数不更新的核心问题是:所有Cells、Range操作都没有绑定当前循环的工作表对象ws,默认会使用活动工作表的数据,导致lr(最后一行行号)始终取的是第一个工作表的数值,后续工作表都用这个值来格式化。

修复方案

给所有单元格/区域操作加上ws.前缀(或在With ws块中用.替代),明确指定操作当前循环的工作表,同时去掉不必要的Select操作(Select不仅降低效率,还容易引发上下文错误)。

修复后的完整代码:

Sub Formatting()
'
' Formatting Macro
'
' Keyboard Shortcut: Ctrl+Shift+F
'
Dim ws As Worksheet
Dim lr As Long ' 显式声明变量类型,更规范
         
For Each ws In ThisWorkbook.Worksheets
    With ws
        ' 明确使用当前工作表的Cells计算最后一行
        lr = .Cells(.Rows.Count, "A").End(xlUp).Row
        
        ' 直接操作Range,无需Select
        With .Range("$A$1:$X$" & lr).Font
            .Name = "Century"
            .Size = 12
            .Strikethrough = False
            .Superscript = False
            .Subscript = False
            .OutlineFont = False
            .Shadow = False
            .Underline = xlUnderlineStyleNone
            .TintAndShade = 0
            .ThemeFont = xlThemeFontNone
        End With
        With .Range("$A$1:$X$" & lr)
            .HorizontalAlignment = xlCenter
            .VerticalAlignment = xlCenter
            .Orientation = 0
            .AddIndent = False
            .IndentLevel = 0
            .ShrinkToFit = False
            .ReadingOrder = xlContext
            .MergeCells = False
        End With
        
        ' 操作当前工作表的G列
        With .Columns("G:G")
            .ColumnWidth = 75
            .VerticalAlignment = xlCenter
            .WrapText = True
            .Orientation = 0
            .AddIndent = False
            .IndentLevel = 0
            .ShrinkToFit = False
            .ReadingOrder = xlContext
            .MergeCells = False
        End With
        
        ' 自动调整当前工作表的行高
        .Cells.EntireRow.AutoFit
        ' 可选:切换到当前工作表的A1单元格(如果需要)
        .Range("A1").Activate
    End With
Next ws
End Sub

关键修改点说明

  1. 绑定工作表对象:所有Cells、Range、Columns前都加上.(因为在With ws块中,.等价于ws.),确保操作的是当前循环的工作表,而非活动工作表。
  2. 显式声明变量:添加Dim lr As Long,避免VBA默认的变体类型带来的潜在问题。
  3. 移除Select操作:直接对Range对象进行格式设置,无需先选中,提升代码效率和稳定性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:55:16