TRIM function/remove spaces from cells using VBA

前端 未结 3 672
名媛妹妹
名媛妹妹 2021-02-08 05:43

I am using the code below to trim some \"blank cells\" that contain a space. The thing is it takes too much time, as is looping to every cell. What I want is to remove the spac

3条回答
  •  长情又很酷
    2021-02-08 06:13

    You'll get much better performance copying the data into an array, and working on the array, then placing the data back into the range.

    Also, don't use Excel.Application.Trim. That's Excel 95 syntax, and a late-bound call with unexpected error handling. VBA has a Trim function built-in - it's about 10 times faster and it provides 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
    

提交回复
热议问题