excel VBA Forloop/ Do until

pjngdqdw  于 2022-12-05  发布在  其他
关注(0)|答案(1)|浏览(179)

只是需要一些帮助来理解forloop的实现。
以下是我失败的尝试:

Sub test()

   Do Until IsEmpty(Worksheets("do not open!").Range("F1"))
         If UI.ComboBoxSource <> ActiveCell Then
         MsgBox "This procedure already exhists. Please click on update summary. "
         Else
         End If
         Worksheets("do not open!").Range("F1").Offset(1, 0).Select
         Loop

End Sub

以下是@FaneDuru的正确尝试:

Sub test()
  Dim ws As Worksheet, rngF As Range
  
  Set ws = Worksheets("do not open!")
  Set rngF = ws.Range("F1")
   
   Do Until rngF.Value = ""
         If UI.ComboBoxSource <> rngF.Value Then
            MsgBox "This procedure already exhists. Please click on update summary. "
         Else 
            'do something...
         End If
         Set rngF = rngF.Offset(1)
  Loop

End Sub

我尝试循环遍历一个单元格区域(在本例中,按F1向下,直到空白单元格),并应用if语句比较值是否匹配。如果值匹配,则我希望循环继续,直到结束......如果不匹配,则我希望出现MsgBox并停止循环。
这就是我试图做的:

Sub check_procedures()
  Dim ws As Worksheet, rngF As Range
  
  Set ws = Worksheets("do not open!")
  Set rngF = ws.Range("F1")
   
   Do Until rngF.Value = ""
         If UI.ComboBoxSource = rngF.Value Then
         MsgBox "This procedure already exhists. Please click on Update Summary. "
         Exit Sub
         
         
         Else
         End If
            
            
         Set rngF = rngF.Offset(1)
         
         
    
    Loop
    
End Sub

谢谢你的帮助。

pkwftd7m

pkwftd7m1#

请尝试下一种方式,选择、激活只会消耗Excel资源,不会带来任何好处:

Sub test()
  Dim ws As Worksheet, rngF As Range
  
  Set ws = Worksheets("do not open!")
  Set rngF = ws.Range("F1")
   
   Do Until rngF.Value = ""
         If UI.ComboBoxSource <> rngF.Value Then
            MsgBox "This procedure already exhists. Please click on update summary. "
         Else 
            'do something...
         End If
         Set rngF = rngF.Offset(1)
  Loop

End Sub

但是代码看起来很奇怪。它会发送很多信息。当UI.ComboBoxSource = rngF.Value时该怎么办?F:F中的所有单元格值是否都等于UI.ComboBoxSource,并且偶然只有一个,或者两个不相等?如果只有一个,你应该把Exit Do放在后面,以使代码更快,而不是迭代到第一个空单元格...

相关问题