Lea*_*ira 10 excel vba excel-vba
我正在使用下面的代码修剪一些包含空格的"空白单元格".事情是需要花费太多时间,就像循环到每个细胞一样.我想要的是删除所有单元格中的空格(开头和结尾,不是中间的空格).
有没有更简单的方法可以一次申请?
For a = 1 To ScenarioTableLastRow
For f = 1 To ScenarioTableLastColumn
If Cells(a, f) <> "" Then
Cells(a, f) = Excel.Application.Trim(Cells(a, f))
End If
Next f
Next a
Run Code Online (Sandbox Code Playgroud)
Thu*_*ame 11
将数据复制到数组中,然后处理数组,然后将数据放回范围内,您将获得更好的性能.
另外,不要使用Excel.Application.Trim.这是Excel 95语法,以及具有意外错误处理的后期绑定调用.VBA Trim内置了一个功能 - 它的速度提高了大约10倍,并提供了智能感知功能.
Sub test()
'Assuming ScenarioTable is a range
Dim ScenarioTable As Range
Set ScenarioTable = Range("ScenarioTable")
'I assume your range might have some formulas, so...
'Get the formulas into an array
Dim v As Variant
v = ScenarioTable.Formula
Dim a As Long
Dim f As Long
'Then loop over the array
For a = LBound(v, 1) To UBound(v, 1)
For f = LBound(v, 2) To UBound(v, 2)
If Not IsEmpty(v(a, f)) Then
v(a, f) = VBA.Trim(v(a, f))
End If
Next f
Next a
'Insert the results
ScenarioTable.Formula = v
End Sub
Run Code Online (Sandbox Code Playgroud)
使用Excel的阵列版本立即在整个范围内执行Trim:
myRange.Value = Application.Trim(myRange.Value)
Run Code Online (Sandbox Code Playgroud)
使用代码中可见的唯一变量,它将是:
With Range(Cells(1,1), Cells(ScenarioTableLastRow, ScenarioTableLastColumn))
.Value = Application.Trim(.Value)
End With
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4046 次 |
| 最近记录: |