Getting “Cannot Run the Macro…” Error in VBA

穿精又带淫゛_ 提交于 2019-12-08 07:52:56

问题


I recently learned how to program in VBA and have gotten some extremely helpful assistance by reading through the previously asked questions and answers on this site. However, I have encountered a problem in one of my programs that doesn't appear to be addressed very directly. So I'll ask it here.

I am making a Powerpoint macro that will automatically update some slides with new data. For one slide that contains an excel table, I want the macro to open up an excel file, run an existing macro in the excel file to populate the spreadsheet with new data, and finally copy the table over to the powerpoint slide. My code so far (without the copy over portion) is this:

Private Sub GetProposals()
    Dim myXL As Excel.Application
    Dim myXLS As Excel.Workbook
    Dim ws As Excel.Worksheet

    Set myXL = New Excel.Application
    Set myXLS = GetObject("K:\Jackson\Proposal Summary Master.xlsm")
    Set ws = myXLS.Sheets(1)
    ws.Visible = xlSheetVeryHidden

    myXLS.Sheets("VLOOKUP").Range("J1").Value = "EPL"
    myXL.Run ("'K:\Jackson\Proposal Summary Master.xlsm'!BABox_Change")
End Sub

It runs correctly until I reach the "myXL.Run..." line. I get a message saying "Run-time error '1004': Cannot run the macro "K:\Jackson\Proposal Summary Master.xlsm'!BABox_Change'. The macro may not be available in this workbook or all macros may be disabled."

The excel macro runs fine when I open up the file directly and start it that way. I am somewhat stuck on what I should do next. Does anyone have some suggestions?


回答1:


The issue may be because you're not opening the workbook. The key to this though, would be to make sure that the objects are released after the code is executed; that way, the file isn't "locked" by your powerpoint file or extra 'hidden' processes/instances of Excel are left open.

Private Sub GetProposals()
    Dim myXL As Excel.Application
    Dim myXLS As Excel.Workbook
    Dim ws As Excel.Worksheet

    Set myXL = New Excel.Application
    Set myXLS = myXL.Workbooks.Open("K:\Jackson\Proposal Summary Master.xlsm")
    myXLS.Application.DisplayAlerts = False
    Set ws = myXLS.Sheets(1)
    ws.Visible = xlSheetVeryHidden

    myXLS.Sheets("VLOOKUP").Range("J1").Value = "EPL"
    myXLS.Application.Run ("BABox_Change")

    myXLS.Application.DisplayAlerts = True
    myXLS.Close(true) ' Change to false if you don't want to save Changes


    Set myXLS = Nothing
    Set myXL = Nothing
    Set ws = Nothing
End Sub



回答2:


Brilliant. that worked for me as well. I just adapted the portion

   myXLS.Sheets("VLOOKUP").Range("J1").Value = "EPL"
        myXLS.Application.Run ("BABox_Change")

to my files



来源:https://stackoverflow.com/questions/18244653/getting-cannot-run-the-macro-error-in-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!