如何从文本框中捕获时间并将其粘贴到Excel表格中

员工login系统使用excel与macros。 员工将input员工ID,然后在txtName中显示他们的姓名。 如果他们点击loginbutton,我希望能够捕获login时间并将其粘贴到Excel表格中,然后在注销时反之亦然。

这是截图: 截图

第二个屏幕截图: Logout_issue

以下是目前的代码:

Dim CM As Boolean Private Sub txtEmpID_Change() Dim mySheet As Worksheet Dim myRange As Range Set mySheet = Sheets("Emp_ID") Set myRange = mySheet.Range("B:B").Find(txtEmpID.Value, , , xlWhole) If Not myRange Is Nothing Then txtName.Value = myRange.Offset(0, -1) Else txtName.Value = "Match not found" End If End Sub Private Sub UserForm_activate() Do If CM = True Then Exit Sub txtTime = Format(Now, "hh:mm:ss") DoEvents Loop End Sub Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) CM = True End Sub 

首先,我build议您使用控件的用户名称来避免可能的错误。 其次,你可以使用do loop而不使用if这样:

 Do While CM = False UserForm1.txtTime = Format(Now, "hh:mm:ss") DoEvents Loop 

至于你的问题,这里是如何将值从文本框传递到您的工作表中的最后一个空单元格:

 Private Sub CommandButton1_Click() With Worksheets("Emp_ID").Range("A65536").End(xlUp) .Offset(1, 0) = UserForm1.txtName.Value .Offset(1, 1) = UserForm1.txtEmpID.Value .Offset(1, 2) = UserForm1.txtTime.Value End With Unload Me 'Optional: Close Userform1 End Sub 

当你说“当注销时反之亦然”时,我不会跟着你,但是如果你想logging注销时间,你也可以使用注销button(CommandButton2)来做同样的事情:

 Private Sub CommandButton2_Click() Worksheets("Emp_ID").Range("D65536").End(xlUp).Offset(1) = Format(Now, "hh:mm:ss") Unload Me 'Optional: Close Userform On Where Logout Button Is End Sub 

请记住,为了能够将文本框值传递给工作表单元格,userform应该是打开的。 除非在closures之前将它们传递给全局variables,否则不能传递closures的用户窗体中的值。