Excel VBA:循环在ActiveSheet中的单元格

我试图循环通过指定数量的单元格(由宽度和高度定义),但我遇到了问题在这里。 它一直在拖延我,然后感到不安:

If .Cells(11 + row, col).Value > maxVal Then 

它给了我一个“应用程序定义或对象定义的错误”

任何人都可以告诉我,我的错在哪里我的代码:

 Sub ApplyFilter() Dim maxVal As Double Dim minVal As Double maxVal = ActiveSheet.Range("D10").Value minVal = ActiveSheet.Range("D11").Value Dim width As Integer Dim height As Integer width = ActiveSheet.Range("L3").Value height = ActiveSheet.Range("L4").Value Dim row As Integer Dim col As Integer ActiveSheet.Select With Selection row = 1 Do col = 1 Do If .Cells(11 + row, col).Value > maxVal Then .Cells(11 + row, col).Value = 0 End If If .Cells(11 + row, col).Value < minVal Then .Cells(11 + row, col).Value = 0 End If col = col + 1 width = width - 1 Loop Until width = 1 row = row + 1 height = height - 1 Loop Until height = 1 End With End Sub 

有时Excel会无缘无故地给“应用程序定义的错误或对象定义的错误”, 因为这只是Excel的方式 ,但这可能不是这种情况。

不要使用SelectSelection与对象交互。 直接命名对象。

 Dim ws As Worksheet Set ws = ActiveSheet With ws ... End With 

这里的问题是我没有重新设置每个新行的宽度值。 我应该使用一个For循环,这将更直观地处理这个问题。