获取 Usedrange 的函数出现错误 91

Function to get Usedrange gets error 91

正在尝试编写范围联合函数

我得到“对象变量或未设置块”

我没弄对(我认为):

 With Rng
     UnionRange = Intersect(ws.UsedRange, Rng.EntireColumn)
 End With



Sub iUnionRange()
Dim R As Range

'Check to see if the Function is working
Set R = UnionRange("Elements", Range("A1:D1, G1:G1, I1:K1"))
R.Select

End Sub

函数

Function UnionRange(shtName As String, Rng As Range) As Range

 Set ws = ThisWorkbook.Sheets(shtName)
 If Rng Is Nothing Then Exit Function

 With ws.Rng
     UnionRange = Intersect(ws.UsedRange, .EntireColumn)
 End With

End Function

首先,使用Set关键字将一个对象赋值给一个变量,所以UnionRange =应该是Set UnionRange =。在检索范围时指定一个 sheet 对象,这样做不需要将 sheet 名称传递给函数,因为 Rng.Parent returns sheet 对象。

例子如下:

Sub test()
    Dim Q As Range
    Dim R As Range
    Set Q = Sheets("Elements").Range("A1:D1, G1:G1, I1:K1")
    Q.Select
    Set R = UnionRange(Q)
    R.Select
End Sub

Function UnionRange(Rng As Range) As Range
    If Rng Is Nothing Then Exit Function
    Set UnionRange = Intersect(Rng.Parent.UsedRange, Rng.EntireColumn)
End Function

您的函数正在返回一个对象,因此您需要使用 'Set',即:

Set UnionRange = Intersect(ws.UsedRange, .EntireColumn)

如果在 "Elements" worksheet 未激活时调用 'R.Select',我认为您的代码也可能会引发错误(即用户激活了另一个 sheet).我也想知道您是否只是将 Range 参数用作单元格的地址,而它可以为您做更多的事情。

如果是我,我会把代码改成下面这样:

Sub iUnionRange()
    Dim ws As Worksheet
    Dim r As Range

    ' Define the worksheet
    Set ws = ThisWorkbook.Worksheets("Elements")

    ' Call the cell selection function
    Set r = UnionRange(ws.Range("A1:D1, G1:G1, I1:K1"))

    ' Note, if you go to the properties of the "Elements"
    ' worksheet, you can change its name property to,
    ' say, ElementsSht and simply refer to the object by that name.
    ' As well as being easier to code, it does protect you
    ' from an error if a user changes the sheet name in
    ' Excel.
    ' So you could just uncomment the following line:
    'Set r = UnionRange(ElementSht.Range("A1:D1, G1:G1, I1:K1"))

    ' Select the target range
    SafeSelect r
End Sub

Function UnionRange(target As Range) As Range
    If target Is Nothing Then Exit Function
    Set UnionRange = Intersect(target.Worksheet.UsedRange, target.EntireColumn)
End Function

Sub SafeSelect(target As Range)
    ' Check that the range object is not nothing
    ' and the worksheet to be selected is active
    If Not target Is Nothing Then
        target.Worksheet.Activate
        target.Select
    End If
End Sub

如果您打算多次调用此例程,那么也许可以在函数范围之外定义 UsedRange,因为您只需处理该命令一次即可定义范围。最后,请注意,如果某些列比其他列短,您可能会选择一些空单元格,尤其是在您使用范围的底部。

祝你项目顺利。