WorksheetFunction.Max / Min的运行时错误“1004”可变范围

我想获得一个范围内的最大和最小的for循环(每行)。

无论我在互联网上find的解决scheme是静态范围,还是给我同样的错误。 目前我使用以下在xMax行给出run-time error '1004'

 Dim i As Long Dim xMax As Double Dim ws1 As Worksheet Set ws1 = Worksheets("Sheet1") For i = 2 To 15 xMax = Application.WorksheetFunction.Max(ws1.range(Cells(i, 6), Cells(i, 15))) Next 

但是下面的静态范围工作:

 xMax = Application.WorksheetFunction.Max(ws1.range(Cells(2, 6), Cells(2, 15))) 

我试图把它变成2个单元格:

静态范围没有问题:

 xMax = Application.WorksheetFunction.Max(Cells(2, 6).Value, Cells(2, 7).Value) 

但dynamic范围popup相同的错误:

 For i = 2 To 15 xMax = Application.WorksheetFunction.Max(Cells(i, 6).Value, Cells(i, 7).Value) Next 

如何在循环内实现可变范围的最小/最大值?

在排除所有范围之后,请发表您的初始声明:

 xMax = Application.WorksheetFunction.Max(ws1.range(ws1.Cells(i, 6), ws1.Cells(i, 15))) 

当范围内的某些单元格出现错误(如#NA#DIV!0Max函数会产生错误。 要让您的计算忽略范围中的错误单元格,可以使用Aggregate函数。

 xMax = Application.Aggregate(14, 6, ws1.range(ws1.Cells(i, 6), ws1.Cells(i, 15)), 1) 
  • 第一个参数14指定Large 。 使用15Small
  • 第二个参数6指定“忽略计算中的错误”
  • 最后一个参数1指定“第一大结果”

还要注意,你尝试的其他版本,即

 xMax = Application.WorksheetFunction.Max(Cells(i, 6).Value, Cells(i, 7).Value) 

不指定连续范围,而是指定一组值(变体)。 只要其中一个variables不是数字,就会引发错误。 但是,你不需要这个版本。

您必须告诉Excel cell指向的位置,否则它将使用活动工作表

 xMax = Application.WorksheetFunction.Max(ws1.range(ws1.Cells(i, 6), ws1.Cells(i, 15))) 

要么

 With ws1 xMax = Application.WorksheetFunction.Max(.Range(.Cells(i, 6), .Cells(i, 15))) End With 

个人而言,我通常首先将范围分配给范围variables – 它有助于debugging:

 With ws1 dim r as range ''' set r = .Range(.Cells(i, 6), .Cells(i, 15)) ' Fails if not all cells are numeric set r = .Range(.Cells(i, 6), .Cells(i, 15)).SpecialCells(xlCellTypeConstants, xlNumbers) xMax = Application.WorksheetFunction.Max(r) End With 

我包括一个分裂function,更容易捕获信件。

 Dim i As Long Dim xMax As Double Dim ws1 As Worksheet Set ws1 = Worksheets("Sheet1") For i = 2 To 15 xMax = Application.WorksheetFunction.Max(ws1.range("F" & i & ":" & Split(Cells(, i).Address, "$")(1) & "15")) Next