Excel VBA:在ActiveSheet中循环遍历单元格

时间:2012-08-11 22:32:42

标签: excel vba loops excel-vba cells

我正在尝试遍历指定数量的单元格(由宽度和高度定义),但我在这里遇到了问题。它一直停滞不前,然后对此感到不安:

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

有时Excel会毫无理由地给出“应用程序定义或对象定义错误”,because it's just the way Excel is,但这可能不是这种情况。

请勿使用SelectSelection与对象进行互动。直接命名对象。

Dim ws As Worksheet
Set ws = ActiveSheet

With ws
  ...
End With