簡體   English   中英

從 MS Access VBA 在密碼失敗后關閉加密 excel

[英]From MS Access VBA close encrypted excel after failed password

I'm keeping an ID for API in an encrypted excel file (open to alternative suggestions) and using Microsoft access VBA to open the encrypted excel and extract the ID.

問題是如果密碼錯誤,它不會關閉 excel。 如果您正確輸入密碼,此代碼可以正常工作

Public Function getDeploymentID() As String
Dim fileLocation As String
fileLocation = "___DeploymentID.xlsx"
Dim objExcel As Object
Set objExcel = CreateObject("Excel.Application")
Dim wb As Excel.Workbook

On Error GoTo getDeploymentID_ERROR
MsgBox "The development password is in a password protected excel. It will prompt you for the password next"
Set wb = Workbooks.Open(fileLocation, True)
'User must enter password to continue. If they don't it'll error out on above line
DoEvents

'Get deploymentID
getDeploymentID = wb.Worksheets("Sheet1").Cells(1, 1)

'Close it
'wb.Close               'will close workbook, won't close excel
wb.Application.Quit     'will close workbook and excel
DoEvents
GoTo getDeploymentID_Cleanup

getDeploymentID_ERROR:
Debug.Print "Failed to open DeploymentID excel file. Error " & err.Number & ":" & err.description
objExcel.Quit           'THIS IS NOT WORKING
DoEvents

getDeploymentID_Cleanup:
Set wb = Nothing
Set objExcel = Nothing
End Function

我相信您需要通過objExcel訪問Workbooks集合。

Set wb = objExcel.Workbooks.Open(fileLocation, True)

然后,

wb.Close 'close workbook
objExcel.Quit 'quit excel app

參考:


關於 function 的結構,我將在底部添加錯誤處理並調用Resume以避免第二個GoTo語句。

'...
On Error GoTo getDeploymentID_ERROR
'...

'Get deploymentID
 getDeploymentID = wb.Worksheets("Sheet1").Cells(1, 1)

getDeploymentID_Cleanup:
    wb.Close
    objExcel.Quit
    Exit Function

getDeploymentID_ERROR:
    Debug.Print "Failed to open DeploymentID excel file. Error " & err.Number & ":" & err.description
    Resume getDeploymentID_Cleanup
End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM