2015-09-09 62 views
1

所以我有這個按鈕代碼時鐘和時鐘輸出,它的工作正常,但我的問題是,該按鈕是在第一張表,我需要它在另一張名爲Timesheet的表上加蓋時間。這是我的代碼。我想如果我用Timesheet替換每個括號中的單詞Location並且它不會在時間表中標記時間。在另一張紙上打印,爲什麼它不起作用?

Sub StampNext() 
    Dim r As Range 
    On Error Resume Next 
    Set r = Range("Timesheet") 
    On Error GoTo 0 
    If r Is Nothing Then Range("A1").Name = "Timesheet" 
    With Range("Timesheet") 
     .Value = Time 
     .NumberFormat = "hh:mm" 
     If .Row = 1 Then 
      .Offset(2, 0).Name = "Timesheet" 
     Else 
      .Offset(-2, 1).Name = "Timesheet" 
     End If 
    End With 
End Sub 

我也有時間表保護,因爲我的老闆不希望員工篡改表。我不知道這是否會成爲代碼的阻礙問題,或者只是無關緊要。

回答

1
Sub StampNext() 

    'Declare a variable as a worksheet and a variable for the named range 
    Dim wsT As Worksheet 
    Dim wsA as Worksheet 
    Dim rngT As Range 

    'Set that variable to the worksheet named "Timesheet" 
    Set wsT = ThisWorkbook.Worksheets("Timesheet") 
    Set wsA = ActiveSheet 

    'Unprotect the sheet using the password. 
    '(Note: you should protect the VBA project from viewing to 
    ' prevent others from viewing the password.) 
    wsT.Unprotect ("sheetPassword") 
    wsT.Activate 

    'Set Range variable 
    On Error Resume Next 
    Set rngT = wsT.Range("Timesheet") 
    On Error GoTo 0 

    If rngT Is Nothing Then 
     wsT.Range("A1").Name = "Timesheet" 
     Set rngT = wsT.Range("Timesheet") 
    End If 


    'Add value and update the named range "Timesheet" 
    With rngT 
     .Value = Time 
     .NumberFormat = "hh:mm" 

     If .Row = 1 Then 
      .Offset(2, 0).Name = "Timesheet" 
     Else 
      .Offset(-2, 1).Name = "Timesheet" 
     End If 
    End With 

    'Reprotect sheet with password 
    wsT.Protect ("sheetPassword") 
    wsA.activate 
End Sub 
+0

它仍然在主表中打印,我不想要。我不知道發生了什麼 – KjosN1

+0

主表的名稱是什麼?我更新了代碼 - 試試看看是否更明確的引用wsT和wsA的幫助。 –

+0

我的主表的名稱是主 – KjosN1

2

您需要聲明工作表對象,然後才能寫入它。

Dim ws1 As Excel.Worksheet 
Set ws1 = ActiveWorkbook.Sheets("Timesheet") 

ws1.Range("A1").Value = Time 

我不確定受保護的工作表,但我的猜測是您將不得不暫時解除保護。

+0

好的,謝謝你這麼快 – KjosN1

相關問題