我有一些导入模块的代码,但是这样做会在名称末尾添加一个数字。有没有办法从导入时的名称中删除数字?
Sub ImportModules()
Dim wkbTarget As Excel.Workbook
Dim objFSO As Scripting.FileSystemObject
Dim objFile As Scripting.File
Dim szTargetWorkbook As String
Dim szImportPath As String
Dim cmpComponents As VBIDE.VBComponents
Dim SpecialPath As String
oneback = Left(ThisWorkbook.path, InStrRev(ThisWorkbook.path, "\") - 1)
SpecialPath = oneback & "\" & Range("PathToModule")
'^ Path where the code modules are located.
'Get the path to the folder with modules
If SpecialPath = "Error" Then
MsgBox "Import Folder not exist"
Exit Sub
End If
''' NOTE: This workbook must be open in Excel.
szTargetWorkbook = ActiveWorkbook.Name
Set wkbTarget = Application.Workbooks(szTargetWorkbook)
Set objFSO = New Scripting.FileSystemObject
If objFSO.GetFolder(SpecialPath).Files.Count = 0 Then
MsgBox "There are no files to import"
Exit Sub
End If
Set cmpComponents = wkbTarget.VBProject.VBComponents
Dim cell As Range
Dim rng
Set rng = Range("ModuleName")
For Each objFile In objFSO.GetFolder(SpecialPath).Files
For Each cell In rng
'If objFile.Name Like "*Import*" Then GoTo skipImport ' Skips the Import Module
If objFSO.GetExtensionName(objFile.Name) = "bas" And _
objFile.Name = cell And _
objFile.DateLastModified > cell.Offset(0, 1) Then
Debug.Print cell
Dim CurrentModuleName
CurrentModuleName = Left(objFile.Name, (InStrRev(objFile.Name, ".", -1, vbTextCompare) - 1))
'^ Gets the file name of the module being imported and removes the extension
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Set VBProj = ActiveWorkbook.VBProject
Set VBComp = VBProj.VBComponents(CurrentModuleName)
VBProj.VBComponents.Remove VBComp
'^ Removes the module that is to be replaced
cell.Offset(0, 1) = Format(Date, "dd/mm/yyyy") & " " & Format(Time, "hh.nn.ss")
'^ Keep time as without, it will import the same module throughout the day when opened.
cmpComponents.Import objFile.path
End If
Next cell
Next objFile
End Sub
到达cmpComponents.Import部分时,它将复制模块,然后在代码完成时复制。它将模块末尾的编号留在模块上,删除已替换的模块