我有代码在excel的列中寻找“模型”,但有时工作“模型”将不存在。有没有办法解决这个问题?基本上我希望它说“如果模型不存在,那么做xxx”
bNotModelType = True
checking_type = "ModelType"
Do While bNotModelType
If Cells(j, 1).Value = checking_type Then
Model_Type_Row = j
bNotModelType = False
End If
j = j + 1
If Model_Type_Row = Nothing Then
MsgBox ("NADA")
Loop
我没有正确使用Nothing
更新:
我最终使用:
lastPossibleRow = 1000000
lastRoww = ActiveSheet.Range("A" & lastPossibleRow).End(xlUp).Row
j = 1
bNotModelType = True
checking_type = "ModelType"
Do While bNotModelType And j < lastRoww
If Cells(j, 1).Value = checking_type Then
Model_Type_Row = j
bNotModelType = False
Else
j = j + 1
End If
Loop
If Model_Type_Row = 0 Then
'do something
Else
'code for if modeltype was found in the excel document
End If
我添加了查找最后一行的内容,因为excel内存不足
答案 0 :(得分:2)
您的代码已支持该功能……您只需要在if中添加else语句即可。
bNotModelType = True
checking_type = "ModelType"
Do While bNotModelType
'changing from value equals to instr so you can find partial matches
If Instr(Cells(j, 1).Value,checking_type) Then 'InStr() this will do a boolean check if it's in the string
Model_Type_Row = j
bNotModelType = False
Else 'added here
'add your code when not met.
End If
j = j + 1
'If Model_Type_Row = 0 Then MsgBox ("NADA") 'if you want within loop, do this
'Model_Type_Row = 0
Loop
If Model_Type_Row = 0 Then MsgBox ("NADA") 'moved msgbox out of loop
编辑1:
问题...在该列上使用.Find()
有什么问题?
if iserror(Columns(1).Find(What:=checking_type, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False))
'when there is an error, do this
MsgBox ("NADA")
else
'do something when the row is found
Model_Type_Row = Columns(1).Find(What:=checking_type, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Row
End if
编辑2:
根据lizard6的评论,显示了将msgbox移动到循环之外。
答案 1 :(得分:0)
您可以这样做:
checking_type = 0
On Error Resume Next
checking_type = ThisWorkbook.Sheets("Sheet where you are looking").Cells.Find("ModelType").Column
On Error GoTo 0
If checking_type <> 0 Then
'code if column is found
Else
'code if column not found
End If
答案 2 :(得分:0)
您可以使用布尔变量来完成测试:
If bNotModelType = False Then
Msgbox
End If
或使用Model_Type_Row <> 0
(然后在循环之前将其初始化为0)。