【发布时间】:2018-10-28 03:14:58
【问题描述】:
下面的代码替换了目标工作簿中的模块。
代码在当前目录的 Updates 子文件夹中搜索 .bas 文件,找到后删除旧版本,然后导入代码。
有时,一个或多个被替换的模块采用名称 xxxxx1,其中 xxxxx 是 .bas 文件的名称。它在模块名称后面加上“1”。没有其他同名模块。我检查了 .bas 文件,第一行正确定义了 VB_Name - Attribute VB_Name = "xxxxx"。删除工作。 Import 有时会导致问题。
我在 Remove 之后添加了一个 Application.Wait,但问题仍然存在。
请注意,例程使用其他函数来确定目录路径并查找文件。调试证明它们是有效的。
Dim iFilesNum As Integer
Dim iCount As Integer
Dim recMyFiles() As FoundFileInfo
Dim blFilesFound As Boolean
Dim directoryPath As String
Dim wbTarget As Workbook
Dim vbMod As Object
Dim myFile As String
Dim txtLine As String
Set wbTarget = ActiveWorkbook
directoryPath = getDirectoryPath("Updates")
If Dir(directoryPath, vbDirectory) = "" Then
varX = MsgBox("Updates directory not found. To apply updates you must first " & _
"unload the updates from the file that was emailed to you.", vbOKOnly, "IPM by Merlin")
Exit Sub
End If
blFilesFound = FindFiles(directoryPath, recMyFiles, iFilesNum, "*.bas", False)
If blFilesFound Then
For iCount = 1 To iFilesNum
With recMyFiles(iCount)
.sName = Replace(.sName, ".bas", "")
Set vbMod = Application.VBE.ActiveVBProject.vbComponents 'First we need to remove the existing module
vbMod.Remove VBComponent:=vbMod.Item(.sName)
Application.Wait (Now + #12:00:01 AM#)
wbTarget.VBProject.vbComponents.Import directoryPath & "\" & .sName & ".bas" 'import the new module.
End If
Kill directoryPath & "\" & .sName & ".bas"
End With
Next
Else
varX = MsgBox("No updates files found in the Updates directory.", vbInformation, "IPM by Merlin")
End If
【问题讨论】:
-
我的猜测是包含 VBA 的 Office 文件可能被轻微损坏 - 它保留了已删除的模块的名称,因此在模块名称后附加了 1。
-
感谢 Cindy 的快速回复!作为信息,我正在运行当前版本的 Office 365 Excel 2016。如果 Office 文件 (.xlsm) 有轻微损坏,我该如何纠正这个问题?