EXCEL VBA - 需要过滤,然后从第二行自动填充一个值到最低行

标签 excel vba

我正在尝试将其余行自动填充到其中包含值的最低行。查看其他帖子以及我自己的研究和测试,我创建了一个代码。但是,我的代码有一个过滤器,这些过滤器值会随着时间而变化。正如您在代码中看到的,我选择 AB2 并插入 Yes,然后自动填充到底部或 Z 列中的最小值。但是有时由于过滤器 No 和 Yes,第二行可能是 AB3 甚至 AB4 .有没有办法让这个功能自动化,我可以将值 Yes 放在第一行下面,然后自动填充它,而不必每次都更改 AB 旁边的数字。

Columns("F:H").Select
Selection.AutoFilter
ActiveSheet.Range("$F$1:$H$13889").AutoFilter Field:=1, Criteria1:="No"
ActiveSheet.Range("$F$1:$H$13889").AutoFilter Field:=3, Criteria1:="Yes"
Range("AB2").Select
ActiveCell.FormulaR1C1 = "Yes"
Selection.AutoFill Destination:=Range("AB2:AB" & Range("Z" & Rows.Count).End(xlUp).Row)
Range(Selection, Selection.End(xlDown)).Select

最佳答案

应该这样做,因为你永远不知道从哪里开始写你的“眼睛”:

Option Explicit
Sub Test()
    
    'Assuming you are running the code on the same workbook it is written
    'change SheetName for the sheet name where you want it to run,
    'if not, change also ThisWorkbook for Workbooks("WorkbookName.Extension")
    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("SheetName")
    
    With ws
        'This is to get the last row with data, so change Z for whichever column
        'has the last row with data
        Dim LastRow As Long: LastRow = .Cells(.Rows.Count, "Z").End(xlUp).Row
        'This gets the last column with data, assuming you have all your headers in row 1
        Dim LastCol As Long: LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
        'Put your whole range into a variable
        Dim FilterRange As Range: Set FilterRange = .Range("A1", .Cells(LastRow, LastCol))
        'Filter by your criteria
        FilterRange.AutoFilter 1, "No"
        FilterRange.AutoFilter 3, "Yes"
        'Now find the first row without data in column AB
        Dim FirstRow As Long
        LastRow = .Cells(.Rows.Count, "Z").End(xlUp).Row
        Set FilterRange = .Range("AB2:AB" & LastRow)
        Dim cell As Range
        For Each cell In FilterRange
            If cell.EntireRow.Hidden = False Then
                FirstRow = cell.Row
                Exit For
            End If
        Next cell
        'Fill all your visible cells in Range AB with Yes
        .Range("AB" & FirstRow & ":AB" & LastRow).SpecialCells(xlCellTypeVisible) = "Yes"
    End With

End Sub

关于EXCEL VBA - 需要过滤,然后从第二行自动填充一个值到最低行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63277056/

相关文章:

vba - 使用 Excel VBA 列出特定模式的文件

excel - 如何从俄语 Excel 中的日期获取英文月份名称?

Excel成绩单

excel - 是否可以从此示例数据创建嵌套字典?

excel - 导出所有 Windchill 用户名

Excel 条件数据和文本处理

excel - 如何从excel中重复多次的单元格中获取唯一值?

excel - 循环遍历已过滤的枢轴项目

excel - 将 MS Access 表拆分为多个部分并使用 VBA 导出到 Excel

vba - 从字符串 VBA 或函数的开头删除零