是否可以使用 VBA 仅针对特定 date/time 使用密码锁定 excel 文件?

Is it possible to lock excel file with password using VBA for just specific date/time?

我目前正在为 excel 创建宏驱动文件,其中相当大量的数据通过 .csv 文件上传,并根据一些规则重新分发到不同的选项卡。 (遗憾的是没有直接 link 到数据库) 每周五都会发生这种情况,直到 12:00AM,在此期间 - 8:00 - 12:00 我想对文件进行密码保护。因此只有负责加载所有数据的人才能使用该文件。

因为它是在具有自动保存功能的 SharePoint 上工作的共享文件,所以很多人想同时使用它。但是 excel 和共享功能并不真正喜欢多人,而宏在后台 运行。那么我是否可以在 Workbook.open() 上弹出一些 MsgBox,其中包含有关当前不可用的文件的信息,并且如果日期 == 星期五,时间在 8-12 点之间,则需要密码才能继续?

是的,这是可能的。

Function unlockwb()

pw = "mypassword1"
' Unprotect WB structure
ThisWorkbook.Unprotect pw
' Unrotect sheet
Sheet1.Unprotect pw

End Function

Function lockwb()

pw = "mypassword1"
' Protect WB structure
ThisWorkbook.Protect pw, True, True
' Protect sheet
Sheet1.Protect pw

End Function

Sub LockOnTime()
'Unlock all, lock again if condition(s) is/are satisfied
unlockwb

' Lock by day of the week
weekdaylock = vbFriday
If Weekday(Date) = weekdaylock Then
    lockwb
End If

' Or lock by time
timelowerbound = TimeValue("11:00:00 AM")
timeupperbound = TimeValue("12:00:00 PM")
If timelowerbound < Time() And Time() < timeupperbound Then
    lockwb
End Sub

' Or both
If Weekday(Date) = weekdaylock Then
    If timelowerbound < Time() And Time() < timeupperbound Then
        lockwb
    End Sub
End If

感谢 Tim Stack 的回答 - 我为将来对它感兴趣的人做了一些修改:

@FaneDuru - must be called by a event you mentioned works because the code is 运行 on "ThisWorkbook" In Excel VBA 这意味着它被调用每次打开工作簿。

Option Explicit
Function unlockwb()
Dim pw

pw = "xxx"
' Unprotect WB structure
ThisWorkbook.Unprotect pw
' Unrotect sheet
Sheet1.Unprotect pw

End Function
Function lockwb()
Dim pw

pw = "xxx"
' Protect WB structure
ThisWorkbook.Protect pw, True, True
' Protect sheet
Sheet1.Protect pw

End Function
Sub Workbook_Open()

Dim weekdaylock, timelowerbound, timeupperbound, pw
pw = "xxx"

weekdaylock = vbFriday
If Weekday(Date) = weekdaylock Then
    lockwb
End If

timelowerbound = TimeValue("08:00:00")
timeupperbound = TimeValue("12:00:00")
' Or both
If Weekday(Date) = weekdaylock Then
    If timelowerbound < Time() And Time() < timeupperbound Then
        If InputBox("Please enter password to continue.", "Enter Password") <> pw Then
            MsgBox "Wrong Password"
            lockwb
            ThisWorkbook.Close
        Else
            unlockwb
        End If
    End If
End If
End Sub