Обработка ошибок VBA, если строка не найдена в столбце - PullRequest
0 голосов
/ 11 апреля 2019

У меня есть код для поиска «Модель» в столбце в Excel, но иногда работы «Модель» не будет. Есть ли способ с ошибкой справиться с этим? По сути, я хочу сказать: «если модели нет, тогда делайте ххх»

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

UPDATE:

Я использовал:

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 не хватило памяти

Ответы [ 3 ]

2 голосов
/ 11 апреля 2019

Ваш код уже поддерживает это ... вам просто нужно другое выражение для вашего if.

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

Edit1:

Вопрос ... что не так с использованием .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

Edit2:

Показано перемещение msgbox за пределы цикла, согласно комментарию lizard6.

0 голосов
/ 11 апреля 2019

Вы можете использовать свою логическую переменную для выполнения теста:

If bNotModelType = False Then
   Msgbox
End If

Или используйте Model_Type_Row <> 0 (затем инициализируйте его до 0 перед циклом).

0 голосов
/ 11 апреля 2019

Вы можете сделать это:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...