Использование COUNTIF и SUMIF вместо цикла - PullRequest
0 голосов
/ 21 сентября 2019

У меня есть рабочий код ниже, но когда я нажимаю ОК, перед закрытием формы пользователя появляется 3-секундная пауза.дело в том, что в моей таблице будет только один результат, который соответствует, так что я не думаю, что мне действительно нужно делать это таким образом, и есть более эффективные способы.все, что мне нужно сделать, это найти строку, соответствующую имени, затем заполнить 5 столбцов этой строки значениями.это что-то подходит для COUNTIF и SUMIF?я попытался дать ему понять, но я не смог заставить его перестать выдавать ошибки, из-за которых я спрашиваю, правильно ли я поступаю.

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

Private Sub OKButton_Click()

    If Me.ComboBox1.Value = vbNullString Then
        MsgBox "Please Select a member of staff", , "Error"
        Exit Sub
    End If


    With TimetableUserForm
        .Hide
        If CheckBox1.Value = False And CheckBox2.Value = False And CheckBox3.Value = False And CheckBox4.Value = False And CheckBox5.Value = False Then
            MsgBox "Error", , "Error"
            Exit Sub
        Else
            Dim EmployeeName As String, f As range, tbl As ListObject, Counter As Integer, LastRow As Long, listcolumns As range
            EmployeeName = ComboBox1.Value
            With Sheets("Timetable").ListObjects("TblTimetable")
                LastRow = .range.Rows.Count
                For Counter = LastRow To 1 Step -1
                Set f = .DataBodyRange.Cells(Counter, .listcolumns("Name and Surname").Index)
                If f = EmployeeName Then
                    If TextBox1.Value = vbNullString And TextBox2.Value = vbNullString And TextBox3.Value = vbNullString And TextBox4.Value = vbNullString And TextBox5.Value = vbNullString Then
                        With f.EntireRow
                            .Cells(5).Value = CheckBox1.Value
                            .Cells(6).Value = CheckBox2.Value
                            .Cells(7).Value = CheckBox3.Value
                            .Cells(8).Value = CheckBox4.Value
                            .Cells(9).Value = CheckBox5.Value
                        End With
                    Else
                        With f.EntireRow
                            .Cells(5).Value = TextBox1.Value
                            .Cells(6).Value = TextBox2.Value
                            .Cells(7).Value = TextBox3.Value
                            .Cells(8).Value = TextBox4.Value
                            .Cells(9).Value = TextBox5.Value
                        End With
                    End If
                    Exit For
                End If
                Next Counter
            End With
        End If
    End With
    Unload Me
End Sub

Вот макрос, который открывает пользовательскую форму

Private Sub Rectangle_16_Click()
If Sheets("Settings").range("Protected") = 1 Then
            'do nothing
            Else
TimetableUserForm.Show
End If
End Sub

1 Ответ

2 голосов
/ 21 сентября 2019

поместите Exit For сразу после заполнения ячеек

, кроме того, вот еще несколько предложений:

Private Sub OKButton_Click()

    With Me ' reference the Userform
        .Hide ' hide the userform

        If .ComboBox1.Value = vbNullString Then
            MsgBox "Please Select a member of staff", , "Error"
            Exit Sub
        End If

        If .CheckBox1 Or .CheckBox2 Or .CheckBox3 Or .CheckBox4 Or .CheckBox5 Then
            Dim EmployeeName As String, f As Range, tbl As ListObject, Counter As Integer, LastRow As Long, listcolumns As Range
            EmployeeName = .ComboBox1.Value
            With Sheets("Timetable").ListObjects("TblTimetable")
                LastRow = .Range.Rows.Count
                For Counter = LastRow To 1 Step -1
                    Set f = .DataBodyRange.Cells(Counter, .listcolumns("Name and Surname").Index)
                    If f = EmployeeName Then
                        With f.EntireRow
                            .Cells(5).Value = Me.TextBox1.Value
                            .Cells(6).Value = Me.TextBox2.Value
                            .Cells(7).Value = Me.TextBox3.Value
                            .Cells(8).Value = Me.TextBox4.Value
                            .Cells(9).Value = Me.TextBox5.Value
                        End With
                        Exit For
                    End If
                Next
            End With
        End If

    End With

'    Unload Me ' <-- move Unload command in the sub that has shown the userform
End Sub

Что касается правильного места для команды Unload, вот ваш Rectangle_16_Click()редакция:

Private Sub Rectangle_16_Click()
    If Sheets("Settings").range("Protected") = 1 Then
            'do nothing
    Else
        With New TimetableUserForm ' instantiate a new instance of your Userform class and reference 
            .Show ' show it
        End With ' this will set the reference object to Nothing      
    End If
End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...