计算单元格并存储在数组中以找到最小值; " min" -function会出现问题

时间:2017-08-01 13:41:23

标签: arrays vba excel-vba min excel

我试图根据用户输入从表中计算出最便宜的产品替代品。 代码应该是 a)获取输入数字,产品大小(来自用户界面表中的K19)并将其与表格中的正确行匹配,以便找到此大小的不同替代方案。 b)将特定成本乘以大小以获得每个替代方案的总成本(因此变量Mx,Nx等是每个替代方案的特定成本)。 c)将总成本存储在一个数组中,并找到这些数字中最小的数字,这些数字在用户界面的C45中返回给用户。

所描述的代码示例:

Sub Calculate()

Dim var As Variant
Dim rownumber As Integer
Dim Mx As Variant
Dim Nx As Variant
Dim Ox As Variant
Dim Px As Variant
Dim Qx As Variant
Dim Rx As Variant
Dim low As Variant
Dim cat As Variant

var = Range(WorksheetFunction.Match(Sheets("User Interface").Range("K19"), Sheets("C-type").Range("L1:L10000"), 0)).Value

rownumber = var.Row

Mx = var * Range("M" & rownumber).Value
Nx = var * Range("N" & rownumber).Value
Ox = var * Range("O" & rownumber).Value
Px = var * Range("P" & rownumber).Value
Qx = var * Range("Q" & rownumber).Value
Rx = var * Range("R" & rownumber).Value

cat = Array("Mx", "Nx", "Ox", "Px", "Qx", "Rx")

low = Min(cat).Value

Sheets("User Interface").Range("C45").Value = low

Sheets("User Interface").Range("c45").Activate
Application.Goto ActiveCell.EntireRow, True

End Sub

问题是VBA在low = Min(cat).Value给出错误(" sub或函数未定义"),即使从我的发现中我认为我使用了正确的语法。到目前为止,我找不到任何可行的解决方案。任何人都可以帮我解决问题吗?

非常感谢提前!

4 个答案:

答案 0 :(得分:2)

您是否尝试使用WorksheetFunction.Min

MSDN page for Excel built-in MIN function

答案 1 :(得分:2)

  1. 使用Excel函数Min时,您必须撰写WorksheetFunction.MinApplication.Min;
  2. 不要在函数.value上使用Min;
  3. 您的low值始终为0'因为您的数组不包含任何值...请改为cat = Array(Mx, Nx, Ox, Px, Qx, Rx)

答案 2 :(得分:1)

low = Application.WorksheetFunction.Min(cat)

这段代码应该有所帮助。

答案 3 :(得分:1)

代码有一些错误。

Sub Calculate()

Dim var As Variant
Dim rownumber As Integer
Dim Mx As Variant
Dim Nx As Variant
Dim Ox As Variant
Dim Px As Variant
Dim Qx As Variant
Dim Rx As Variant
Dim low As Variant
Dim cat As Variant

var = Range(WorksheetFunction.Match(Sheets("User Interface").Range("K19"), Sheets("C-type").Range("L1:L10000"), 0)).Value
'<~~ range error
rownumber = var.Row

Mx = var * Range("M" & rownumber).Value
Nx = var * Range("N" & rownumber).Value
Ox = var * Range("O" & rownumber).Value
Px = var * Range("P" & rownumber).Value
Qx = var * Range("Q" & rownumber).Value
Rx = var * Range("R" & rownumber).Value

'cat = Array("Mx", "Nx", "Ox", "Px", "Qx", "Rx")
cat = Array(Mx, Nx, Ox, Px, Qx, Rx) '<~~ quote is not need
low = WorksheetFunction.Min(cat) '<~~ use WorksheetFunction

Sheets("User Interface").Range("C45").Value = low

Sheets("User Interface").Range("c45").Activate
Application.Goto ActiveCell.EntireRow, True

End Sub