excel 查找选定单元格旁边列的最后一行

1hdlvixo  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(147)

我必须经常删除大段的行,不幸的是我不能在excel文件本身中编写任何宏。所以我做了另一个Excel文件,其中包含我需要的宏。这也意味着范围是可变的。
我现在需要找到一种方法来删除所选单元格旁边的列中包含“0”的所有行。之后,我需要填写日期并向下拖动选定的单元格,直到最后一行(请参见下图)。

的数据
到目前为止,我有这个:

Private Sub CommandButton4_Click()
    Dim RngSelected As Range
    Dim dtToday As String
    dtToday = Format(Date, "yymmdd")      
       
    Set RngSelected = Application.InputBox(Title:="Please select a range", Prompt:="Select range", Type:=8)    
    
    For Each cell In RngSelected
        cell.Value = dtToday 
    Next    
    
    Dim LastRow As Long
    Dim ColC As Long

    ColC = RngSelected.Column - 1 'this part seems to identify the correct column (as column number)
    
    LastRow = Range(ColC & Rows.Count).End(xlUp).Row 'this part does not work at the moment 

    RngSelected.AutoFill Destination:=Range(RngSelected & ":" & RngSelected.Column & LastRow) ' this also does not work currently    
End Sub

字符串
任何建议都将得到重视

pwuypxnk

pwuypxnk1#

假设此数据

下面的代码

Option Explicit

Public Sub DoSomeStuff()
    
    ' get selection so we know where to start
    Dim SelRng As Range
    On Error Resume Next
    Set SelRng = Application.InputBox(Title:="Please select a range", Prompt:="Select range", Type:=8)
    On Error GoTo 0
    If SelRng Is Nothing Then Exit Sub
    
    ' find out which sheet we are working with
    Dim ws As Worksheet
    Set ws = SelRng.Parent
    
    ' get last used row left of the selection
    Dim LastRow As Long
    LastRow = ws.Cells(ws.Rows.Count, SelRng.Column - 1).End(xlUp).Row

    ' get the data range left of the selection
    Dim DataRange As Range
    Set DataRange = SelRng.Offset(ColumnOffset:=-1).Resize(LastRow - SelRng.Row + 1)
    
    
    ' here we collect all rows that will be deleted
    Dim RowsToDelete As Range
    
    ' loop through all cells in the data range
    Dim Cell As Variant
    For Each Cell In DataRange.Cells
        ' if value is zero add the row to RowsToDelete
        If Cell.Value = 0 Then
            If RowsToDelete Is Nothing Then
                Set RowsToDelete = Cell.EntireRow
            Else
                Set RowsToDelete = Application.Union(RowsToDelete, Cell.EntireRow)
            End If
        End If
    Next Cell
    
    ' if RowsToDelete were found then delete them
    If Not RowsToDelete Is Nothing Then
        RowsToDelete.Delete
    End If
    
    ' get again the last used row (because we deleted rows it's less)
    LastRow = ws.Cells(ws.Rows.Count, SelRng.Column - 1).End(xlUp).Row
    
    ' write the numeric date into the first cell
    SelRng.Value = Now()
    SelRng.NumberFormat = "YYMMDD" 'format the date
    
    ' fill down
    SelRng.AutoFill ws.Range(SelRng, ws.Cells(LastRow, SelRng.Column))
End Sub

字符串
会把它变成

我强烈建议不要使用dtToday = Format(Date, "yymmdd")将日期写入单元格,因为Format将返回一个看起来像日期的文本String。但这不再是一个日期,所以你不能用它来计算。始终使用数字日期,如SelRng.Value = Now()Date(),然后使用NumberFormat。这样,它保持一个数字日期,您可以计算,您可以轻松地改变格式,每当需要的。

相关问题