加快VBA marco

时间:2017-09-22 14:22:52

标签: excel vba excel-vba

我有一个可以正常工作的宏,当有大量数据时它会非常慢,我希望有人可以帮助我加快速度。

当我的VBA执行操作时,检查工作表的列是否为" NULL"如果它在那里它清除那个细胞。这是代码:

.env.production.local

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

我有一个文件,我运行它有从A到AD和61k +行的列,它花了30多分钟才完成,我希望能更快地完成。

4 个答案:

答案 0 :(得分: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

这将确保您保留格式。

答案 1 :(得分:1)

如果您想使用ActiveCell作为参考清除NULL

Range(ActiveCell, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Replace What:="NULL", Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, _
    ReplaceFormat:=False

答案 2 :(得分:0)

请试一试......

Sub RemoveNullColumn()
Dim lr As Long, lc As Long
Dim rng As Range, cell As Range, FirstCell As Range

With Application
    .Calculation = xlCalculationManual
    .EnableEvents = False
    .ScreenUpdating = False
End With

lr = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
lc = Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

Set FirstCell = ActiveCell
Set rng = Range(Cells(1, FirstCell.Column), Cells(lr, lc))

For Each cell In rng
    If cell.Value = "NULL" Then
        cell.Clear
    End If
Next cell

With Application
    .Calculation = xlCalculationAutomatic
    .EnableEvents = True
    .ScreenUpdating = True
End With
MsgBox "Finished"
End Sub

答案 3 :(得分:0)

使用.Find / .FindNext将所有匹配的单元格收集到Union中,然后清除Union联合单元格的内容。

Option Explicit

Sub noNULLs()
    Dim firstAddress As String, c As Range, rALL As Range
    With ActiveSheet.Cells    'This should be named worksheet like Worksheets("sheet1")
        Set c = .Find("NULL", MatchCase:=True, _
                      LookIn:=xlValues, LookAt:=xlWhole)
        If Not c Is Nothing Then
            Set rALL = c
            firstAddress = c.Address
            Do
                Set rALL = Union(rALL, c)
                Set c = .FindNext(c)
            Loop While c.Address <> firstAddress
            rALL.Clear
        End If
    End With
End Sub