首页 > 解决方案 > 采用动态数组并返回动态数组的 VBA 函数

问题描述

我有一个在 A1:A100 中有重复的数字列表。使用 Excel 新的动态数组函数,我们可以在 Cell D1 中写入=UNIQUE(A1:A100)以获得唯一列表。

然后,我们可以在单元格 E1=D1#+100中写入,以根据 D 列的值获取动态列表。

现在,我想编写一个 VBA 函数MYFUN来实现相同的目的,这样我们就可以=MYFUN(D1#)在单元格 F1 中编写以获得与 E 列相同的值。

有人知道怎么写吗?

标签: vbaexcel-formula

解决方案


不是 100% 清楚你想要做什么 - 似乎缺少一些东西。

但是,当您=MYFUN(D1#)在 F1 中输入公式时,这将返回 E 列中的内容。

Function MYFUN(rng As Range) As Variant
    MYFUN = Evaluate(rng.Address & "+100")
End Function

这是一个不使用的替代方案Evaluate

Function MYFUN(rng As Range) As Variant
Dim arr As Variant
Dim idx As Long

    ReDim arr(1 To rng.Rows.Count, 1 To 1)
        
    For idx = LBound(arr, 1) To UBound(arr, 1)
        arr(idx, 1) = rng.Cells(idx, 1) + 100
    Next idx
    
    MYFUN = arr
    
End Function

推荐阅读