在VBA中运行导入的宏时出现问题

时间:2017-07-25 09:54:20

标签: excel vba excel-vba automation

我想从指定文件夹中所有工作簿中的指定位置导入宏文件,并希望在每个工作簿上运行宏,我可以通过下面提到的代码成功导入所有工作簿但无法运行那些宏。

Sub RecursiveFolders()
    Dim FileSys As Object
    Dim objFolder As Object
    Dim objSubFolder As Object
    Dim objFile1 As Scripting.File
    Dim wkbOpen As Workbook
    Dim szImportPath As String
    Dim objFSO As Scripting.FileSystemObject
    Dim cmpComponents As VBIDE.VBComponents

    Set objFSO = New Scripting.FileSystemObject
    Set FileSys = CreateObject("Scripting.FileSystemObject")
    Set objFolder = FileSys.GetFolder("C:\Users\Yashika Vaish\Desktop\testform")

    Application.ScreenUpdating = False

    For Each objSubFolder In objFolder.SubFolders
        For Each objFile In objSubFolder.Files

            Set wkbOpen = Workbooks.Open(Filename:=objFile)
            szImportPath = FolderWithVBAProjectFiles & "C:\Macros"
            Set cmpComponents = wkbOpen.VBProject.VBComponents

            For Each objFile1 In objFSO.GetFolder(szImportPath).Files

                If (objFSO.GetExtensionName(objFile1.Name) = "cls") Or _
                   (objFSO.GetExtensionName(objFile1.Name) = "frm") Or _
                   (objFSO.GetExtensionName(objFile1.Name) = "bas") Then
                    cmpComponents.Import objFile1.Path
                End If
            Next objFile1

            Application.DisplayAlerts = False

            MsgBox "Import is ready"
            Application.Run "HeaderChange_User_Financial_Input"
            Application.Run HeaderChange_User_Financial_Input
            Application.Run HeaderChange_User_Operation_Input
            Application.Run SelectRangeUnitMap
            Application.Run reportingunitmap
            Application.Run HeaderChange_Finacial_Standard
            Application.Run HeaderChange_Operation_Standard
            wkbOpen.Close savechanges:=True
        Next
    Next

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub

此代码让我弹出无法运行的宏,

  

可能无法使用或所有宏都已禁用

但是没有密码和保护,所以为什么我无法运行宏,请帮助。

2 个答案:

答案 0 :(得分:0)

调用宏(未测试)时需要包含工作簿名称:

strFile = ActiveWorkbook
Application.Run "'" & strFile.Name & "'!HeaderChange_User_Financial_Input"

答案 1 :(得分:0)

因为您没有使用Option Explicit,所以您没有看到您的问题,因此我建议您始终使用Option Explicit在编辑器中标记此类内容。< / p>

这里的问题是

Application.Run HeaderChange_User_Financial_Input

VBA假定HeaderChange_User_Financial_Input是包含宏引用的变量。但是这个变量是空的,因为它从未被设置,因此它无法找到该宏。

我认为你的意思是HeaderChange_User_Financial_Input是宏名而不是变量所以请改用字符串

Application.Run "HeaderChange_User_Financial_Input"

代码中的所有Application.Run