Блок поиска выдает «Ошибка выполнения 91» - PullRequest
0 голосов
/ 29 марта 2019

Добрый день, Когда я ищу в столбце определенную строку, я получаю ошибку запуска 91.

Я попытался изменить логику - скопировал результат на новый лист и затем сделалудаление - см. второй фрагмент кода.

Затем я обнаружил, что это происходит потому, что vba не может найти текст, поэтому я попросил человека, который запускает этот отчет на требуемом языке, изменить "??????? ATLAS ???? - ??? "к тому, как это написано на языке источника данных.Но это не помогло.

    Columns("A:A").Select
    Selection.Find("??????? ATLAS ????-???", LookIn:=xlValues).Select
    Range(ActiveCell.Address & ":" & Cells(Cells(Rows.Count, "A").End(xlUp).Row, ActiveCell.Column + 4).Address).Select
    Selection.Copy
    'Pasting the Ylan-Yde data to the new sheet
    Sheets("interim").Select
    Range("A1").Select
    ActiveSheet.Paste
    'Copying the Ylan-Yde data to a new sheet
    Cells.Select
    Selection.Copy
    Sheets("interim").Select
    Cells.Select
    ActiveSheet.Paste
    Columns("A:A").Select
    Selection.Find("??????? ATLAS ????-???", LookIn:=xlValues).Select
    Range("A1:A" & ActiveCell.Row - 1).EntireRow.Delete```


If I stick to the 2nd version, the code is supposed to find the a certain string in a column (it is present only once) and delete all rows before the row with the found string.

1 Ответ

1 голос
/ 29 марта 2019

Вам следует избегать использования .Select, потому что все может пойти не так, если пользователь взаимодействует с Excel. Вместо этого вам нужно объявить переменные для ваших книг и рабочих листов.

В этом подходе предполагается, что ваше слово появляется только один раз, а его длина всегда равна 22, поэтому другие ATLAS, отображаемые в столбце, имеют разную длину. Имея это в виду, это должно работать:

Option Explicit
Sub Test()

    Dim arr As Variant, LastRow As Long, ws As Worksheet, wsInterim As Worksheet, i As Long, StartRow As Long, NowDelete As Boolean


    With ThisWorkbook
        Set ws = .Sheets("NameWhereAtlasIs")
        Set wsInterim = .Sheets("Interim")
    End With
    With ws
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
        arr = .Range("A1:A" & LastRow).Value 'store the column A inside an array
    End With

    NowDelete = False

    For i = 1 To UBound(arr) 'find the ATLAS with the exact length match.
        If arr(i, 1) Like "*ATLAS*" And Len(arr(i, 1)) = 22 Then
            StartRow = i
            NowDelete = True
            arr(i, 1) = vbNullString 'if you intend to delete this row too, the one with the ATLAS
        End If
        If NowDelete Then arr(i, 1) = vbNullString 'from the moment you find your match all the rows will be emptied on column A
    Next i

    ws.Range("A" & StartRow & ":A" & LastRow).Copy wsInterim.Range("A1")

    ws.Range("A1:A" & LastRow).Value = arr 'this would paste the array back with the empty cells you cleared before

End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...