循环遍历行

时间:2015-06-26 06:58:22

标签: excel excel-vba excel-2010 vba

如果是statemtns,我有这个,如果我希望它循环遍历列中的值(“A2:A50”)的每一行,我该怎么办?我尝试了很多,但还没弄明白该怎么做。 if statemtens的代码就是这些,

 If WorksheetFunction.CountA(ThisWorkbook.Sheets(1).Range("B2:D50")) = 0 Then
   Error 1001
ElseIf WorksheetFunction.CountA(ThisWorkbook.Sheets(1).Range("B2:B50")) > 0 And WorksheetFunction.CountA(ThisWorkbook.Sheets(1).Range("C2:C50")) > 0 Then
   Error 1001
End If

if语句有效并且它们按我的意愿行事,但它们不按我的意愿循环,我想要它做的是:

If WorksheetFunction.CountA(ThisWorkbook.Sheets(1).Range("A2:A50")) > 50 Then
Do the if statements above and loop. 

2 个答案:

答案 0 :(得分:0)

我已经重新编辑了,你能测试一下吗?

Sub loopXER()

'Define variables
Dim rng As Range
Dim cell As Range
Dim cell1 As Range
Dim cell2 As Range
Dim cell3 As Range


'Set the range to use
Set rng = Range("A2:A50")
Set rng2 = Range("B2:D50")
Set rng3 = Range("B2:B50")
Set rng4 = Range("C2:C50")


'Iterate through each cell in range
For Each cell In rng
'If cell is empty or it's value is over 50, go to if's defined by OP, else go to next cell
    If IsEmpty(cell) Or cell.Value > 50 Then
         For Each cell1 In rng2
            If IsEmpty(cell1) Or cell1.Value = 0 Then
                MsgBox "Error 1001"
            End If
         Next cell1

         For Each cell2 In rng3
            If cell2.Value > 0 Then
                MsgBox "Error 1001"
            End If
         Next cell2

         For Each cell3 In rng4
            If cell3.Value > 0 Then
                MsgBox "Error 1001"
            End If
         Next cell3

    End If

Next cell

End Sub

答案 1 :(得分:0)

试试这段代码: -

  Dim rng As Range
  Dim data As Range
  Dim myCell As Range

  Set rng = ThisWorkbook.Sheets(1).Range("A2:A50")  

  'If *any* cell has a value in this range (adjust as required)
  If WorksheetFunction.CountA(rng) > 0 Then

    'Capture cells with values and formulae
    Set data = Union(rng.SpecialCells(xlCellTypeConstants, 23), _
                     rng.SpecialCells(xlCellTypeFormulas, 23))

    data.Select

    For Each myCell In data

      Debug.Print myCell.Address

    Next

  End If