【问题标题】:Need to replace all the cells with "0" values in an excel array with blank using VBA [duplicate]需要使用 VBA 将 excel 数组中所有具有“0”值的单元格替换为空白 [重复]
【发布时间】:2022-01-21 23:13:52
【问题描述】:

我需要运行一个宏,将数组中包含“0”的所有单元格替换为空白值 同时,包含 0 和其他文本/数字的单元格,例如。不应考虑“Test01”并保持原样

这是我写的代码,但在 3k 行表上确实很慢

Set sht = ActiveWorkbook.Sheets("Nuova Base Dati")
sht.Activate
Set rng = Range(Range("B2"), Range("E" & sht.UsedRange.Rows.count))
For Each cell In rng
If cell.Value = "0" Then cell.Value = ""
Next

有什么建议可以加快速度吗?

【问题讨论】:

  • 在整个范围内使用Range.Replace,不循环?
  • 如果Replace() 做不到,请设置一个数组dim arr as variant,并将该范围设置为数组arr = Range(Range("B2"), Range("E" & sht.UsedRange.Rows.count)),然后处理该数组。
  • 在循环Application.ScreenUpdating = FalseApplication.Calculation = xlCalculationManual上方和循环Application.Calculation = xlCalculationAutomatic下方添加两行
  • 感谢我通过@Toddleson 输入解决了它 :)
  • @Matteo - 这个建议就像在动脉伤口上贴创可贴。答案不是逐个单元循环。

标签: excel vba replace


【解决方案1】:

请使用下一个代码。它使用两个数组,并且对于大范围也应该足够快:

Sub ReplaceZero()
  Dim shT As Worksheet, arrE, r As Long, c As Long, arrFin
  Set shT = ActiveWorkbook.Sheets("Nuova Base Dati")

 'place the range to be processed in an array (for faster iteration):
 arrE = shT.Range(shT.Range("B2"), shT.Range("E" & shT.UsedRange.Rows.count)).Value2
 ReDim arrFin(1 To UBound(arrE), 1 To UBound(arrE, 2)) 'set dimensions of the final array, keeping the processing result
 For r = 1 To UBound(arrE)         'iterate between the array rows
    For c = 1 To UBound(arrE, 2)  'iterate between the array columns
        If arrE(r, c) = 0 Then
            arrFin(r, c) = ""             'write a null string in case of zero
        Else
             arrFin(r, c) = arrE(r, c)  'keep the existing value, if not zero
        End If
    Next c
 Next r
 'Drop the processed array content, at once:
 shT.Range("B2").resize(UBound(arrFin), UBound(arrFin, 2)).Value = arrFin
End Sub

上面的代码速度很快,但是如果涉及公式,它会将公式转换为它们的值...

【讨论】:

  • @BigBen 是的!是否涉及公式?我没有看到任何提及...
  • @BigBen 是的,你是对的!我将编辑我的答案并提及。谢谢!
猜你喜欢
  • 2018-04-28
  • 2020-11-19
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 2015-04-16
  • 1970-01-01
  • 2010-12-30
相关资源
最近更新 更多