每个VBA为嵌套For Each

时间:2017-11-13 15:48:56

标签: excel vba excel-vba

我已经编写了一个For循环,我希望遍历该范围并测试第一个条件并将值添加到组合框中。 ONLY如果找不到那个条件,那么我希望它为每个循环执行第二个并添加符合条件的所有值。

我写了下面的代码,然后说

  

否则没有If

即使有IF

 Dim Keys As Range, cell As Range


 Set Keys = ThisWorkbook.Worksheets("keyHistory").Range("A2:A20000")

   For Each cell In Keys
     If cell.Value = WindowsUserName And cell.Offset(0, 4) = 1 Then Me.ComboBox1.AddItem cell.Value

   Else
      For Each cell In Keys
      If cell.Offset(0, 4).Value = 1 And cell.Offset(0, 3) = "" Or cell.Value = "Spare" And cell.Offset(0, 4) = 1 Then Me.ComboBox1.AddItem cell.Value

   Next cell

 Next cell
 Set Keys = Nothing

2 个答案:

答案 0 :(得分:1)

将此行拆分为2行,如下所示

 If cell.Value = WindowsUserName And cell.Offset(0, 4) = 1 Then
     Me.ComboBox1.AddItem cell.Value

你还需要在某个地方使用End If - 这样的结构会使结构正确,但就功能而言,我不确定你要做的是什么,所以我猜到了。

Dim Keys As Range, cell As Range, cell2 as Range


 Set Keys = ThisWorkbook.Worksheets("keyHistory").Range("A2:A20000")

   For Each cell In Keys
     If cell.Value = WindowsUserName And cell.Offset(0, 4) = 1 Then 
         Me.ComboBox1.AddItem cell.Value
     Else
        For Each cell2 In Keys
            If cell2.Offset(0, 4).Value = 1 And cell2.Offset(0, 3) = "" Or cell2.Value = "Spare" And cell2.Offset(0, 4) = 1 Then Me.ComboBox1.AddItem cell.Value
        Next
     End IF
 Next
 Set Keys = Nothing

答案 1 :(得分:0)

对于任何感兴趣的人,我通过在测试第一个条件的开头添加do while循环来修复此问题,如果找到则组合框退出sub,或者为每个循环运行并添加所有匹配的值

    Dim Keys As Range, cell As Range, userName As Variant


userName = WindowsUserName

ThisWorkbook.Worksheets("keyHistory").Range("A2").Select

Do While ActiveCell.Value <> ""
        If ActiveCell.Value = userName And ActiveCell.Offset(0, 2) <> "" And ActiveCell.Offset(0, 4) = 1 Then
        Me.ComboBox1.AddItem ActiveCell.Value
        Set userName = Nothing
        Exit Sub

        Else
        ActiveCell.Offset(1, 0).Select
        End If
Loop


Set Keys = ThisWorkbook.Worksheets("keyHistory").Range("A2:A20000")

For Each cell In Keys
If cell.Offset(0, 4).Value = 1 And cell.Offset(0, 3) = "" Or cell.Value = "Spare" And cell.Offset(0, 4) = 1 Then Me.ComboBox1.AddItem cell.Value
Next cell


 Set Keys = Nothing

 Set userName = Nothing

 Set cell = Nothing