在Do,While循环中嵌套IF语句

我一直有一个代码段,在那里我想比较一个用户inputstring与列中的一组string,然后运行一个循环,检查是否相同,如果不是,它会提示用户换另一个string。 如果它们匹配,则继续执行脚本的下一部分。

我称之为variablesChecktagServiceTag :(都是变体)。

 ServiceTag = InputBox("Please enter the laptop service tag ID") Set TagCheck = ActiveWorkbook.Sheets("Sheet5").Range("B2:B1000").Find(ServiceTag, lookat:=xlWhole) Do If TagCheck Is Nothing Then ServiceTag = InputBox(" User entered Service ID is not present in database, please re-enter the laptop service tag ID") Set TagCheck = ActiveWorkbook.Sheets("Sheet5").Range("B2:B1000").Find(ServiceTag, lookat:=xlWhole) Else MsgBox (" Service Tag ID recognised ") s1.Cells(2, 3).Value = ServiceTag End If Loop While TagCheck Is Nothing 

有没有更简单的方法来做到这一点?

如果代码没有与ServiceTag值匹配,那么代码似乎会将TagCheck设置为不初始化。

我有另一个做类似工作的子,但是在执行另一个单元/用户比较之后,继续写一个特定的单元:

  Set rngX = ActiveWorkbook.Sheets("Sheet5").Range("B2:B1000").Find(ServiceTag, lookat:=xlWhole) Set TagCheckA = ActiveWorkbook.Sheets("Sheet1").Range("C2:C10000").Find(ServiceTag, lookat:=xlWhole) If Not TagCheckA Is Nothing Then RowZ = Range(TagCheckA.Address).Row DateReadA = Worksheets("Sheet1").Cells(RowZ, 7).Value End If If TagCheck = TagCheckA And DateRead = DateReadA Then If Not rngX Is Nothing Then RowX = Range(rngX.Address).Row s5.Cells(RowX, 3).Interior.Color = RGB(0, 255, 0) s5.Cells(RowX, 3).Value = " Checked IN " s5.Cells(RowX, 4).Value = myDate End If s1.Cells(RowZ, 8).Value = myDate MsgBox ("The Laptop has been Sucessfully Signed IN") 

在这种情况下,我想要一个单元格进行编辑和绿色满足匹配时。 但是,它总是跳过这段代码,直接跳到最后的消息框。 我不知道为什么。

我真的没有看到从你的编码循环有效的退出。 用户应该能够通过简单地点击取消退出。

 Sub st() Dim ServiceTag As String, s1 As Worksheet Set s1 = Worksheets("Service Tags") ServiceTag = InputBox("Please enter the laptop service tag ID") Do While CBool(Len(ServiceTag)) If CBool(Application.CountIf(ActiveWorkbook.Sheets("Sheet5").Range("B2:B1000"), ServiceTag)) Then MsgBox (" Service Tag ID recognised ") 'need to have some way to increment the receiving cell - see commented line s1.Cells(2, 3).Value = ServiceTag 's1.Cells(Rows.Count, 3).End(xlUp).offxet(1, 0) = ServiceTag End If ServiceTag = InputBox("Please enter the laptop service tag ID") Loop End Sub 

我从来没有使用Range.Find方法的风扇,并将结果与Nothing进行比较。 引入像COUNTIF这样的工作表函数将简单地parsing为零(例如False )或除零之外的任何东西(例如True )。