【问题标题】:2-DRange -> Array -> 2D-Range with UDF Excel 2007 VBA2-DRange -> 数组 -> 2D-Range 与 UDF Excel 2007 VBA
【发布时间】:2013-03-28 08:34:59
【问题描述】:

我正在尝试创建一个以 2D-Range 作为输入的 UDF,调整它的大小,调整它的一个值并将新的 2D-Range 作为输出。将 Range 作为输出很重要,因为 Range 将用于其他功能。不幸的是,其他函数无法将新的 2D-Range 识别为 Range。


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-Range 中的行数。

有人帮忙吗?

我使用的是 Excel 2007

【问题讨论】:

  • 您不能从头开始创建范围:您只能引用现有范围。因此,函数不能输出“新”范围,它只能修改输入范围,或者输出对另一个位置的不同范围的引用。
  • Tim,STRUCTURE 是电子表格上的二维范围,Func1 应该更改旧范围并输出新范围。然后我使用 Func2 来计算新范围内的行数(以及更复杂的函数)以使用新范围。最初我用 Func2 引用旧范围(结构)来获取行数,即 Func2(结构)。但现在我需要修改原始范围,因此我使用 Func1。
  • 可能需要其他评论。我不想将新范围粘贴到电子表格中。我会参考原始范围来获取 Func2 的值,即上面的 Func2(Func1(Structure))。
  • Func1 返回数组而不是范围。稍后您需要对该 ARRAY 做什么 - 仅检查您在 Func2 中尝试执行的元素数量或更多?要返回 Funct2 中使用的元素数,请使用以下结构:Func2 = Ubound(InputArray, 1)
  • KazJaw,是的,这个 Func2 = Ubound(InputArray, 1) 返回元素的数量。但这是最简单的功能。我正在尝试做的是以下内容。我有一个叫做 STRUCTURE 的范围,然后我用 Func2(STRUCTURE) 来计算各种东西。现在我需要修改 STRUCTURE(截断并更改元素) - 因此我使用 Func1。理想情况下,我需要得到像 Func2(Func1(Structure)) 这样的公式。理论上这个函数应该输出新范围内的行数。

标签: arrays vba resize range user-defined-functions


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多