2016-06-15 2 views
0

У меня есть код, над которым я работаю, где мне нужно определить, имеет ли ячейка определенное слово в нем, и если это так, он вставляет определенную строку в соседнюю ячейку. Однако у меня возникают проблемы с его обнаружением! Вот что я до сих пор.Как определить, присутствует ли слово в ячейке внутри строки?

Sub searchandpaste() 
    Dim stopvar As Variant 
    Dim i As Variant 
    Dim j As Variant 
    Dim k As Variant 
    Dim TestVal1 As Variant 
    Dim TestVal2 As Variant 

    i = 0 
    j = 0 

    Do While stopvar = 0 
     i = i + 1 
     MsgBox ("Row " & i) 
     MsgBox ("j equals " & j) 
     'If the first cell is empty, that means we've hit the end of the worksheet, and it stops the do-while loop 
     TestVal1 = Cells(i, 1) 
     If TestVal1 = 0 Then 
      stopvar = 1 
     Else 
      TestVal2 = Cells(i, 6) 
      If IsEmpty(TestVal2) = True Then 
       MsgBox ("Detected Empty Cell in Column 6") 
       j = 1 
      ElseIf TestVal2 = "XXXX" Then 
       'This means we have a place we need to insert a value 
       MsgBox ("Detected XXXX in Column 6") 
       'We know at this point that in Cells(6,i) we have a value we need to insert. Thus, we need to search Cells(7,i) for key text 
       If IsNumeric(Cells(7, j).Find("CYLINDER")) Or IsNumeric(Cells(7, j).Find("CYLINDERS")) Or IsNumeric(Cells(7, j).Find("CYL")) = True Then 
        MsgBox ("Detected the string CYLINDER") 
        j = j + 1 
        MsgBox ("j equals " & j) 
       Else 
        MsgBox ("Did not detect the string CYLINDER") 
       End If 

      End If 
     End If 
    Loop 
End Sub 

Я вырежу важную часть здесь.

'We know at this point that in Cells(6,i) we have a value we need to insert. Thus, we need to search Cells(7,i) for key text 
If IsNumeric(Cells(7, j).Find("CYLINDER")) Or IsNumeric(Cells(7, j).Find("CYLINDERS")) Or IsNumeric(Cells(7, j).Find("CYL")) = True Then 
    MsgBox ("Detected the string CYLINDER") 
    j = j + 1 
    MsgBox ("j equals " & j) 
Else 
    MsgBox ("Did not detect the string CYLINDER") 
End If 

Мое намерение состоит в том, что это будет искать строку в ячейке (я, 7) для различных вариаций слова цилиндра, и если он находит, то он будет возвращать значение TRUE или FALSE (ложь будет NAN , который пойман IsNumeric и обратился к FALSE), и сообщите мне, что он его обнаружил. Однако, похоже, это не работает.

Может ли кто-нибудь определить мою ошибку?

Есть ли лучший способ поиска строки? Например, могу ли я просто найти «CYL» и сказать, что он обнаружил какие-либо из этих вариантов?

+1

Вы должны использовать 'метод InStr' сделать сравнение, как это:' Если InStr (1, Cells (7, J), "ЦИЛИНДР")> 0 или InStr (1, Ячейки (7, j), «CYLINDERS»)> 0 или InStr (1, ячейки (7, j), «CYL»)> 0 Then' – Ralph

+1

Также, что происходит, когда «Cyl», «cyl»? Почему бы вам не перевернуть слово в верхнем регистре кода, чтобы покрыть эти сценарии -UCase() -? Или используйте Option Compare Text в начале модуля, я не понимаю, зачем делать 3 сравнения, если у ячейки есть «CYL», конечно, на ней были бы CYLINDER и CYLINDERS. – Sgdva

+0

Отлично, спасибо Ральф. И ты правильный Срдва. @Ralph, если вы представите это как комментарий, я буду отмечать его как ответ. – TheTreeMan

ответ

1

