根据单元格创建公式

时间:2014-01-17 19:23:35

标签: excel vba excel-vba excel-formula

我需要创建一个基于单元格的匹配公式,如下面的示例:

+------+--------+--------+
| Col1 | SumCol | Val    | 
+------+--------+--------+
|    1 |      8 | v1     | '=Match([otherWorkbook]MainSheet!C1,RC3,[otherWorkbook]MainSheet!C8)
|    2 |      5 | v44*   | '=Match([otherWorkbook]MainSheet!C2,RC3,[otherWorkbook]MainSheet!C5)
|    3 |      7 | ls*    | '=Match([otherWorkbook]MainSheet!C3,RC3,[otherWorkbook]MainSheet!C7)
+------+--------+--------+

要构建公式,我需要获取字符串“[otherWorkbook] MainSheet”并与Column Col1 中的Cell连接。然后我需要从Column Val 中获取值。最后,我再次连接字符串“[otherWorkbook] MainSheet”和Column SumCol 中的单元格。

我期待像=Match([otherWorkbook]MainSheet!C1,RC3,[otherWorkbook]MainSheet!C8)这样的公式。我可以使用两个临时列进行连接,然后构建wole公式。

PS:我正在使用VBA来制作公式,所以我可以用它来达到我的目标。

1 个答案:

答案 0 :(得分:1)

也许你需要像这个

这样的东西
Sub AddFormulas()

    myOtherWorkbook = "[otherWorkbook]"

    myFormula1 = "=Match(" & myOtherWorkbook & "MainSheet!C"
    myFormula2 = ",RC3," & myOtherWorkbook & "MainSheet!C"

    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    For x = 2 To lastRow  'Loops from row 2 to the last of column "A"

        Cells(x, 4).Formula = myFormula1 & Cells(x, 1) & myFormula2 & Cells(x, 2) & ")"

    Next x


End Sub
相关问题