在尝试执行此类操作时,我似乎遇到了类型不匹配错误:
在新工作簿中:
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()应返回5,但代码似乎在从test2()返回范围时终止。是否可以返回范围?
答案 0 :(得分:45)
范围是一个对象。分配对象需要使用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
答案 1 :(得分:8)
您还可以返回表示值数组的Variant()
。下面是一个函数示例,它将值从一个范围反转到一个新范围:
Public Function ReverseValues(ByRef r_values As Range) As Variant()
Dim i As Integer, j As Integer, N As Integer, M As Integer
Dim y() As Variant
N = r_values.Rows.Count
M = r_values.Columns.Count
y = r_values.value 'copy values from sheet into an array
'y now is a Variant(1 to N, 1 to M)
Dim t as Variant
For i = 1 To N / 2
For j = 1 To M
t = y(i, j)
y(i, j) = y(N - i + 1, j)
y(N - i + 1, j) = t
Next j
Next i
ReverseValues = y
End Function
在工作表中,您必须将此函数应用为数组公式(使用Ctrl
- Shift
- Enter
)并选择适当数量的单元格。 Swap()函数的细节在这里并不重要。
注意对于很多行,这非常有效。当x = Range.Value
是一个数组并且范围包含多行时,执行Range.Value = x
和x
操作列比直接执行操作快多倍细胞。
答案 2 :(得分:4)
将Test2中的最后一行更改为:
Set Test2 = rg
答案 3 :(得分:2)
这也有效
Function Test2(Rng As Range) As Range
Set Test2 = Rng
End Function