Hello,
I am trying to get VBA to import a folder of .bas files into the PERSONAL.xlsb workbook upon Excel startup to ensure that users always have the most updated macros. Two lines of mine are throwing Runtime Error 9, and after playing around a bit I think it's either because I'm using Dir or there's something wrong with this line: *If IsNull(TargetWB.VBProject.VBComponents(fileNameNoExt)) = True Then Is Nothing Then*, but I'm not sure it that's what's wrong or how to fix it. (When I substitute an existing module name in quotes (no extension) for fileNameNoExt, there is no error in the AutoUpdateBasFiles sub, only in the DeleteVBComponent Sub. When I substitute a non-existent module name in quotes (no extension) for fileNameNoExt, it throws Runtime Error 9 again.) I am a novice with VBA. Any help or ideas would be appreciated.
Moderator's note: Please take the time to review our rules. There aren't many, and they are all important. Rule #2 requires code tags. I have added them for you this time because you are a new member. --6StringJazzer
Sub DeleteVBComponent(ByVal wb As Workbook, ByVal CompName As String)
'Delete the component
wb.VBProject.VBComponents.Remove wb.VBProject.VBComponents(CompName) '***THIS LINE THROWS RUNTIME ERROR 9***
End Sub
Sub AutoUpdateBasFiles()
'Automate import of all other modules
Dim userID As String
userID = Environ("UserName")
Dim destPath As String
destPath = "C:\Users" & userID & "\AppData\Roaming\Microsoft\Excel\XLSTART"
Dim sourcePath As String
sourcePath = "C:\File Path" '**FilePath removed for the purpose of this post
'Loop through all files in a folder
Dim fileName As Variant
fileName = Dir(sourcePath)
Dim TargetWB As Workbook
Set TargetWB = Workbooks("PERSONAL.xlsb")
Dim fileNameNoExt As String
While IsNull(fileName) = False
fileNameNoExt = Left(fileName, InStrRev(fileName, ".") - 1)
If IsNull(TargetWB.VBProject.VBComponents(fileNameNoExt)) = True Then 'Check for existence of module '***THIS LINE THROWS RUNTIME ERROR 9***
Else
Call DeleteVBComponent(Workbooks("PERSONAL.xlsb"), fileNameNoExt) 'Delete existing module before importing the new one of the same name
End If
TargetWB.VBProject.VBComponents.Import (sourcePath & fileName) 'Import the new module
'Set the fileName to the next file
fileName = Dir()
Wend
'Save the workbook
Workbooks("PERSONAL.xlsb").Save
End Sub
Private Sub Auto_Open()
Call AutoUpdateBasFiles
End Sub
Bookmarks