Вы должны использовать функцию InStr, чтобы сделать сравнение, как это:

If InStr(1, Cells(7, j), "CYLINDER") > 0 Or _ 
    InStr(1, Cells(7, j), "CYLINDERS") > 0 Or _ 
    InStr(1, Cells(7, j), "CYL") > 0 Then 
     MsgBox ("Detected the string CYLINDER") 
     j = j + 1 
     MsgBox ("j equals " & j) 
Else 
    MsgBox ("Did not detect the string CYLINDER") 
End If 

Для получения дополнительной информации об этой функции посетите MSDN на https://msdn.microsoft.com/en-us/library/office/gg264811%28v=office.15%29.aspx

Чтобы избежать различных случаев (как это было предложено @Sgdva) вас есть несколько вариантов:

If InStr(1, Cells(7, j), "CYLINDER", vbTextCompare) > 0 Or _ 
    InStr(1, Cells(7, j), "CYLINDERS", vbTextCompare) > 0 Or _ 
    InStr(1, Cells(7, j), "CYL", vbTextCompare) > 0 Then 
     MsgBox ("Detected the string CYLINDER") 
     j = j + 1 
     MsgBox ("j equals " & j) 
Else 
    MsgBox ("Did not detect the string CYLINDER") 
End If 

ИЛИ

If InStr(1, UCase(Cells(7, j)), "CYLINDER") > 0 Or _ 
    InStr(1, UCase(Cells(7, j)), "CYLINDERS") > 0 Or _ 
    InStr(1, UCase(Cells(7, j)), "CYL") > 0 Then 
     MsgBox ("Detected the string CYLINDER") 
     j = j + 1 
     MsgBox ("j equals " & j) 
Else 
    MsgBox ("Did not detect the string CYLINDER") 
End If 

ИЛИ

Используйте Option Compare Text в верхней части модуля и как указано здесь: https://msdn.microsoft.com/en-us/library/office/gg278697.aspx

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

Option Explicit 

(для хорошо практика кодирования).

+0

Благодарим за помощь! Я ценю это :) – TheTreeMan

1

Не знаете, что вы пытаетесь выполнить с помощью переменной j, поскольку она, похоже, не имеет никакого отношения. Кроме того, я, кажется, обнаружил ошибку в вашем коде и ответ, полученный Ральфом. Cells(7, j) должно быть Cells(i, 7). Полный код будет:

Sub searchandpaste() 
    Dim stopvar As Variant 
    Dim i As Variant 
    Dim j As Variant 
    Dim k As Variant 
    Dim TestVal1 As Variant 
    Dim TestVal2 As Variant 

    i = 0 
    j = 0 

    Do While stopvar = 0 
     i = i + 1 
     MsgBox ("Row " & i) 
     MsgBox ("j equals " & j) 
     'If the first cell is empty, that means we've hit the end of the worksheet, and it stops the do-while loop 
     TestVal1 = Cells(i, 1) 
     If TestVal1 = 0 Then 
      stopvar = 1 
     Else 
      TestVal2 = Cells(i, 6) 
      If IsEmpty(TestVal2) = True Then 
       MsgBox ("Detected Empty Cell in Column 6") 
       j = 1 
      ElseIf TestVal2 = "XXXX" Then 
       'This means we have a place we need to insert a value 
       MsgBox ("Detected XXXX in Column 6") 
       'We know at this point that in Cells(6,i) we have a value we need to insert. Thus, we need to search Cells(7,i) for key text 
       If InStr(LCase(Cells(i, 7)), "cyl") > 0 Then 
        MsgBox ("Detected the string CYLINDER") 
        j = j + 1 
        MsgBox ("j equals " & j) 
       Else 
        MsgBox ("Did not detect the string CYLINDER") 
       End If 

      End If 
     End If 
    Loop 
End Sub 
+0

j как я отслеживаю что-то еще. Это не очень актуально для текущего кода. Спасибо, что собрали вместе! – TheTreeMan

Смежные вопросы