如何使用Application.Run获取受密码保护的工作簿?

时间:2011-02-10 13:07:31

标签: excel vba excel-vba

作为我创建的基于Excel的调度程序的一部分,我使用'Application.Ontime'函数以下列方式在指定时间执行宏

Sub Load
    //snipped for brevity

    Dim startName As String
    startName = "'StartSub""" & filePath & """, """ & fileName & """, """ & macroName & """'"

    Application.OnTime y, startName

End Sub

Sub StartSub(filePath As String, fileName As String, macroName As String)
    Dim wb As String
    wb = "'" & filePath & "'!" & macroName
    Application.Run wb
    Application.Workbooks(fileName).Close Savechanges:=True
End Sub

测试和简单的POC似乎运作得很好。我面临的问题是其中一个电子表格受密码保护。问题是密码输入对话框阻止宏执行,我猜这是预期的。由于输出和结果被导出到多个报告,因此无需对受密码保护的工作簿进行写访问。

我的问题是如何克服这个问题并使用Application.Run从受密码保护的工作簿中运行宏?

2 个答案:

答案 0 :(得分:1)

没用。 MS不支持它。在运行之前,您需要取消保护工作簿。以下是一个示例:http://www.ozgrid.com/forum/showthread.php?t=36816&page=1

答案 1 :(得分:0)

由于工作簿受密码保护,因此在打开文件时始终提供密码。为了解决这个问题,我需要将密码存储在我的工作簿中。所以问题实际上归结为用正确的密码打开文件。

Sub StartSub(filePath As String, fileName As String, macroName As String)
    Dim wb As String
    wb = "'" & filePath & "'!" & macroName
    Dim scheduledWb As Workbook

    Dim pwd As String
    Dim saveChange As Boolean
    pwd = GetPassword(fileName) ' method that extracts correct password from somewhere
    If Len(pwd) > 0 Then
        Set scheduledWb = Workbooks.Open(fileName:=filePath, ReadOnly:=True, Password:=pwd)
        saveChange = False
    Else
        Set scheduledWb = Workbooks.Open(fileName:=filePath)
        saveChange = True
    End If

    Application.Run "'" & fileName & "'!" & macroName
    Application.Workbooks(fileName).Close Savechanges:=saveChange
End Sub
相关问题