改变范围破坏子

时间:2013-08-14 14:29:37

标签: excel excel-vba vba

我需要设置第一行,所以我从

更改了Sub中的范围
For Each rng In Sheets("360").Range("B:CJ" & Lastrow)

For Each rng In Sheets("360").Range("B2:CJ2" & Lastrow)

子知道大麦运行需要5秒钟才能运行,知道如果它完成了就需要几分钟

如何解决这个问题?

由于

Sub CleanAll()

    Dim rng As Range
    Dim Lastrow As Long

    With Sheets("360")
        Lastrow = .Range("A" & .Rows.Count).End(xlUp).Row
    End With

    For Each rng In Sheets("360").Range("B2:CJ" & Lastrow)
        rng.Value = NumberOnly(rng.Value)
    Next
End Sub

功能

Function NumberOnly(strSource As String) As String
Dim i As Integer
Dim strResult As String

For i = 1 To Len(strSource)
    Select Case Asc(Mid(strSource, i, 1))
        Case 32, 48 To 57, 65, 78:
            strResult = strResult & Mid(strSource, i, 1)
    End Select
Next
NumberOnly = strResult

End Function

2 个答案:

答案 0 :(得分:4)

For Each rng In Sheets("360").Range("B2:CJ2" & Lastrow)

删除以下2个CJ:

For Each rng In Sheets("360").Range("B2:CJ" & Lastrow)

Lastrow已指定最后一行编号,因此如果Lastrow值为300且您编写“CJ2”& Lastrow,你现在的实际范围是B2:CJ2300,这意味着你现在又跑了2000行。

答案 1 :(得分:1)

我发现在表格中使用您的数据可以解决大量的重新调整范围问题。

话虽这么说,你应该从你的范围创建一个变量数组,然后遍历变量数组。一旦完成复制到数组回到范围。这将使它加速百倍。

像这样......

Sub CleanAll()

    Dim myArray As Variant
    Dim Lastrow As Long


    With Sheets("360")
        Lastrow = .Range("A" & .Rows.Count).End(xlUp).Row
    End With

    myArray = Sheets("360").Range("B2:CJ" & Lastrow)

    For x = LBound(myArray) To UBound(myArray)
        For y = LBound(myArray, 2) To UBound(myArray, 2)
            myArray(x, y) = NumberOnly(myArray(x, y))
        Next y
    Next x

    Sheets("360").Range("B2:CJ" & Lastrow) = myArray
End Sub

Function NumberOnly(ByVal strSource As String) As String
    Dim i As Integer
    Dim strResult As String

    For i = 1 To Len(strSource)
        Select Case Asc(Mid(strSource, i, 1))
            Case 32, 48 To 57, 65, 78:
                strResult = strResult & Mid(strSource, i, 1)
        End Select
    Next
    NumberOnly = strResult

End Function