在尝试执行以下操作时,我似乎遇到类型不匹配错误:
在新工作簿中:
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()返回范围时终止.是否可以返回范围?
范围是一个对象.分配对象需要使用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
您还可以返回Variant()
表示值数组的a.下面是一个函数示例,它将值从一个范围反转到一个新范围:
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
是一个数组,并且范围包含多行列比直接在单元格上逐个执行操作要快许多倍.