Excel VBA尝试将“MAX”公式写入具有For-Loop的不同范围的单元格

问题描述 投票:-1回答:2

我试图让VBA将公式写入不同的单元格,这些单元格将找到由某些变量决定的Range的最大值。我的变量IJ是(数字/整数)。

这是我的代码。

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

曾试图多次重写第二部分(等号后面的部分)。通常我收到消息Compile error:Sub或Function not defined,它标记为“Max”。我认为Max(也尝试过大字母)是一个像SUM这样的内置函数。

我试图让它像这样写一个Excel公式到单元格中:

对于I=2J=3

细胞F5:=MAX(D5:E5) 细胞F6:=MAX(D6:E6) 细胞F7:=MAX(D7:E7)

即我想在单元格中使用一个公式,就像我在单元格中手动编写它来计算最大值一样,这样如果单元格D5,D7和E5到E7中的值发生变化,则可以找到新的最大值而不需要任何脚本跑步。

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

excel vba for-loop max formula
2个回答
2
投票

你不应该将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界面。选择MAX公式应该在的单元格。保持选择整个范围,将MAX公式放入其任何单元格中,就像您只为该单元格创建它一样,但不是按Enter键,而是按Ctrl + Enter。


1
投票

您必须小心区分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

更新:对不起,我没有查看公式的内容,当然RangeCells对象是VBA对象。您的公式中需要的是范围的地址,因此将行更改为

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

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

© www.soinside.com 2019 - 2024. All rights reserved.