Excel VBA – 范围的function最小值

我有两个非常相似的function,在我将代码切换到Option Explicit以进行debuggingpuposes(成功!)之前工作。 从那时起, Maxfunction已经不起作用了,我也无法详细说明为什么并解决它作为一个完美的新手。

  • 最大function (不起作用):

     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代表:undefined object或With block variable

  • 最小function(作品)

     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行,包含格式化的数字和文本。

(不是一个答案,但太大的评论)

我有一个正常模块中的以下,它工作正常:

 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 

不知道为什么分钟工作,但我相信它应该是

 Application.WorksheetFunction.Max 

 Application.WorksheetFunction.Min