您的函数正在返回一个对象,因此您需要使用“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,因为您只需处理该命令一次即可定义范围。最后,请注意您可能会选择一些空单元格,尤其是在您使用范围的底部,如果某些列比其他列短。
祝你的项目好运。