简体   繁体   English

Excel VBA - 清除最后使用的单元格的内容

[英]Excel VBA - clear content to the last used cell

Worksheets("happy").Unprotect
Range("C4").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Range("C4:BB100").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents

I want to clear the range from C4 to the last used cell which constantly changes.我想清除从C4到最后使用的不断变化的单元格的范围。 Does anyone have any idea?有人有什么主意吗?

This is my attempt.这是我的尝试。

Sub del_range()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("happy")
'ws.Range(Cells(4, 3), Cells(ws.UsedRange.SpecialCells(xlCellTypeLastCell).Row, ws.UsedRange.SpecialCells(xlCellTypeLastCell).Column)).Select
ws.Range(Cells(4, 3), Cells(ws.UsedRange.SpecialCells(xlCellTypeLastCell).Row, ws.UsedRange.SpecialCells(xlCellTypeLastCell).Column)).ClearContents
End Sub

The commented line would just select it, but i recommend not doing that because select needs time.注释行将只是 select 它,但我建议不要这样做,因为 select 需要时间。 It looks in which line the last value in this sheet is and in which column is the last value and deletes all from cell C4 to last row and cell.它查看此工作表中的最后一个值在哪一行,最后一个值在哪一列,并删除从单元格 C4 到最后一行和单元格的所有内容。

The Range from a Cell to the Last Cell从一个单元格到最后一个单元格的范围

Option Explicit

Sub clearHappy()
    With ThisWorkbook.Worksheets("happy")
        '.Unprotect
        With .Range("C4")
            Dim rg As Range:
            Set rg = .Resize(.Worksheet.Rows.Count - .Row + 1, _
                .Worksheet.Columns.Count - .Column + 1)
            'Debug.Print rg.Address
            Dim cel As Range
            Set cel = rg.Find("*", , xlFormulas, , xlByRows, xlPrevious)
            If Not cel Is Nothing Then
                'Debug.Print cel.Address
                Set rg = rg.Resize(cel.Row - .Row + 1, _
                    rg.Find("*", , , , xlByColumns, xlPrevious).Column _
                    - .Column + 1)
                'Debug.Print rg.Address
                rg.ClearContents
            End If
        End With
        '.Protect
    End With
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM