2017-02-09 244 views
9

我正在使用下面的代码修剪包含空格的一些“空白单元格”。 问题是需要太多时间,因为循环到每个单元格。 我想要的是删除所有单元格中的空格(开始和结束,而不是中间)。TRIM功能/使用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 
+0

是你在运行之前设置'Application.ScreenUpdating = False'?这可以大大加快VBA代码。只要不要忘记在代码的末尾设置'Application.ScreenUpdating = True'。 – TylerH

+2

@TylerH这里的主要瓶颈是读取和写入单个单元格,但如果您要开始更改'ScreenUpdating',那么在您的过程劫持它之前,您至少应该将其恢复为* *。 – ThunderFrame

+1

@ThunderFrame是的,因此我说为什么在代码结束时将它重新设置为true。 – TylerH

回答

10

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

另外,请勿使用Excel.Application.Trim。这是Excel 95的语法,以及具有意外错误处理的延迟调用。 VBA内置了Trim函数,速度提高了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 
+0

非常感谢您!方式方式更快! –

+0

但我没有公式,我可以简单地删除v? –

+0

它应该没有关系,但如果你想更明确,只要将'.Formula'的两种用法都改为'.Value' – ThunderFrame

7

做它的整个范围内一次使用Excel的Trim的数组版本:

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

使用在你的代码唯一可见的变量,那就是:

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

这比我的答案快,如果范围包含公式, d将'.Value'的实例替换为'.Formula',并保存公式。 – ThunderFrame