最小功能在VBA中无法正常工作

时间:2018-07-16 17:19:33

标签: excel vba excel-vba excel-formula

我正在处理一个宏,它正在产生奇怪的结果。专门无法正常工作的部分是Min函数。

a1RowTemp1 = a1Row
For i = 0 To diff1
intercept = Application.WorksheetFunction.intercept(a(),c())
LinReg1 = (slope * Cells(a1RowTemp1, 1)) + intercept 
difference1 = Worksheets("GF9").Cells(a1RowTemp1, 2) - LinReg1              
e(i) = difference1
a1RowTemp1 = a1RowTemp1 + 1
Next i

a2RowTemp2 = a2Row

For i = 0 To diff2
intercept2 = Application.WorksheetFunction.intercept(b(), d())
LinReg2 = (slope2 * Cells(a2RowTemp2, 1)) +   intercept2
difference2 = Worksheets("GF9").Cells(a2RowTemp2, 2) - LinReg2
f(i) = difference2  
a2RowTemp2 = a2RowTemp2 + 1
Next i


Worksheets("Chart").Cells(currentRow, 12) = Application.Max(e())
Worksheets("Chart").Cells(currentRow, 13) = Application.Min(e())
Worksheets("Chart").Cells(currentRow, 25) = Application.Max(f())
Worksheets("Chart").Cells(currentRow, 26) = Application.Min(f())

在代码的底部,将difference1和difference2值存储在数组e()和f()中。当我使用max / min函数时,宏仅为max函数输出正确的值。我怀疑这与我错误地使用数组有关。

2 个答案:

答案 0 :(得分:1)

如果e是一维数组,您应该可以编写

Application.WorksheetFunction.Min(e)

示例:

Option Explicit
Public Sub TEST()
    Dim e()
    e = Array(3, 4, 2, 5)
    MsgBox Application.WorksheetFunction.Min(e)
End Sub

如果仍然得到错误的值,则需要使用 F8 逐步执行,并检查循环中分配给e的值是否是预期值。

答案 1 :(得分:1)

您已经省略了 e f 数组的声明和标注。这是您遇到问题的重要因素。

当您将 e f 声明为长数组或双精度数组时,它们被实例化为零值。

Dim v() As Double, i As Long
ReDim v(5)    '<~~ all zero values
For i = LBound(v) To UBound(v) - 1   '<~~fill all but the last one
    v(i) = i + 10
Next i
Debug.Print Application.Min(v)  'zero as v(5) is zero

如果要忽略尚未分配值的数组元素,请将数组声明为变量类型。

Dim v() As Variant, i As Long
ReDim v(5)    '<~~ all empty values
For i = LBound(v) To UBound(v) - 1   '<~~fill all but the last one
    v(i) = i + 10
Next i
Debug.Print Application.Min(v)  '10 as v(5) is empty and not considered in Min

未分配的变量数组元素被认为是空的,并且在Min计算中不使用。

或者,使用两种方法之一删除未使用的数组元素。

'...

'redimension before the loop to the known ubound
redim e(diff1)
For i = 0 To diff1
    intercept = Application.WorksheetFunction.intercept(a(),c())
    LinReg1 = (slope * Cells(a1RowTemp1, 1)) + intercept 
    difference1 = Worksheets("GF9").Cells(a1RowTemp1, 2) - LinReg1              
    e(i) = difference1
    a1RowTemp1 = a1RowTemp1 + 1
Next i

'...

'or redimension after the loop with Preserve
For i = 0 To diff2
    intercept2 = Application.WorksheetFunction.intercept(b(), d())
    LinReg2 = (slope2 * Cells(a2RowTemp2, 1)) +   intercept2
    difference2 = Worksheets("GF9").Cells(a2RowTemp2, 2) - LinReg2
    f(i) = difference2  
    a2RowTemp2 = a2RowTemp2 + 1
Next i
'i exits with a value 1 greater than diff2
redim preserve f(i-1)

'...