需要使用 VBA 将 excel 数组中所有具有“0”值的单元格替换为空白
Need to replace all the cells with "0" values in an excel array with blank using VBA
我需要 运行 一个宏,将数组中仅包含“0”的所有单元格替换为空白值
同时,包含 0 和其他 text/numbers 的单元格,例如。 “Test01”不应被考虑并保留原样
这是我写的代码,但它在 3k 行上真的很慢sheet
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
有什么可以让它更快的建议吗?
请使用下一个代码。它使用两个数组,对于大范围也应该足够快:
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
上面的代码很快,但是如果涉及公式,它会转换公式的值...
我需要 运行 一个宏,将数组中仅包含“0”的所有单元格替换为空白值 同时,包含 0 和其他 text/numbers 的单元格,例如。 “Test01”不应被考虑并保留原样
这是我写的代码,但它在 3k 行上真的很慢sheet
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
有什么可以让它更快的建议吗?
请使用下一个代码。它使用两个数组,对于大范围也应该足够快:
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
上面的代码很快,但是如果涉及公式,它会转换公式的值...