2014-09-19 73 views
4

我有2个非常类似的功能,在我将代码切换到选项明确调试puposes(成功!)之前工作。从那时起,Max功能不再工作了,我不能详细说明为什么,并解决它作为一个xl vba完美的noob。Excel VBA - 功能最小范围

  • max函数(不工作):

    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代表:未定义的对象或含块变量

  • 分钟功能(作品)

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

+0

我不能复制这个错误 – Horaciux 2014-09-19 15:31:15

+0

当然,它看起来是一个棘手的。 – hornetbzz 2014-09-19 15:32:50

+1

如果您将X_max设置为Nothing,那么X_max是一个不合适的对象变量。使用'Dim X_max as String' – Rory 2014-09-19 15:34:21

回答

4

(不是一个答案,但过大的注释)

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

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 
+0

Thx!你明白了:Dim X_max As String – hornetbzz 2014-09-19 15:39:08

4

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

Application.WorksheetFunction.Max 

&

Application.WorksheetFunction.Min