我在行下面的代码中得到了对象所需的运行时错误,我检查了表单名称是否正确但是仍然显示相同的错误Sheet1.Range(" A1")。Value = Date& " " &安培;时间
Private Sub CommandButton1_Click()
Dim username As String
Dim password As String
username = TextBox1.Text
password = TextBox2.Text
Dim info
info = IsWorkBookOpen("D:\TMS_Project\username-password.xlsx")
If info = False Then
Workbooks.Open ("D:\TMS_Project\username-password.xlsx")
End If
Dim x As Integer
x = 2
Do While Cells(x, 1).Value <> ""
If Cells(x, 1).Value = username And Cells(x, 2).Value = password Then
MsgBox "Welcome!"
Sheet1.Range("A1").Value = Date & " " & Time
Selection.NumberFormat = "m/d/yyyy h:mm AM/PM"
UserForm1.Hide
ActiveWorkbook.Close True
End
Else
x = x + 1
End If
Loop
MsgBox "Please check your username or password!"
ActiveWorkbook.Close True
TextBox1.Text = ""
TextBox2.Text = ""
TextBox1.SetFocus
End Sub
答案 0 :(得分:0)
当您使用Sheet1.Range("A1").Value
时,Sheet1
实际上是Worksheet.CodeName
属性,请在MSDN上阅读。
虽然我认为您打算使用工作表,其名称为“ Sheet1 ”,但您需要使用Worksheets("Sheet1").Range("A1").Value
。
如果您已定义并设置了Worksheet
对象,则可以跟踪它。
我正在使用下面的代码,以确认没有人更改了我的工作表名称(或删除了它)。
Option Explicit
' list of worksheet names inside Workbook - easy to modify here later
Const ShtName As String = "Sheet1"
'====================================================================
Sub VerifySheetObject()
Dim Sht As Worksheet
On Error Resume Next
Set Sht = ThisWorkbook.Worksheets(ShtName)
On Error GoTo 0
If Sht Is Nothing Then ' in case someone renamed the Sheet (or it doesn't exist)
MsgBox "Sheet has been renamed, it should be " & Chr(34) & ShtName & Chr(34), vbCritical
Exit Sub
End If
' your line here
Sht.Range("A1").Value = Date & " " & Time
End Sub
答案 1 :(得分:0)
要使用变量用于表格,请使用:
Dim sht as Worksheet
Set sht = Worksheets("Name")
如果您要大量引用工作表,那么必须使用它,但也可以让以后更容易更改。