Excel VBA 尝试使用 For 循环将 "MAX" 公式写入具有不同范围的单元格

Excel VBA Trying to write a "MAX" formula to Cells with different Ranges with For-Loop

我正在尝试让 VBA 将公式写入不同的单元格,以找到由某些变量决定的范围的最大值。我的变量 IJ 是 (numbers/Integers).

这是我的代码。

Sub AddMAX()
    Dim I As Integer
    Dim J As Integer
    Dim L As Integer

    I = InputBox("Number of columns to check max value")
    J = InputBox("Number of Rows to add formula inn and find max value of that row")

    For L = 5 To 4 + J
        Worksheets(1).Cells(L, 4 + I).Formula = "=" & Max(Range(Cells(L, 4), Cells(L, 3 + I)))
    Next L
End Sub

已经多次尝试重写第二部分(等号后面的部分)。通常我会收到消息编译错误:未定义子或函数,它标记 "Max"。我认为 Max(也尝试使用大字母)是一个内置函数,如 SUM 等。

我试图让它在单元格中写入这样的 Excel 公式:

对于I=2J=3

单元格 F5:=MAX(D5:E5)
单元格 F6:=MAX(D6:E6)
单元格 F7:=MAX(D7:E7)

即我想要一个单元格中的公式,就像我在单元格中手动编写的那样计算最大值,这样如果单元格 D5、D7 和 E5 到 E7 中的值发生变化,将找到新的最大值,而无需任何脚本运行.

如果有什么不清楚的地方,请告诉我。

你必须小心区分 VBA 看到的部分和最终公式。

如果你写

Worksheets(1).Cells(L, 4 + I).Formula = "=" & Max(Range(Cells(L, 4), Cells(L, 3 + I)))

Max(以及以下所有内容)被 VBA-解释器看到,而不是 Excel。但是没有 Max-函数,你会得到一个(编译器)错误。

如果你写

Worksheets(1).Cells(L, 4 + I).Formula = "=Max(Range(Cells(L, 4), Cells(L, 3 + I)))"

VBA-解释器将整个内容视为一个字符串。它无法处理 LI 之类的变量,因为它看不到它们。因此,您最终会得到一个与您编写的公式完全相同的公式 - Excel(而不是 VBA)会向您显示错误,因为它不理解 LI.

您需要的是一条语句(在 VBA 中)创建一个包含变量的实际 的字符串,并将其分配给 cell.formula.我强烈建议您首先将其分配给一个字符串变量 - 它使调试更容易:

Dim formula As String
formula = "=Max(Range(Cells(" & L & ", 4), Cells(" & L & ", 3 + " & I & ")))"
Debug.Print formula
Worksheets(1).Cells(L, 4 + I).Formula = formula

Update:抱歉,我根本没有看公式的内容,当然 RangeCells-objects 是VBA 个对象。您在公式中需要的是范围的地址,因此将行更改为

formula = "=MAX(" & Range(Cells(L, 4), Cells(L, 3 + i)).Address & ")"

现在VBA将创建一个Range并将地址放入公式字符串中。

您不应该将 RangeCells 放在公式字符串中,它们对 Excel 公式引擎没有任何意义。您需要 Address 个单元格:

Dim I As Long
Dim J As Long
Dim L As Long

I = InputBox("Number of columns to check max value")
J = InputBox("Number of Rows to add formula inn and find max value of that row")
L = 5

With Worksheets(1)
  .Range(.Cells(L, 4 + I), .Cells(4 + J, 4 + I)).Formula = "=MAX(" & .Cells(L, 4).Address(False, False) & ":" & .Cells(L, I + 3).Address(False, False) & ")"
End With

实际上所有单元格的公式都相同,这就是为什么可以在一次分配中为整个范围分配它。它在 A1 引用符号中看起来不同,但如果在 Excel 设置中切换到 R1C1,您会发现它们是相同的。这也意味着首先创建公式 using the R1C1 notation 更容易:

Dim I As Long
Dim J As Long
Dim L As Long

I = InputBox("Number of columns to check max value")
J = InputBox("Number of Rows to add formula inn and find max value of that row")
L = 5

With Worksheets(1)
  .Range(.Cells(L, 4 + I), .Cells(4 + J, 4 + I)).FormulaR1C1 = "=MAX(RC[-" & I & "]:RC[-1])"
End With

但在我看来,您应该按照预期的方式使用 Excel 界面。 Select MAX 公式所在的单元格。保持选中整个范围,将 MAX 公式放入其中的任何单元格,就好像您只是为该单元格创建它一样,但不要按 Enter,而是按 Ctrl+输入.