[英]2-DRange -> Array -> 2D-Range with UDF Excel 2007 VBA
I'm trying to create a UDF that has 2D-Range as the input, resizes it, adjusts one of its values and has new 2D-Range as output. 我正在尝试创建一个以2D范围作为输入的UDF,调整其大小,调整其值之一,并以新的2D范围作为输出。 It is important to have Range as output since ranges will be used it other functions.
将范围作为输出非常重要,因为范围将与其他功能一起使用。 Unfortunately other function do not recognize new 2D-Range as Range.
不幸的是,其他功能无法将新的2D范围识别为范围。
Function Func1(Structure As Range) As Variant
i = 3
Dim temp1 As Range
Dim temp2 As Range
Set temp1 = Structure.Resize(i, 3)
Dim arr1()
ReDim arr1(1 To i, 1 To 3)
arr1 = temp1
arr1(2, 2) = 100
Func1 = arr1
End Function
Function Func2(InputArray)
Func2 = InputArray.Rows.Count
End Function
So - function Func2(Func1(Structure)) does not work. 因此-函数Func2(Func1(Structure))不起作用。 it should give out number of rows in new 2D-Range.
它应该给出新的2D范围的行数。
Will anyone help please? 有人可以帮忙吗?
I'm using Excel 2007 我正在使用Excel 2007
Tim Williams and KazJaw are correct, you might consider using another approach. Tim Williams和KazJaw是正确的,您可以考虑使用另一种方法。 However, I have a possible solution and the code is below.
但是,我有一个可能的解决方案,下面的代码。 Note that this approach will be slow and you must be strict with your exception handling.
请注意,这种方法将很慢,并且您必须严格处理异常。
Option Explicit
Function Func1(Structure As Range) As Range
Dim TempWs As Worksheet 'Needed to create a range
Dim temp1 As Range 'Resized input range
Dim temp2 As Range 'Why is this needed?
Dim arr1 As Range 'Range to be returned
Dim i As Integer '?
'Add a temporary worksheet to the end
Set TempWs = ThisWorkbook.Worksheets.Add(, _
ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
i = 3
Set temp1 = Structure.Resize(i, 3)
With TempWs
'Set the temporary range and get the existing values
Set arr1 = TempWs.Range(.Cells(1, 1), .Cells(i, 3))
End With
arr1.Value = temp1.Value
arr1(2, 2) = 100
Set Func1 = arr1
'clean up
Set temp1 = Nothing
Set temp2 = Nothing
Set arr1 = Nothing
Set TempWs = Nothing
End Function
Sub test()
Dim GetRange As Range
Set GetRange = Func1(Range("A1:C3"))
ThisWorkbook.Worksheets(1).Range("D1:F3").Value = GetRange.Value
'You need to delete the temporary worksheet
Application.DisplayAlerts = False
GetRange.Worksheet.Delete
Application.DisplayAlerts = True
Set GetRange = Nothing
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.