我正在尝试在与特定过滤年份对应的每个单元格中插入“ Y”。 例如:过滤年份-2018年,我将在c列的所有单元格中均使用“ Y”。
但是,如果我仅包含1行数据(2018年仅在单元格b2中),则我的宏将继续运行并显示运行时错误。
numbers = [-2, 2, 3]
答案 0 :(得分:0)
Sub Macro1()
With Workbooks(REF).Sheets(REF) 'Change
'Set filter
.Range(Cells(1, 2), Cells(1, 3)).AutoFilter Field:=1, Criteria1:="2018"
'Determine last row
LRow = .Cells(.Rows.Count, "B").End(xlUp).Row
'For all visible (filtered) rows, value "Y" in col C
If LRow = 3 Then
.Range("C3").Value = "Y"
Else
.Range("B3:B" & LRow).SpecialCells(xlCellTypeVisible).Offset(0, 1).Value = "Y"
End If
End With
End Sub
编辑
下面的Sub将清除过滤器并正确处理第2行中过滤后的值的情况,这可能导致错误发生
Sub Macro1()
With Workbooks(REF).Sheets(REF) 'Change
'Clear filter
If .AutoFilterMode Then Cells.AutoFilter
'Set filter
.Range("A:B").AutoFilter Field:=1, Criteria1:="2018"
'Determine last row
LRow = .Cells(.Rows.Count, "B").End(xlUp).Row
'For all visible (filtered) rows, value "Y" in col C
If LRow > 2 Then
If LRow = 3 Then
.Range("C3").Value = "Y"
Else
.Range("B3:B" & LRow).SpecialCells(xlCellTypeVisible).Offset(0, 1).Value = "Y"
End If
End If
End With
End Sub
答案 1 :(得分:0)
TagFilteredYear
做您想做的事。 TestMe
仅用于测试 TagFilteredYear
UDF
Option Explicit
Sub TestMe()
TagFilteredYear "2018", "Y"
End Sub
Sub TagFilteredYear(ByVal sFilterCriteria As String, ByVal sSetValueTo As String)
Dim iLRow As Long
With ThisWorkbook.Worksheets("Sheet1")
' Clear any existing autofilter
If .AutoFilterMode Then Cells.AutoFilter
' Get row count
iLRow = Cells(Rows.Count, "B").End(xlUp).Row
' Filter range
.Range("A:B").AutoFilter Field:=1, Criteria1:=sFilterCriteria
' Populate visible cells in column C with specified value (starting form 2 row)
.Range("C2:C" & iLRow).SpecialCells(xlCellTypeVisible).Value = sSetValueTo
End With
End Sub