Excel VBA - 函数最小范围的最大值

时间:2014-09-19 15:24:19

标签: excel vba excel-vba

我有两个非常相似的功能,在我将代码切换到 Option Explicit 以进行调试(成功!)之前,它们正在工作。从那时起,Max函数不再工作,我无法详细说明原因,并将其解析为xl vba完美noob。

  • 最大功能(不起作用):

    Function MaxAddress(The_Range) As Variant
    ' See http://support.microsoft.com/kb/139574
    
    Dim MaxNum As Variant
    Dim cell As Range
    
      ' Sets variable equal to maximum value in the input range.
      MaxNum = Application.Max(The_Range)
      ' Loop to check each cell in the input range to see if equals the
      ' MaxNum variable.
      For Each cell In The_Range
         If cell.Value = MaxNum Then
            ' If the cell value equals the MaxNum variable it
            ' returns the address to the function and exits the loop.
            MaxAddress = cell.Address
            Exit For
         End If
      Next cell
    
    End Function
    
  • 运行时错误

      

    我在运行时收到“错误91”,Xmax估值为:“Nothing”   错误91代表:未定义的对象或使用块变量

  • min 功能(正常)

    Function MinAddress(The_Range) As Variant
    ' See http://support.microsoft.com/kb/139574
    
    Dim MinNum As Variant
    Dim cell As Range
    
      ' Sets variable equal to maximum value in the input range.
      MinNum = Application.Min(The_Range)
      ' Loop to check each cell in the input range to see if equals the
      ' MaxNum variable.
      For Each cell In The_Range
         If cell.Value = MinNum Then
            ' If the cell value equals the MaxNum variable it
            ' returns the address to the function and exits the loop.
            MinAddress = cell.Address
            Exit For
         End If
      Next cell
    
      End Function
    

我如何调用这两个函数:

Set rng = ws_source.Range("3:3")
X_min = MinAddress(rng)
X_max = MaxAddress(rng) ' returns : X_max = Nothing

数据位于第3行,包含格式化的数字和文字。

2 个答案:

答案 0 :(得分:5)

不确定为什么min有效,但我相信它应该是

Application.WorksheetFunction.Max

&安培;

Application.WorksheetFunction.Min

答案 1 :(得分:5)

(不是答案,但对评论来说太大了)

我在普通模块中有以下内容,它可以正常工作:

Function MaxAddress(The_Range) As Variant
' See http://support.microsoft.com/kb/139574

Dim MaxNum As Variant
Dim cell As Range

  ' Sets variable equal to maximum value in the input range.
  MaxNum = Application.Max(The_Range)
  ' Loop to check each cell in the input range to see if equals the
  ' MaxNum variable.
  For Each cell In The_Range
     If cell.Value = MaxNum Then
        ' If the cell value equals the MaxNum variable it
        ' returns the address to the function and exits the loop.
        MaxAddress = cell.Address
        Exit For
     End If
  Next cell

End Function

Sub xxx()
Dim rng As Range
Dim X_max As String
Set rng = ThisWorkbook.Sheets(1).Range("3:3")
X_max = MaxAddress(rng)
MsgBox (X_max)
End Sub