【问题标题】:VBA - fill range with function of cells from another rangeVBA - 用另一个范围的单元格功能填充范围
【发布时间】:2020-09-11 21:11:38
【问题描述】:

我正在寻找一种快速的方法来使用自定义函数的结果填充一系列单元格,该函数将另一个范围(大小相等)作为参数值。例如,我想根据 A 列用 my_function 的结果填充所有 E 列。

这按预期工作,但在 2000 个单元格处已经很慢:

With ActiveSheet:
    For i = 2 to 2000:
        .cells(i,5)=my_function(.cells,i,1)
    Next i
End With

我正在寻找这样的东西(用文本“测试”填充 E 列:

Set range_to_fill = ActiveSheet.Range("E2:E2000")
range_to_fill.Value="Testing"

但是除了用文本填充范围之外,我找不到其他方法来编写此内容。 第一步是尝试从 A 列复制值,但这只是将 E 列中的所有单元格都清空(老实说,我不太明白为什么):

range_to_fill.Value = Array((Range("A2:A2000").Value))

【问题讨论】:

  • my_function 到底是做什么的?也许你应该重构它以返回一个给定多单元输入的数组。
  • 是搜索功能;基本上是扭曲的查找;将单元格的值作为参数my_function(A2)

标签: excel vba function range


【解决方案1】:

您的函数MyFunction 需要返回一个二维值数组。然后你可以像这样使用它

Range("B2:B11").Value = MyFunction(Range("A2:A11").Value)

例如:

如果您有此输入:

以下函数将计算 x² 并在 B 列中输出

Option Explicit

Public Sub test()
    Range("B2:B11").Value = MyFunction(Range("A2:A11").Value)
End Sub

Public Function MyFunction(ByVal InputArr As Variant) As Variant
    'create an output array at the same size as the input array
    ReDim OutputArr(LBound(InputArr, 1) To UBound(InputArr, 1), LBound(InputArr, 2) To UBound(InputArr, 2))
    
    'loop through all rows/columns of the array and calculate something
    Dim iRow As Long
    For iRow = LBound(InputArr, 1) To UBound(InputArr, 1)
        Dim iCol As Long
        For iCol = LBound(InputArr, 2) To UBound(InputArr, 2)
            'calculate something, here x² as an example
            OutputArr(iRow, iCol) = InputArr(iRow, iCol) * InputArr(iRow, iCol)
        Next iCol
    Next iRow
    
    MyFunction = OutputArr 'return full array in your function
End Function

这种方法会非常快,因为它不会一次写入每个单元格,而是一次写入整个范围。计算在数组内完成,比直接使用单元格要快得多。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 2012-02-11
    • 1970-01-01
    • 2012-02-20
    • 2014-01-16
    • 2015-11-26
    相关资源
    最近更新 更多