无论执行什么操作(打开、保存、关闭),工作簿“计算选项”都会保持在手动状态,除非获得批准的用户点击计算

问题描述 投票:0回答:1

提前感谢您的帮助。我有一本工作簿,其中有一个与 Pi 系统相关的公式。

目标:

  1. 用户通过密码进行身份验证
  2. 如果密码错误,工作簿将关闭
  3. 是否应打开正确的工作簿并保持手动模式,直到激活计算。

我一直希望这个工作簿的“计算选项”无论进行什么操作(打开、保存、关闭)都保持在手动状态。

下面是我从此处阅读的 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

我已经尝试过上面的代码,但效果不佳。

excel vba formula spreadsheet
1个回答
0
投票

您正在使用错误处理来进行流量控制,这并不总是一个好主意:您可以这样做 -

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
© www.soinside.com 2019 - 2024. All rights reserved.