简体   繁体   English

在另一张纸上打印,为什么不工作?

[英]Printing on a different sheet, why isn't it working?

So I have this button code to clock in and clock out and it works fine, but my problem is that the button is on the first sheet and I need it to stamp the time on a different sheet called Timesheet. 所以我有这个按钮代码进入和退出,它工作正常,但我的问题是按钮是在第一张纸上,我需要它在一个名为Timesheet的不同工作表上标记时间。 Here is my code. 这是我的代码。 I thought if I replaced the word Location that was in every parenthesis with the word Timesheet and it will just not stamp the time in the 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

I also have the Timesheet protected because my boss doesn't want the employee to tamper with the sheet. 我还保护时间表,因为我的老板不希望员工篡改工作表。 I don't know if that would be a hindering problem to the code or if that just doesn't matter. 我不知道这对代码是否会成为一个阻碍问题,或者这无关紧要。

You need to declare the worksheet object and then you can write to it. 您需要声明工作表对象,然后您可以写入它。

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

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

I'm not sure about the protected sheet, but my guess is you will have to unprotect it temporarily. 我不确定受保护的纸张,但我的猜测是你必须暂时取消保护。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM