【问题标题】:object required run time error '424'对象所需的运行时错误“424”
【发布时间】:2017-07-14 05:25:18
【问题描述】:

我在下面的代码中收到对象所需的运行时错误,我检查了工作表名称它们是否正确但仍然显示相同的错误 Sheet1.Range("A1").Value = Date & " " & Time

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

【问题讨论】:

  • 它是Sheet1 CodeName,不一定是您的工作表名称,对吧?
  • 我想我解决了 worksheets("Sheet1").Range("A1").Value = Date & " " & Time
  • @shai 你说的也对..我会这样尝试

标签: excel userform vba


【解决方案1】:

当您使用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

【讨论】:

    【解决方案2】:

    要将变量用于表格,请使用:

    Dim sht as Worksheet
    Set sht = Worksheets("Name")
    

    如果您要大量参考工作表,则必须使用它,但也可以让以后更容易更改。

    【讨论】:

    • 我知道,但是当您不使用/打开多个工作簿时,不需要它。
    • Shai Radao 和 UGP 感谢您的澄清
    猜你喜欢
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多