【问题标题】:Running Macro Once Does Not Do Anything. Running the Macro Again Works运行宏一次不会做任何事情。再次运行宏有效
【发布时间】:2020-04-08 19:30:17
【问题描述】:

我一直在处理的宏遇到了一些问题。它用于在运行另一个单独的宏时删除空白(超过一百万个空白行)。如果我让这个工作正常,我想将这两个宏合并在一起。

这是宏:

Sub Test()
DeleteBlankTableRows ActiveSheet.ListObjects(1)
End Sub
Sub DeleteBlankTableRows(ByVal tbl As ListObject)
Dim rng As Range
Set rng = tbl.DataBodyRange ' Get table data rows range.
Dim DirArray As Variant
DirArray = rng.Value2       ' Save table values to array.

' LOOP THROUGH ARRAY OF TABLE VALUES
Dim rowTMP As Long
Dim colTMP As Long
Dim combinedTMP As String
Dim rangeToDelete As Range

'  Loop through rows.
For rowTMP = LBound(DirArray) To UBound(DirArray)
    combinedTMP = vbNullString  ' Clear temp variable.

    ' Loop through each cell in the row and get all values combined.
    For colTMP = 1 To tbl.DataBodyRange.Columns.Count
        combinedTMP = combinedTMP & DirArray(rowTMP, colTMP)
    Next colTMP

    ' Check if row is blank.
    If combinedTMP = vbNullString Then
        ' Row is blank.  Add this blank row to the range-to-delete.
        If rangeToDelete Is Nothing Then
            Set rangeToDelete = tbl.ListRows(rowTMP).Range
        Else
            Set rangeToDelete = Union(rangeToDelete, tbl.ListRows(rowTMP).Range)
        End If
    End If
Next rowTMP

' DELETE BLANK TABLE ROWS (if any)
If Not rangeToDelete Is Nothing Then rangeToDelete.Delete
End Sub

第一次运行时,它会加载并运行起来。加载后不到一分钟......没有任何反应(至少在视觉上)。我再次运行它,它加载得很快;这一次,空白行在视觉上消失了。

【问题讨论】:

  • 变量tbl没有定义,它指的是什么
  • 不要使用 Activesheet。使用特定的父工作表名称参考。

标签: excel vba


【解决方案1】:

一个类似的想法,使用显式父工作表引用和索引和最大值来确定一行是否为空白。

Option Explicit
Public Sub DeleteRowsIfBlank()
    Dim ws As Worksheet, table As ListObject, arr(), i As Long, counter As Long, unionRng As Range
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    Set table = ws.ListObjects(1)
    arr = table.DataBodyRange.Value
    counter = table.DataBodyRange.Cells(1, 1).Row
    For i = LBound(arr, 1) To UBound(arr, 1)
        If Application.Max(Application.Index(arr, i, 0)) = 0 Then
            If Not unionRng Is Nothing Then
                Set unionRng = Union(unionRng, table.Range.Rows(counter))
            Else
                Set unionRng = table.Range.Rows(counter)
            End If
        End If
        counter = counter + 1
    Next
    If Not unionRng Is Nothing Then unionRng.Delete
End Sub

【讨论】:

  • 感谢 QHarr 提供更精简的代码。它可以工作,但是在我运行它两次之后。第一次仍然需要大约 30 秒,然后下一次需要 1 秒(然后删除空白)。您认为第一个宏是否仍在后台运行?这就是我必须运行这个宏两次的原因吗?
  • 我不确定您还运行了哪些其他代码。如果您只运行上面的代码,它不会调用其他任何东西,除非您在其他地方有一些基于事件的代码。它应该在第一次运行时删除。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-07
  • 2020-01-01
  • 1970-01-01
相关资源
最近更新 更多