Используйте цикл, чтобы найти строку на основе двух критериев и вставить текущее время в 12-й столбец - PullRequest
0 голосов
/ 13 января 2019

У меня есть userform1, который действует как экран входа в систему для ввода данных в базу данных для каждого человека. Userform2 для выхода. Я использую цикл для сопоставления имени и данных в базе данных. Когда имя и дата найдены, мне нужно поместить текущее время в пустой столбец, самый дальний столбец справа от набора данных. Это столбец 12. Я перепробовал много разных комбинаций, и ничто не вставит текущее время в соответствующую ячейку. У меня где-то что-то написано неправильно, но я не знаю, какая часть неправильная. Вероятно, в пределах 2 критериев (NameOut и DateOut) и / или вставки текущего времени.

Private Sub LogOutButton_Click()

Dim finalrow As Integer
Dim i As Integer
Dim NameOut As String
Dim DateOut As String

NameOut = NameOutBox.Text
DateOut = DateOutBox.Text

Sheets("ATDataSheet").Select
finalrow = Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To finalrow
    If Cells(i, 1).Value = NameOut And Cells(i, 2).Value = DateOut Then
        Cells(Columns.Count, 12).End(xlToLeft).Offset(1, 0) = Format(Time, "hh:mm")

        End If

    Next i


Unload Me


Sheets("SignIN").Select

MsgBox "LOG OUT Successful"

End Sub

Когда человек уходит на день, он нажимает кнопку «Выйти», которая открывает форму пользователя2. Они вводят свое имя и дату и нажимают кнопку «Выйти» в пользовательской форме. Затем код выполнит поиск в базе данных, найдет имя и дату, а затем поместит текущее время в 12-й столбец базы данных.

1 Ответ

0 голосов
/ 13 января 2019

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

Private Sub LogOutButton_Click()

    Dim finalrow As Integer             ' better to be Long
    Dim i As Integer                    ' better to be Long
    Dim NameOut As String
    Dim DateOut As String

    ' If the following are text boxes on a user form
    ' note that no form has been loaded.
    NameOut = NameOutBox.Text           ' can you avoid typos? What about case?
    DateOut = DateOutBox.Text           ' This isn't a date. It's text that looks like a date.
                                        ' Try not to need the user's injput for this date.
                                        ' It should always be the current date or the date before.

    Sheets("ATDataSheet").Select        ' Don't select anything !!!
    ' Presumably the button is on a sheet. That sheet is the ActiveSheet - no doubt.
    ' If you want to refer to "ATDataSheet", assign it to a variable, e.g.
    ' Dim Ws as worksheet
    ' Set Ws = Worksheets("ATDataSheet")

'    finalrow = Cells(Rows.Count, 1).End(xlUp).Row

    With Ws                             ' refer to the declared worksheet
        finalrow = .Cells(.Rows.Count, 1).End(xlUp).Row
        For i = 2 To finalrow
            ' the next line is highly problematic:
                ' a) the name may not match (different case, wrong spelling)
                ' b) the date may not match (different format, different spelling)
                    ' Try to create a system by which the date is always a true date,
                    ' meaning a number. I think it is created on sign-in. At that time it
                    ' should be the current date and you can enter it without the user's
                    ' asistance, thereby making sure it's a proper date, for example,
                    ' Cells(R, 2)Value = Date
                    ' Then, on the way out, you might check for
                    ' .Cells(i, 2).Formula = Clng(CDate(DateOut))
            If .Cells(i, 1).Value = NameOut And .Cells(i, 2).Value = DateOut Then
                ' wrong addressing. you want .Cells(i, 12)
                .Cells(Columns.Count, 12).End(xlToLeft).Offset(1, 0) = Format(Time, "hh:mm")
            End If

        Next i
    End With

    ' Me is the worksheet at this point. No form has been loaded.
    ' The worksheet can' be unloaded.
    Unload Me

    ' I think this is the sheet on which you have the button which
    ' called this procedure. If you didn't select any other sheet,
    ' and you should not, then it is still the ActiveSheet at this point.
    Sheets("SignIN").Select

    MsgBox "LOG OUT Successful"

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