繁体   English   中英

在ActiveSheet.Range中应用动态范围

[英]Apply Dynamic Range in ActiveSheet.Range

我运行了一个宏,以使用指定的数据集粘贴,编辑,更改和拆分数据。

在新的数据集(更多数据)上,我的数据范围出现问题。

ActiveSheet.Range("$A$1:$T$299").AutoFilter Field:=6, Criteria1:= _
  "=Site Reference A", Operator:=xlOr, Criteria2:= _
  "=Site Reference A  Total"
Range("A1:T299").Select
Range("F160").Activate
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Copy

我的数据范围是$ A $ 1:$ T $ 299。 我将如何使其动态化?

范例-
数据集A有200列。
数据集B有230列。

有点长,但是完整的代码是在工作表中查找最后一行和最后一列的更安全的方法。

Dim Sht As Worksheet
Dim FiltRng As Range
Dim LastCol As Long
Dim LastRow As Long

Set Sht = ActiveSheet '<-- better not rely on ActiveSheet

LastRow = FindLastRow(Sht)
LastCol = FindLastCol(Sht)

With Sht
    Set FiltRng = .Range(.Cells(1, 1), .Cells(LastRow, LastCol)) ' <-- set the filtered range dynamically
End With

With Sht
    FiltRng.AutoFilter Field:=6, Criteria1:= _
        "=Site Reference A", Operator:=xlOr, Criteria2:= _
        "=Site Reference A  Total"

    ' rest of your code goes here

End With

“================================================= =========

Function FindLastCol(Sht As Worksheet) As Long

' This Function finds the last col in a worksheet, and returns the column number

Dim LastCell As Range

With Sht
    Set LastCell = .Cells.Find(What:="*", After:=.Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, _
                        SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)
    If Not LastCell Is Nothing Then
        FindLastCol = LastCell.Column
    Else
        MsgBox "Error! worksheet is empty", vbCritical
        End
    End If
End With

End Function

“================================================= =========

Function FindLastRow(Sht As Worksheet) As Long

' This Function finds the last row in a worksheet, and returns the row number

Dim LastCell As Range

With Sht
    Set LastCell = .Cells.Find(What:="*", After:=.Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, _
                        SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
    If Not LastCell Is Nothing Then
        FindLastRow = LastCell.Row
    Else
        MsgBox "Error! worksheet is empty", vbCritical
        End
    End If
End With

End Function

如果列A中没有其他数据,则可以使用动态命名范围。 只需使用以下公式作为命名范围的范围,然后在代码中引用命名范围。 请记住,这仅在A列中没有其他数据时才有效。

 =OFFSET($A$1,0,0,COUNTA($A:$A),1)

暂无
暂无

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

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