每个VBA嵌套For Each

我写了一个对于每个循环,我想通过范围和testing的第一个条件,并将值添加到combobox。 只有如果它不能find这个条件,那么我希望它执行每个循环的第二个,并添加所有符合条件的值。

我写了下面的代码,它说

否则没有如果

即使有一个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条线

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

你也将需要使用End If某个地方 – 类似这样的结构是正确的,但至于function,我不知道你在做什么,所以我猜。

 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 

对于任何感兴趣的人,我通过添加一个do while循环来testing第一个条件,如果find或者为每个循环运行并添加了所有匹配的值,则填充该combobox。

  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