VBA无限循环 – 当用户没有任何价值时

我是一个VBA的新手,我正在写一个VBA代码,将接受用户input的开始和结束值的序列号,并将检查另一个表中的序列号是否在指定的范围之间。 如果是这样,那么我的代码将select完整的logging,并将其粘贴到另一个表。

现在,具有挑战性的部分是序列号值不一致,可能是没有固定长度的字母数字string。 所以,我用StrComp函数来检查值是否在用户指定的范围内。 问题是,如果用户键入的值为开始值和结束值不存在的序列号表中,然后进行无限循环。

例如,如果有一个序列号,例如1120,并且用户input1110(不存在)的起始值和1200的最终值,则代码进入无限循环。 从技术上讲,代码应该挑选序列号1120并返回,因为它确实位于1110和1200的范围内,尽pipe表格中不存在值1110。

这是我的代码:

'Assigining values enterted by user to variables start = Me.txtStart.Value finish = Me.txtEnd.Value 'Checking Upper bound Vs Lower bound If (Len(start) <> 0 And (Len(finish) <> 0)) Then If (StrComp(start, finish) > 0) Then MsgBox ("Lower Bound cannot be higher than the Upper Bound") Exit Sub Else If Len(tempWorkPriority) = 0 Then MsgBox ("Enter a value for Work Priority") Exit Sub Else If Len(tempDescription) = 0 Then MsgBox ("Enter a value for Description") Exit Sub Else Goto Here End If End If End If Else result = MsgBox("Please enter values for Upper and Lower bounds") Exit Sub End If End Sub Here: Sheets("Imported e-Facilities Data").Activate 'Number of rows in Raw Data sheet RowCount = Cells(Cells.Rows.Count, "A").End(xlUp).Row 'Loop to iterate and pick data that falls within the specified range For i = 2 To RowCount tempSerial = Range("A" & i).Value tempAsset = Range("V" & i).Value tempAssignedResource = Range("R" & i).Value tempManufacturer = Range("F" & i).Value 'Condition to check if a Serial Number falls within the range If (StrComp(start, tempSerial) <= 0 And StrComp(tempSerial, finish) <= 0) Then 'Selecting Export Sheet Sheets("Data Ready for Import").Select 'Counting Rows in the Export sheet RowCountExport = Cells(Cells.Rows.Count, "A").End(xlUp).Row Range("A" & RowCountExport + 1).Value = tempSerial End If Next End Sub 

请帮忙!!!

您正在使用不合格的Range调用,因此您依赖正确设置活动工作表。 当您发现一个在该范围内的序列号时,您可以在另一个具有更改活动工作表的效果的纸张上调用Select 。 下一次您的循环tempSerialtempAsset等将从“Data Ready For Import”表单中读取,该表单现在处于活动状态,而不是之前使用的“Imported e-Facilities Data”表单。

您应该限定您的Range参考,而不是依赖活动工作表, SelectActivate

 Set wsInput = Worksheets("Imported e-Facilities Data") tempSerial = wsInput.Range("A" & i).Value 

或者使用With ... End With来重复引用同一个对象:

 Set wsInput = Worksheets("Imported e-Facilities Data") With wsInput tempSerial = .Range("A" & i).Value tempAsset = .Range("V" & i).Value tempAssignedResource = .Range("R" & i).Value tempManufacturer = .Range("F" & i).Value End With