2017-02-09 292 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