在VBA循环中更新Excel状态栏

时间:2016-09-28 15:10:28

标签: excel vba excel-vba

我有一个宏代码来执行数据修剪。以下是我的代码:

Sub StatusBarExample()
Application.ScreenUpdating = False
Application.DisplayStatusBar = True
Application.StatusBar = "Trimming..."
Dim x As Long
x = 1
Do While Cells(x, 1) <> ""
Cells(x, 2).Select
ActiveCell.FormulaR1C1 = "=trim(RC[-1])"
x = x + 1
Loop
Application.Wait Now + TimeValue("00:00:02")
Application.StatusBar = False
End Sub

数据总是在变化,这就是我使用Do While循环的原因。使用此代码,我只能在不知道百分比进度的情况下看到“修剪”消息。任何人都可以帮我改进这段代码吗?

1 个答案:

答案 0 :(得分:1)

我会采取这种方法。我更喜欢for循环,这将显示状态栏中的%complete。

Sub StatusBarExample()
Application.ScreenUpdating = False
Application.DisplayStatusBar = True
Application.StatusBar = "Trimming..."
Dim x As Long
Dim lRow as Long
Dim prePct as Single, newPct as Single

newPct = 0
prePct = 0
With ThisWorkbook.Sheets("Sheet Name Goes Here")
   lRow = .Range("A" & .Rows.Count).End(xlUp).Row

   For x = 1 to lRow
      .Cells(x,2).FormulaR1C1 = "=trim(RC[-1])"
      newPct = x/lRow

      If newPct > prePct + .01
         DoEvents
         prePct = newPct
      End If

      Application.StatusBar = "Trimming..." & Format(x/lRow,"0.00%") & " Complete"
   Next x
Application.StatusBar = False
Application.ScreeUpdating = True
End Sub

感谢您提供的修改建议。我做了一些改变。在第If newPct > prePct + .01行中,您可能需要根据数据量将.01更改为其他内容。