提前感谢您的帮助。我有一本工作簿,其中有一个与 Pi 系统相关的公式。
目标:
我一直希望这个工作簿的“计算选项”无论进行什么操作(打开、保存、关闭)都保持在手动状态。
下面是我从此处阅读的 VBA 代码,但它没有按照我想要的方式工作。 密码错误时工作簿仍然打开。当我在工作簿中点击保存时,它开始计算。
我需要帮助来修改下面的 VBA 代码以完成我上面想要的操作。
Private Sub Workbook_Open()
uName = InputBox("Please type your username.", "Authentication Required", Environ("USERNAME"))
uPwd = InputBox("Please type your password.", "Authentication Required")
On Error GoTo ErrorRoutine
If uPwd = Application.WorksheetFunction.VLookup(uName, Sheets("Password").Range("A:B"), 2, False) Then
'Password correct
Sheets("BE").EnableCalculation = False
Sheets("BE").Visible = True
Sheets("XGI Tags").Visible = True
Sheets("Password").Visible = xlVeryHidden
Sheets("KQI Tags").Visible = True
Else
'Password incorrect
ErrorRoutine:
msgReply = MsgBox("Password is incorrect. Spreadsheet will be closed.", "Invalid Password", vbOKOnly)
ActiveWorkbook.Close (False)
End If
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Sheets("BE").EnableCalculation = False
Sheets("BE").EnableCalculation = False
Sheets("BE").Visible = True
Sheets("XGI Tags").Visible = True
Sheets("Password").Visible = xlVeryHidden
Sheets("KQI Tags").Visible = True
End Sub
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
Sheets("BE").Visible = True
End Sub
我已经尝试过上面的代码,但效果不佳。
您正在使用错误处理来进行流量控制,这并不总是一个好主意:您可以这样做 -
Private Sub Workbook_Open()
Dim uName As String, uPwd As String, res, ok As Boolean, wb As Workbook
uName = InputBox("Please type your username.", "Authentication Required", Environ("USERNAME"))
uPwd = InputBox("Please type your password.", "Authentication Required")
res = Application.VLookup(uName, ThisWorkbook.Worksheets("Password").Range("A:B"), 2, False)
If Not IsError(res) Then ok = (uPwd = res) 'check password match
Set wb = ThisWorkbook
If ok Then
'Password correct
wb.Worksheets("BE").EnableCalculation = False
wb.Worksheets("BE").Visible = True
wb.Worksheets("XGI Tags").Visible = True
wb.Worksheets("Password").Visible = xlVeryHidden
wb.Worksheets("KQI Tags").Visible = True
Else
'Password incorrect
MsgBox "Password is incorrect. Spreadsheet will be closed.", "Invalid Password", vbOKOnly
wb.Close False
End If
End Sub