加快VBA marco

Mik*_*ike 1 excel vba excel-vba

我有一个可以正常工作的宏,当有大量数据时它真的很慢,我希望这里的某个人可以帮助我加快速度.

当我的VBA做的是检查工作表的列是否为值"NULL",如果它在那里它清除该单元格.这是代码:

Sub RemoveNullColumn()
    Dim c, count, r, lc, FirstCell
    Application.ScreenUpdating = False
    count = 0
    r = ActiveCell.row      'lets you choose where you want to start even if it is not at "A1"
    c = ActiveCell.Column   'lets you choose where you want to start even if it is not at "A1"
    c = GetLetterFromNumber(c)  'Gets the column letter from the number provided above
    FirstCell = c & r       'sets the cell that you selected to start in so that you will end thereafter removing all the NULL

    lc = ActiveSheet.Cells(1, Columns.count).End(xlToLeft).Column   'Finding the last used column
    For H = ActiveCell.Column To lc Step 1      'Starts with where you selected a cell and moves right to the last column
        For x = 1 To Range(c & Rows.count).End(xlUp).row Step 1     'Starts with the first row and moves through the last row
            count = count + 1
            If Range(c & x).Value = "NULL" Then 'Checks the contents fo the cell to see if it is "NULL"
                Range(c & x).Clear
            End If
            If count = 1000 Then    'This was used testing but is not seen with the ScreenUpdating set to false
                Range(c & x).Select
                count = 1
            End If
        Next x
        ActiveCell.Offset(0, 1).Select  'select the next column
        c = ActiveCell.Column
        c = GetLetterFromNumber(c)      'get the letter of the next column
    Next H
    Application.ScreenUpdating = True
    MsgBox "Finished"
    Range(FirstCell).Select
End Sub

Function GetLetterFromNumber(Number)
    GetLetterFromNumber = Split(Cells(1, Number).Address(True, False), "$")(0)
End Function
Run Code Online (Sandbox Code Playgroud)

当没有很多行时它很快,但有很多行很慢.

我有一个文件,我运行它有从A到AD和61k +行的列,它花了超过30分钟完成,我希望更快.

S N*_*ash 6

而不是查看工作表中的每个单元格,使用更快的替换功能:(您可能需要编辑它根据您的需要自定义)

示例:

Sub RemoveNullColumn()

  Dim targetSheet As Worksheet
  Set targetSheet = ActiveSheet 'TODO: replace with a stronger object reference

  targetSheet.Cells.Replace What:="NULL", Replacement:="", LookAt:=xlWhole, _
  SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
   ReplaceFormat:=False
End Sub
Run Code Online (Sandbox Code Playgroud)

这将确保您保留格式.

  • 至少,使用`Range`参数并使用它而不是隐式地对抗`ActiveSheet`(通过`Cells`),从而强制调用者"激活"工作表.就目前而言,此程序鼓励呼叫者使用最差的编码实践. (3认同)
  • LookAt:= xlWhole将要求整个单元格值等于What:="NULL".如果要在文本中替换,请在LookAt中使用xlPart. (2认同)
  • fwiw,用`vbNullString`替换``"`稍快一些. (2认同)