【问题标题】:Excel VBA UDF finding maximum spread between two assigned values and two rangesExcel VBA UDF 查找两个分配值和两个范围之间的最大分布
【发布时间】:2018-07-31 00:02:28
【问题描述】:

最近发表了一篇类似的帖子,由于我的问题措辞错误,我不得不删除。我正在尝试创建一个 Excel VBA UDF,其中将分配范围的每一行与分配的值进行比较,并得出系列中的最大范围。请注意 range1 和 range2 的长度总是相等的,我只是试图对范围内的每个唯一行执行分析。例如,下面的日期集将有 4 次比较,由于 4 行,maxrangecheck 结果为180%

loop1 = 3
loop2 = 1000

range1  range2  range1 %    range2 %    maxrangecheck
5       882     67%         -12%                79%
6       842     100%        -16%               116%
8       869     167%        -13%               180%
2       859     -33%        -14%               -19%

下面的代码是我设计的 - 我知道它不起作用,但希望能给我想要做的事情提供一个想法,

Function maxrangecheck(loop1 As Double, loop2 as Double, range1 As range, range2 As range)

Dim i As Range
Dim j As Range
Dim checki As Double
Dim checkj As Double
Dim spread As Double
Dim output As Double

For Each i In range1
    checki = i.Value - loop1

For Each j In range2
    checkj = j.Value - loop2

spread = checki - checkj

If spread >= spread Then
output = spread
Else:
output = output

Next j
Next i

maxrangecheck = output

End Function

感谢您的帮助,谢谢!

【问题讨论】:

  • 我在this Code Review question 上描述了执行此操作的一般算法。应该是一个简单的 VBA 端口。
  • 如果你想像For Each i In range1 这样循环,那么i 的类型应该是Range,而不是Long
  • 你究竟是如何得到 78% 的结果的?我可能错过了一些东西。
  • 你只是想在第 4 列中找到最大值吗?
  • 另外,If spread > spread 永远不会起作用,因此输出将始终保持为零。

标签: vba excel


【解决方案1】:

试试这个。它涵盖了我在 cmets 和 Vityata 中提出的观点。就目前而言,如果所有检查均为负数,则它将返回零,因此可能需要更改。

Function maxrangecheck(loop1 As Double, loop2 As Double, range1 As Range, range2 As Range)

Dim i As Long
Dim j As Long
Dim checki As Double
Dim checkj As Double
Dim spread As Double
Dim output As Double

For i = 1 To range1.Count
    checki = (range1(i).Value - loop1) / loop1
    checkj = (range2(i).Value - loop2) / loop2
    spread = checki - checkj
    If spread > output Then
        output = spread
    End If
Next i

maxrangecheck = output

End Function
'a quick test
Sub x()

MsgBox Format(maxrangecheck(3, 1000, Range("A2:A5"), Range("B2:B5")), "0.0%")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多