尝试执行以下操作时,我似乎收到类型不匹配错误:

在新工作簿中:

A1 B1
5  4

Function Test1() As Integer
    Dim rg As Range
    Set rg = Test2()
    Test1 = rg.Cells(1, 1).Value
End Function
Function Test2() As Range
    Dim rg As Range
    Set rg = Range("A1:B1")
    Test2 = rg
End Function

添加= Test1()应该返回5,但是从test2()返回范围时代码似乎终止。是否可以返回范围?

最佳答案

范围是一个对象。分配对象需要使用SET关键字,并且看起来您在Test2函数中忘记了一个:

Function Test1() As Integer
    Dim rg As Range
    Set rg = Test2()
    Test1 = rg.Cells(1, 1).Value
End Function

Function Test2() As Range
    Dim rg As Range
    Set rg = Range("A1:B1")
    Set Test2 = rg         '<-- Don't forget the SET here'
End Function

10-05 18:50