在一个数组中找到 2 个元素,这些元素在一个简单的方程式中给出了目标结果

Find 2 elements in an array that give a target result in a simple equation

在电子产品中我需要一定的电阻,但是市场上的标准值有限。如果我将两个电阻器并联组合,我可以获得非常接近目标的结果。问题是哪 2 个电阻器可以提供最好的结果。

到目前为止我有这些元素:

  1. Excel column of 86 standard values from 0.25 to 1000000 in A2:A87 cells
  2. Target resistance that I enter in cell C3
  3. R1 and R2 - variables that can get 86 values from A2 to A87 cells
  4. equation giving the parallel resistance: Rtarget=R1*R2/(R1+R2)

我是一个 VBA 无知的人,我发现这个任务是学习更多 VBA 操作的好机会。在这里我从变量开始,但我不知道如何进行。非常感谢您的帮助。

Sub ResCom()

Dim Rstd As Double 
Dim Rt As Double, R1 As Double, R2 As Double

Rstd = Range("a2:a87").Value

.
.
.

End Sub

提前致谢!

只是为了让你开始,用这个继续

Option Explicit

Sub ResCom()

    Dim Rstd As Double
    Dim Rt As Double, R1 As Double, R2 As Double

    Rstd = Range("a2:a87").Value

    ' step thru upper triangle of R1/R2 values
    ' (lower triangle gives same results)
    Dim r1Row As Long, r2Row As Long
    For r1Row = LBound(Rstd) To UBound(Rstd)
        For r2Row = r1Row To UBound(Rstd)
            ' here is where you solve for  Rtarget=R1*R2/(R1+R2)
            ' R1 = Rstd(r1Row)
        Next r2Row
    Next r1Row


End Sub

试试这个

Sub ResCom()
    Dim Rt as Double, R1 as Double, R2 as Double

    Rt = Range("C3").Value

    For i = 2 to 87
       R1 = Range("A" & i).Value
       if R1 < Rt Then
          For j = 2 to 87
             R2 = Range("A" & j).Value
             if Round(Rt,2) = Round((R1*R2/(R1+R2)),2) then
                ' Success you have found a Resistance Combination that matches
             End If
          Next j
       End If
    Next i
End Sub

...

我们可以创建一个可以轻松重复使用的工具。

首先在A2A87中输入电阻值。然后 运行:

Sub tablemaker()
    Dim i As Long, j As Long, K As Long

    K = 2
    For i = 2 To 87
        For j = i To 87
            Cells(K, 2) = Cells(i, 1)
            Cells(K, 3) = Cells(j, 1)
            K = K + 1
        Next j
    Next i

    Range("D2:D" & K - 1).Formula = "=B2*C2/(C2+B2)"
End Sub

这将在 B2D3742 中产生阻力 table。 table 列出组合对和每对的相关电阻。

(不需要排列,因为 4,2 和 2,4 实际上是一样的)

然后在单元格E2中输入目标值。在E3中输入数组公式:

=MATCH(MIN(ABS(D2:D3742-E2)),ABS(D2:D3742-E2),0)

数组公式必须用Ctrl + Shift + 输入Enter 而不仅仅是 Enter 键。如果操作正确,公式将在公式栏中显示,并带有花括号。

这给出 table 中与 E4 中最接近的 match.Finally 的行输入:

=INDEX(B2:B3741,$E3)

然后复制到F4

要重新运行这个,只需更改E2

中的目标