我遇到了一段代码的问题,我希望将用户输入字符串与列中的一组字符串进行比较,然后运行一个循环,检查它们是否相同,如果没有提示用户输入另一个字符串。如果它们匹配,则继续执行脚本的下一部分。
我调用变量Checktag
和ServiceTag
:(两者都是变体)。
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
有更简单的方法吗?
似乎代码未初始化TagCheck - 将其设置为空 - 如果它未与ServiceTag值匹配。
我有另一个做类似工作的子工作,然后继续执行另一个单元/用户比较后写入特定单元格:
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")
在这种情况下,我希望在匹配满足时编辑单元格并填充绿色。但是,它总是跳过该部分代码并直接跳转到最终的消息框。我不知道为什么。
答案 0 :(得分:1)
我真的没有看到你编码循环的有效退出。用户应该只需单击取消即可退出。
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 method并将结果与Nothing
进行比较。引入像COUNTIF这样的工作表函数只会解析为零(例如 False )或零以外的任何内容(例如 True )。