TRIMfunction/使用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 

将数据复制到数组中,然后在数组上进行操作,然后将数据放回到范围中,您将获得更好的性能。

另外,不要使用Excel.Application.Trim 。 这是Excel 95语法,以及意外error handling的延迟调用。 VBA内置了Trimfunction,速度提高了10倍左右,并提供了Intellisense。

 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 

一次使用Excel Trim的arrays版本在整个范围内执行:

 myRange.Value = Application.Trim(myRange.Value) 

使用代码中唯一可见的variables,它将是:

 With Range(Cells(1,1), Cells(ScenarioTableLastRow, ScenarioTableLastColumn)) .Value = Application.Trim(.Value) End With