Excel中的VBA函数可以返回范围吗? [英] Can a VBA function in Excel return a range?

查看:211
本文介绍了Excel中的VBA函数可以返回范围吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在新的工作簿中:

  A1 B1 
5 4

功能Test1()As Integer
Dim rg As Range
Set rg = Test2()
Test1 = rg.Cells(1,1).Value
结束函数
函数Test2()As Range
Dim rg As Range
Set rg =范围(A1:B1)
Test2 = rg
结束功能

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

解决方案

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

 函数Test1()As整数
Dim rg As Range
设置rg = Test2()
Test1 = rg.Cells(1,1).Value
结束函数

函数Test2()As Range
Dim rg As Range
设置rg =范围(A1:B1)
设置Test2 = rg'< - 不要忘记这里的$
结束功能


I seem to be getting a type mismatch error when trying to do something like this:

In new workbook:

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

Adding =Test1() should return 5 but the code seems to terminate when returning a range from test2(). Is it possible to return a range?

解决方案

A range is an object. Assigning objects requires the use of the SET keyword, and looks like you forgot one in your Test2 function:

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

这篇关于Excel中的VBA函数可以返回范围吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