获取 Usedrange 的函数出现错误 91

Posted

技术标签:

【中文标题】获取 Usedrange 的函数出现错误 91【英文标题】:Function to get Usedrange gets error 91 【发布时间】:2015-08-30 18:56:11 【问题描述】:

尝试编写范围函数的并集

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

我没有做对(我认为):

 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

【问题讨论】:

【参考方案1】:

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

下面有例子:

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

【讨论】:

感谢 omegastripes,我觉得有点愚蠢,忽略了 Set【参考方案2】:

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

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

我认为,如果在“元素”工作表未处于活动状态(即用户已激活另一个工作表)时调用“R.Select”,您的代码也可能会引发错误。我也想知道您是否将 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,因为您只需处理该命令一次即可定义范围。最后,请注意,您可能会选择一些空单元格,尤其是在您使用范围的底部,如果某些列比其他列短。

祝你的项目好运。

【讨论】:

谢谢 Ambie,您的 cmets 很有帮助

以上是关于获取 Usedrange 的函数出现错误 91的主要内容,如果未能解决你的问题,请参考以下文章

Excel vba 运行时错误 91 对象变量或未设置块

类函数中的错误 91

出现错误 TypeError: Promise.any 不是函数

Excel vba:.find 函数返回运行时错误 91

VBA 缺少 Worksheet.Range 作为值并不断获取未设置对象变量(错误 91)

宏以获取列中每个唯一值的范围