1

尝试编写范围函数的联合

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

我没有做对(我认为):

 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
4

2 回答 2

2

首先,使用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
于 2015-08-30T20:26:41.057 回答
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,因为您只需处理该命令一次即可定义范围。最后,请注意您可能会选择一些空单元格,尤其是在您使用范围的底部,如果某些列比其他列短。

祝你的项目好运。

于 2015-08-30T20:27:05.850 回答