[英]2-DRange -> Array -> 2D-Range with UDF Excel 2007 VBA
我正在嘗試創建一個以2D范圍作為輸入的UDF,調整其大小,調整其值之一,並以新的2D范圍作為輸出。 將范圍作為輸出非常重要,因為范圍將與其他功能一起使用。 不幸的是,其他功能無法將新的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
因此-函數Func2(Func1(Structure))不起作用。 它應該給出新的2D范圍的行數。
有人可以幫忙嗎?
我正在使用Excel 2007
Tim Williams和KazJaw是正確的,您可以考慮使用另一種方法。 但是,我有一個可能的解決方案,下面的代碼。 請注意,這種方法將很慢,並且您必須嚴格處理異常。
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.