Mah*_*hav 4 excel vba excel-2013
对于大数据选择(1000 + 单元格),下面的查询不起作用,但对于小数据选择,它可以工作。除非我按转义键,否则 Excel 将停止工作。
Sub TrimReplaceAndUppercase()
For Each cell In Selection
If Not cell.HasFormula Then
cell.Value = UCase(cell.Value)
cell = Trim(cell)
Selection.Replace What:="-", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End If
Next cell
End Sub
Run Code Online (Sandbox Code Playgroud)
Excel并没有停止工作。如果 Excel 冻结,则意味着 Excel 仍在工作!由于选择范围很大,它需要更长的时间,因此看起来它什么也没做。
我建议使用 VBAreplace()而不是Range.Replace()一步完成所有操作,否则您需要 3 次读/写操作,这会使速度慢 3 倍。还要关闭屏幕更新和计算,以使其运行得更快。
Option Explicit
Public Sub TrimReplaceAndUppercase()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
On Error GoTo CLEAN_EXIT ' in case anything goes wrong make sure to reactivate calculation and screenupdating
Dim Cell As Range
For Each Cell In Selection.Cells
If Not Cell.HasFormula Then
Cell.Value = Replace$(Trim(UCase(Cell.Value)), "-", vbNullString)
End If
Next Cell
CLEAN_EXIT:
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
' If there was an error above we want to know
If Err.Number Then Err.Raise Err.Number
End Sub
Run Code Online (Sandbox Code Playgroud)
问题是这段代码
cell.Value = UCase(cell.Value)
cell = Trim(cell)
Selection.Replace What:="-", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Run Code Online (Sandbox Code Playgroud)
意味着读取单元格内容 3 次,写入单元格内容 3 次。每个读/写操作都需要花费大量时间。每个写入操作都会触发一个需要时间的计算。
因此,首先您希望将读写操作最小化为仅 1 个操作。从单元中读取一次数据,完成所有处理并将其写回一次。
其次,您不希望对每个写入操作进行计算,因此我们将其设置为手动,最后又设置为自动。这将在最后仅进行一次计算(对于所有更改的单元格),而不是对每个单元格进行计算。