Excel应用程序不从MS-Project VBAclosures

下面的子不closuresExcel应用程序。 它仍然在任务pipe理器中。 这有点奇怪,因为我使用相同的方法来打开和closures其他模块中的工作簿,它的工作原理。 此代码在MS-Project中。

Sub updateModules() 'TESTE INICIAL PARA SABER SE AS INFORMAÇÕES BÁSICAS ESTÃO INSERIDAS If sanity_test = 0 Then Exit Sub End If '--------------------------------//-------------------------------- Dim xlapp As Object Dim xlbook As Object Dim sHostName As String ' Get Host Name / Get Computer Name sHostName = Environ$("username") Set xlapp = CreateObject("Excel.Application") 'xlapp.Visible = True Set xlbook = xlapp.Workbooks.Open(modulesVBA_loc) 'ENCONTRAR CÓDIGO NA TABELA DO FICHEIRO MASTER Dim rng_modules As Range Dim rng_usernames As Range Dim username As Range Dim atualizado As Range Dim lastcol As Long With xlbook.Worksheets(1) 'Última coluna lastcol = .Cells(2, .Columns.Count).End(xlToLeft).Column lastcol_letter = Functions_mod.GetColumnLetter(lastcol) End With 'Range com os usernames Set rng_usernames = xlbook.Worksheets(1).Range("E2:" & lastcol_letter & "2") 'Encontra o username correto Set username = rng_usernames.Find(sHostName) Set rng_modules = xlbook.Worksheets(1).Range("A3") 'Primeiro módulo Do While rng_modules.Value <> Empty linha = rng_modules.Row Set atualizado = username.Offset(linha - 2) If atualizado.Value = "Not Updated" Then With ThisProject.VBProject .VBComponents.Remove .VBComponents("CoreTeam_mod") .VBComponents.Import supportDoc_loc & "Project\Próxima Actualização - Apenas PP pode modificar\VBA\Modules\CoreTeam_mod.bas" End With atualizado.Value = "Updated" End If Set rng_modules = rng_modules.Offset(1) Loop xlbook.Saved = True xlbook.Close End Sub 

编辑 :似乎错误来自获取列字母的函数。 我用字母“G”replace了lastcol_letter,代码运行良好,并正确closures了Excel应用程序。 我应该怎样写这个函数呢?

 Function GetColumnLetter(colNum As Long) As String Dim vArr vArr = Split(Cells(1, colNum).Address(True, False), "$") GetColumnLetter = vArr(0) End Function 

打开excel应用程序,你可以使用这样的代码:


 Dim xlapp as Excel.application Set xlapp = GetObject("", "Excel.Application") ' your other code goes here xlapp.quit End sub 

编写Application.Quit在应该closures实例的最后。

您的函数GetColumnLetter (在MS Project中)使用Excel Cells对象,而不引用父对象(例如工作表对象)。 当代码在Excel中本地运行时,Excel将隐式使用活动工作表。 但是,MS Project不会使用不合格的Excel引用来执行此操作。

获取Range对象所需的一种更好的方法是这样做:

 Dim rng_usernames As Range Dim lastcell As Range With xlbook.Worksheets(1) 'Última coluna Set lastcell = .Cells(2, .Columns.Count).End(xlToLeft) 'Range com os usernames Set rng_usernames = .Range("E2", lastcell) End With End Sub 

如果在macros完成后Excel仍在运行,请在macros的末尾显式closures并将Excel对象设置为Nothing。

 ' close out xlbook.Close SaveChanges:=True xlapp.Quit Set xlbook = Nothing Set xlapp = Nothing 

注意:“ 工作簿已保存”属性指示文件是否已保存。 将其设置为True意味着在closures文件时不会提示您保存更改,并且不会保存更改。 您的代码会对出现您实际想要保存的文件进行更改。 考虑使用Workbook Close方法的SaveChanges参数来显式保存更改。