Excel resetting “UsedRange”

前端 未结 12 2166
醉酒成梦
醉酒成梦 2021-01-05 15:42

Don\'t know what I\'m missing, but the examples I see posted do not appear to work.

I import data from a web query. I set the query to clear unused cells when it re

12条回答
  •  感动是毒
    2021-01-05 15:59

    Best code that worked for me:

    Sub DeleteUnused()
    Dim myLastRow As Long
    Dim myLastCol As Long
    Dim dummyRng As Range
    Dim AnyMerged As Variant
    'http://www.contextures.on.ca/xlfaqApp.html#Unused
    'Helps to reset the usedrange by deleting rows and columns AFTER your true used range
    
        'Check for merged cells
        AnyMerged = ActiveSheet.UsedRange.MergeCells
        If AnyMerged = True Or IsNull(AnyMerged) Then
            MsgBox "There are merged cells on this sheet." & vbCrLf & _
                   "The macro will not work with merged cells.", vbOKOnly + vbCritical, "Macro will be Stopped"
            Exit Sub
        End If
    
        With ActiveSheet
            myLastRow = 0
            myLastCol = 0
            Set dummyRng = .UsedRange
            On Error Resume Next
            myLastRow = _
            .Cells.Find("*", after:=.Cells(1), _
                        LookIn:=xlFormulas, lookat:=xlWhole, _
                        searchdirection:=xlPrevious, _
                        searchorder:=xlByRows).Row
            myLastCol = _
            .Cells.Find("*", after:=.Cells(1), _
                        LookIn:=xlFormulas, lookat:=xlWhole, _
                        searchdirection:=xlPrevious, _
                        searchorder:=xlByColumns).Column
            On Error GoTo 0
    
            If myLastRow * myLastCol = 0 Then
                .Columns.Delete
            Else
                .Range(.Cells(myLastRow + 1, 1), _
                       .Cells(.Rows.Count, 1)).EntireRow.Delete
                .Range(.Cells(1, myLastCol + 1), _
                       .Cells(1, .Columns.Count)).EntireColumn.Delete
            End If
        End With
    
    End Sub
    

提交回复
热议问题