2017-07-14 170 views
0

我在下面的代碼行中得到了對象所需的運行時錯誤,我檢查了它們的正確表名,但仍然顯示相同的錯誤Sheet1.Range(「A1」)。Value = Date & 「」 &時間對象所需運行時錯誤'424'

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

它是'Sheet1'的'CodeName',不一定是你的工作表的名字,對吧? –

+0

我想我解決了它的工作表(「Sheet1」)。Range(「A1」)。Value = Date&「」&Time – Kittu

+0

@shai你說的也是正確的..我會試試這種方式 – Kittu

回答

0

當您使用Sheet1.Range("A1").ValueSheet1實際上是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 
0

使用變量爲你的表使用:

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

如果你是闖民宅很多工作表其必須使用,但也使得它更容易改變以後。

+0

我知道,但是當你不使用/打開多個工作簿時,不需要它。 – UGP

+0

Shai Radao和UGP感謝您的澄清 – Kittu

相關問題