返回Vba中Max Cell的地址

时间:2014-06-30 23:21:28

标签: excel-vba vba excel

对Excel vba不太了解。如何在最大值范围内(例如“MaxVal”)返回单元格的位置

  Sub FillSched()


    Dim LTrig As Long
    Dim i As Integer
    Dim MaxVal As Double
    Dim WorkRange As Range


    Worksheets("Inputs").Activate
    LTrig = Range("Trigger").Value

    Worksheets("Daily").Activate

    For i = 0 To 5
        If Range("AggInvStart").Offset(i, 0).Value > LTrig Then
        Set WorkRange = Range("M" & i + 5 & ":" & "O" & i + 5)
        MaxVal = WorksheetFunction.Max(WorkRange)
        End If    
    Next i


End Sub

提前谢谢。

2 个答案:

答案 0 :(得分:0)

在您的代码中,MaxValue只是一个计算值而不是范围。 您需要获取包含MaxValue

的WorkRange的位置
  Sub FillSched()


    Dim LTrig As Long
    Dim i As Integer
    Dim MaxVal As Double
    Dim WorkRange As Range
    Dim col Long
    Dim rw As Long

    Worksheets("Inputs").Activate
    LTrig = Range("Trigger").Value

    Worksheets("Daily").Activate

    For i = 0 To 5
        If Range("AggInvStart").Offset(i, 0).Value > LTrig Then
        Set WorkRange = Range("M" & i + 5 & ":" & "O" & i + 5)
        MaxVal = WorksheetFunction.Max(WorkRange)
        rw = WorkRange.Row
        col = WorkRange.Column
        End If
    Next i

MsgBox "MaxValue is in Row: " & rw & ", Column: " & col

End Sub

答案 1 :(得分:0)

Sub FillSched()

  Dim rngSearch As Range, WorkRange As Range
  Dim MaxVal as Double, lCol as Long, lRow as Long, sAddress as String

  With WorksheetFunction
    Set rngSearch = Range("AggInvStart").Resize(6, 1)      ' Define search range
    MaxVal = .Max(rngSearch.Value2)                        ' Get its max value
    If MaxVal <= Range("Trigger").Value2 Then _ ' Use this if you do not want to
      Exit Sub                           ' find MaxVal when is <= Range("Trigger")
    lCol = Range("AggInvStart")(1,1).Column                ' Get first column
    lRow = Range("AggInvStart")(1,1).Row - 1               ' Get one row before first
    Set WorkRange = Cells(lRow + .Match(MaxVal, rngSearch, 0), lCol) ' Get its location
    sAddress = WorkRange.Address                           ' Get Cell Address
    lRow = WorkRange.Row                                   ' Get Row No
    lCol = WorkRange.Column                                ' Get Column No
  End With

End Sub

我希望这有帮助!

PS:我认为在原始代码中,您希望LTrigDouble。此外,它必须初始化为一个非常小的数字(如果max值为负,则代码将会失败,因为Dim语句将LTrig初始化为零。)