ActiveCell.Offset在筛选器处于活动状态时不起作用

时间:2020-03-14 11:51:57

标签: excel vba

代码:-

cd C:\Python37\projects
python file.py

它给出以下结果:-

enter image description here

但是在这种情况下,它应该是“ B5 ”。

主要是在以下代码中进行更改:

Sub Macro6()
'
' Macro6 Macro
'
' Keyboard Shortcut: Ctrl+Shift+A
'
    Columns("B:B").Select
    Selection.Insert Shift:=xlToRight
    Range("B1").Select
    ActiveCell.FormulaR1C1 = "p"
    Range("C1").Select
    Selection.AutoFilter
    ActiveSheet.Range("A1", Range("C" & Rows.Count).End(xlUp)).AutoFilter Field:=3, Criteria1:="Credit"
    ActiveCell.Offset(1, -1).Select
    'ActiveCell.Offset(1, 0).Select
    'Selection.AutoFilter
End Sub

1 个答案:

答案 0 :(得分:0)

自动过滤器可以创建非连续范围,例如$C$1:$C$2,$C$6,$C$11,$C$15,$C$19,这意味着要处理多个区域。

Sub Macro6()

    Dim ws As Worksheet, lastrow As Long
    Dim rngFilter As Range, rng As Variant
    Set ws = ThisWorkbook.ActiveSheet
    ws.Columns("B:B").Insert Shift:=xlToRight

    ws.Range("B1").Value = "p"
    If ws.AutoFilterMode = True Then ws.AutoFilter.ShowAllData

    lastrow = ws.Range("C" & Rows.Count).End(xlUp).Row
    Set rngFilter = ws.Range("A1:C" & lastrow)
    rngFilter.AutoFilter Field:=3, Criteria1:="credit"
    Set rng = Intersect(rngFilter.SpecialCells(xlCellTypeVisible), ws.Columns(3))

    If rng.Areas.Count = 1 Then
        If rng.Cells.Count = 1 Then
            ' no cell to select
            MsgBox "No cell to select", vbCritical
        Else
            rng.Offset(1, -1).Select
        End If
    Else
        If rng.Areas(1).Cells.Count > 1 Then
            rng.Offset(1, -1).Select
        Else
            rng.Areas(2).Offset(0, -1).Select
        End If
    End If

End Sub