在另一张纸上打印,为什么它不起作用?

时间:2015-09-09 13:14:13

标签: excel vba

所以我有这个按钮代码进入和退出并且它工作正常,但我的问题是按钮在第一张纸上,我需要它在一张名为Timesheet的不同纸张上标记时间。这是我的代码。我想如果我用单词Timesheet替换每个括号中的位置,它就不会在时间表中标记时间。

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

我还保护时间表,因为我的老板不希望雇员篡改工作表。我不知道这对代码是否会成为一个阻碍问题,或者这是否无关紧要。

2 个答案:

答案 0 :(得分:2)

您需要声明工作表对象,然后才能写入它。

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

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

我不确定受保护的表格,但我猜你必须暂时取消保护。

答案 1 :(得分: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