繁体   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