如何使用VBA代码获取列中的最大值

时间:2018-03-18 06:25:14

标签: excel vba excel-vba

我有兴趣获取列中的最大值并添加值1。结果数字将存储在另一列中。

我尝试使用行valuate("=MAX(AM3:AM300))")查找指定列中的最大值,但我一直收到不匹配错误,类型为13.

有人可以帮忙吗?

Private Sub Worksheet_Change(ByVal Target As Range)

Dim j As Long
Dim LastColumnValue As Integer
Dim NewColumnValue As Long

For j = 1 To 500
    If Cells(j, 39).Value = "" And Cells(j, 1) > 1 Then
        LastColumnValue = Evaluate("=MAX(AM3:AM300))")
        NewColumnValue = LastColumnValue + 1
        Cells(j, 39).Value = NewColumnValue
        Exit Sub
    End If
Next j

End Sub

1 个答案:

答案 0 :(得分:1)

使用Worksheetfunction.Max(),并在更改任何工作表单元格之前将Application.EnableEvents设置为False并在

之后立即将其恢复为True,从而避免无限循环
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim j As Long
    Dim LastColumnValue As Long
    Dim NewColumnValue As Long
    For j = 1 To 500
        If Cells(j, 39).Value = "" And Cells(j, 1) > 1 Then
            LastColumnValue = WorksheetFunction.Max(Range("AM3:AM300"))
            NewColumnValue = LastColumnValue + 1
            Application.EnableEvents = False
            Cells(j, 39).Value = NewColumnValue
            Application.EnableEvents = True
            Exit Sub
        End If
    Next j
End Sub