vbams-project

how to close an excel workbook from ms project? (VBA)


I'm trying to create a little macro on MS project. it would simply close a workbook already open in excel. ideally, I would like to close one specific excel workbook, but I'd be satisfied even just being able to close excel from MS project.

it's pretty easy to find how to close a workbook I created/opened in my MS project macro, but I can't find a way to close an open workbook which was not created within my macro.

Help will be much appreciated. 🙂

I've tried to activate the workbook from MS project by opening it again, but vba says it can't open it because it's already open.

I've also tried to use Application.SendKeys ("%{TAB}") but ms project vba returns an error 438 "object doesn't support this method"


Solution

  • so, using the proposal of @Rachel Hettinger, I managed to finalize a function to close one specific excel workbook from MS project.

    important : this works for MS project, but I'm not sure it would for any other office applications. (definitely not on excel, on which it would be way simpler)

    Function CloseWorkbook(WorkbookToClose As String)
    
        'the name of the file you want to close (the variable WorkbookToClose above)
        'must contain the name of the file and the extension
        Dim xlapp As Object
        On Error GoTo Error_handler
    
        Set xlapp = GetObject(, "Excel.Application")
    
        Dim wb As Object
        For Each wb In xlapp.Workbooks
            If wb.Name = WorkbookToClose Then
                wb.Close False
            End If
        Next wb
    
    Error_handler:
    
    End Function