Excel VBA Find.Row, возвращающее значение плюс 1268 - PullRequest
1 голос
/ 16 марта 2020

Я настроил пользовательскую форму, которая ищет в рабочем листе данные из 1-го поля и успешно находит их. Два других поля заполняются данными из строки, найденной при поиске. Я хочу иметь возможность записывать данные в одну строку из 4-го поля. Тем не менее, тот же рабочий код поиска возвращает номер строки, который на 1268 строк отключен в другой подпрограмме.

Редактировать: вставлен весь код пользовательской формы с новым поиском, как описано в ответе BigBen. Вот изображение пользовательской формы , чтобы увидеть сторону пользователя. Я ценю помощь и слышу ваши стоны из-за отсутствия у меня обучения VBA.

Private Sub UserForm_Initialize()

    'Reset buttons to white
    button_search_inactive.Visible = True
    button_save_inactive.Visible = True

    'Make code operate faster
    Application.Calculation = xlManual

    'Declare all default variables
    Dim allTransactionData As Worksheet
    Dim locationNew As String
    Dim bottle As String
    Dim locationFormer As String
    Dim bottleFormer As String

    'Assign default values to variables
    Set allTransactionData = Worksheets("Transactions")
    locationNew = ""
    bottle = ""
    bottleFormer = "^ Search Bottle"
    locationFormer = ""

    'Set default form view
    With Me
        .Height = 205
        .Width = 181
        .Top = 0
        .Left = 0
        .StartUpPosition = 2
        .field_locationFormer.Value = locationFormer
        .field_bottle = bottleFormer
        .field_search = bottle
        .field_location = locationNew

    End With

End Sub

Private Sub button_search_active_Click()

    With Me
        'Validates search entry
        If .field_search.Value = "" Then
            MsgBox ("Please enter a bottle number.")
        Else
            'Set query
            bottle = .field_search.Value
            Set allTransactionData = Worksheets("Transactions")

            'Find most recent transaction for relevant bottle number
            With allTransactionData
                Dim foundRng As Range
                Set foundRng = .Columns("C:C").Find(What:=bottle, LookIn:=xlFormulas, _
                                                    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, _
                                                    MatchCase:=False, SearchFormat:=False)

                If Not foundRng Is Nothing Then

                    'Pull the former container location
                    bottleFormer = bottle
                    locationFormer = allTransactionData.Cells(foundRng.Row, 6)
                Else

                    'Inform user there are no transactions under query
                    bottle = "No Transactions"
                    locationFormer = "Found."

                End If
            End With
        End If
    End With

    With Me

        'Fill form fields with search results
        .field_bottle = bottle
        .field_locationFormer = locationFormer

        'Set focus to new location
        .field_location.SetFocus


    End With
End Sub

Private Sub button_save_active_Click()

    With Me
        'Validate that search has been performed
        If .field_search.Value = "" Then
            MsgBox ("Search for a bottle number first.")
        Else
            'Validates if bottle was found
            If .field_locationFormer.Value = "Found." Then
                MsgBox ("Search must yield a bottle result before you can modify a location.")
            Else
                'Validates contents in location field
                If .field_location.Value = "" Then
                    MsgBox ("Please enter a location.")
                Else

                    '               Issue with value + 1268


                    'Enter the location

                    Set allTransactionData = Worksheets("Transactions")

                    With allTransactionData
                        Dim foundRng As Range
                        Set foundRng = .Columns("C:C").Find(What:=bottle, LookIn:=xlFormulas, _
                                                            LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, _
                                                            MatchCase:=False, SearchFormat:=False)

                        If Not foundRng Is Nothing Then
                            .Cells(foundRng.Row, 11).Value = Me.field_location.Value
                        End If
                    End With
                    'Empty fields for next use
                    With Me
                        locationNew = ""
                        bottle = ""
                        bottleFormer = "^ Search Bottle"
                        locationFormer = ""
                        .field_locationFormer.Value = locationFormer
                        .field_bottle = bottleFormer
                        .field_search = bottle
                        .field_location = locationNew
                        'Set focus to search field
                        .field_search.SetFocus
                    End With
                End If
            End If
        End If
    End With
End Sub

Private Sub button_search_inactive_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    'Add Color to Search Button
    button_search_inactive.Visible = False
    button_save_inactive.Visible = True

End Sub

Private Sub button_save_inactive_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    'Add Color to Save Button
    button_save_inactive.Visible = False
    button_search_inactive.Visible = True

End Sub

Private Sub UserForm_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    'Reset buttons to white

    button_search_inactive.Visible = True
    button_save_inactive.Visible = True

End Sub

Private Sub frame_current_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)

    button_search_inactive.Visible = True

End Sub

Private Sub frame_new_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)

    button_save_inactive.Visible = True

End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)

    If CloseMode = 0 Then
        Application.Calculation = xlAutomatic
    Else

    End If

End Sub

Поиск пользователя: Bottle 1

Bottle 1 найдено в строке 2 под заголовком. Строки 3 и далее пусты.

releRow должно равняться 1, но вместо этого равно 1269. В результате (1269,10) становится выделением, а я хочу (1,10). Я попробовал простое вычитание (releRow = releRow - 1268) с небольшим ожиданием, и это не решило проблему.

Заранее спасибо, это мой первый пост.

1 Ответ

1 голос
/ 16 марта 2020

Нет необходимости Select, и вы на самом деле не ссылаетесь на With allTransactionData. Обратите внимание на период ., необходимый перед Columns("C:C").

With allTransactionData
    Dim foundRng as Range
    Set foundRng = .Columns("C:C").Find(What:=bottle, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, _
        MatchCase:=False, SearchFormat:=False)

    If Not foundRng Is Nothing Then
         .Cells(foundRng.Row, 10).Value = Me.field_location.Value
    End If
End With
...