Конец обёртывания .indNext без цикла? - PullRequest
1 голос
/ 09 апреля 2019

Я новичок в VBA и создаю электронную таблицу CRM для небольшой компании. У меня есть лист с именами компаний / клиентов, и я пытаюсь извлечь их контактную информацию из другого листа и показать ее во всплывающей форме пользователя.

Моя пользовательская форма перечисляет индивидуальную контактную информацию с текстовыми полями, поэтому я использую функции .Find / FindNext для их заполнения. Но FindNext продолжает переходить к началу, заставляя пользовательскую форму снова показывать те же имена.

Как мне остановить .FindNext от переноса без использования цикла?

Я пытался поместить это в цикл Do-Loop, но это, кажется, помещает его в бесконечный цикл или что-то в этом роде и останавливает Excel. Я также попробовал формулу LastRow без удачи.

Sub UserForm_Activate()

Dim fSearch As Range 'the column we are searching in
Dim fFind As Range 'the value we are searching for
Dim LastRow As Long

Set fSearch = Sheets("Contact List").Range("Company_Find")

'First Find
Set fFind = fSearch.Find(What:=Selection.Value)
Debug.Print
    Txt_Contact1 = fFind.Offset(0, 5)
    Txt_Title1 = fFind.Offset(0, -1)
    Txt_Email1 = fFind.Offset(0, 1)
    Txt_Office1 = fFind.Offset(0, 2)
    Txt_Mobile1 = fFind.Offset(0, 3)

'Second Find
Set fFind = fSearch.FindNext(fFind)
Debug.Print
    Txt_Contact2 = fFind.Offset(0, 5)
    Txt_Title2 = fFind.Offset(0, -1)
    Txt_Email2 = fFind.Offset(0, 1)
    Txt_Office2 = fFind.Offset(0, 2)
    Txt_Mobile2 = fFind.Offset(0, 3)

'Third Find
Set fFind = fSearch.FindNext(fFind)
Debug.Print
    Txt_Contact3 = fFind.Offset(0, 5)
    Txt_Title3 = fFind.Offset(0, -1)
    Txt_Email3 = fFind.Offset(0, 1)
    Txt_Office3 = fFind.Offset(0, 2)
    Txt_Mobile3 = fFind.Offset(0, 3)

'Fourth Find

'Fifth Find

End Sub

1 Ответ

0 голосов
/ 09 апреля 2019
    Set fFind = fSearch.Find(What:=Selection.Value)
    If Not fFind Is Nothing Then
        'Save the address of the first found range to compare with later
        Fadd = fFind.Address
    End If

    Do While Not fFind Is Nothing
         'Do stuff

         Set fFind = fSearch.FindNext(fFind)
         If Not fFind is Nothing Then
             'If the next found address is the same as the first, stop searching, exit the loop
             If fFind.Address = Fadd Then Exit Do
         End If
    Loop

Это мой метод.Надеюсь, поможет.Я считаю, что вы не правильно вышли из своего Do...Loop, отсюда и бесконечные циклы, которые убили Excel.Этот цикл завершится, если вы не измените значение первого найденного диапазона.

Вам гораздо лучше использовать цикл, чем писать метод Find для каждого поиска.Это приводит к жестко закодированному поиску «цикла» без гибкости в итерациях.

EDIT

Приведенный ниже код будет зацикливаться, чтобы заполнить все текстовые поля в UF,и выйдите из цикла, как только все заполнены / новые значения не найдены

Dim ctrl as Control
Dim b as Integer

Set fFind = fSearch.Find(What:=Selection.Value)
If Not fFind Is Nothing Then
    b = 1
    'Save the address of the first found range to compare with later
    Fadd = fFind.Address
End If

Do While Not fFind Is Nothing
     For Each ctrl In Me.Controls
         If ctrl.Name Like "Txt_Contact" & b And ctrl.Value = "" Then ctrl.Value = fFind.Offset(0, 5)
         If ctrl.Name Like "Txt_Title" & b And ctrl.Value = "" Then ctrl.Value = fFind.Offset(0, -1)
         If ctrl.Name Like "Txt_Email" & b And ctrl.Value = "" Then ctrl.Value = fFind.Offset(0, 1)
         If ctrl.Name Like "Txt_Office" & b And ctrl.Value = "" Then ctrl.Value = fFind.Offset(0, 2)
         If ctrl.Name Like "Txt_Mobile" & b And ctrl.Value = "" Then ctrl.Value = fFind.Offset(0, 3)
     Next ctrl

     Set fFind = fSearch.FindNext(fFind)
     If Not fFind is Nothing Then
         'If the next found address is the same as the first, stop searching, exit the loop
         If fFind.Address = Fadd Then Exit Do
     End If
     b = b + 1
Loop
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...