PDA

View Full Version : Solved: How do you name an imported module via code?



nitt1995
06-19-2006, 12:54 PM
My VBA project imports in *.bas files into a workbook and I need a way to check to see that functions with the same name don't already exist. I plan to name the modules when they are imported (preferably to the same file name), and just search for the same module name. I will then give the user the choice to replace the file.

I have not yet found out how to name an imported module. It always takes the next in the sequence Module1, Module2..... ModuleX.

I have figured out this code to search for all components, including modules. I don't know how the module1 is selected without knowing what the name is?

Therefore, I don't know how to name the module, without already knowing its current name. (how do you name it during creation?).

Is there a way to "pick-off" the modules from the worksheets, class modules, etc?

Thanks!


Private Function listComponents()
Dim ref As Object
Dim msg As String
msg = ""
For Each ref In ActiveWorkbook.VBProject.VBComponents
msg = msg & ref.Name & vbCrLf
If (ref.Name = "Module1") Then
'Renames module, once selected.
ref.Name = "Module2"
End If
Next ref
MsgBox msg
'deletes module that you know the name
With ActiveWorkbook.VBProject.VBComponents
.Remove ActiveWorkbook.VBProject.VBComponents("why")
End With
End Function

While on the same subject, is there a way to isolate all of the functions listed on a given module? Can I do a similar listFunction sub to list all of the subs and functions on a given module?

malik641
06-19-2006, 05:58 PM
Therefore, I don't know how to name the module, without already knowing its current name. (how do you name it during creation?).
If you import it during runtime you could just set it to an object and rename it after setting it to the object.

Option Explicit

Sub Test()
On Error GoTo This

Dim objModule As Object
Set objModule = ThisWorkbook.VBProject.VBComponents.Import("C:\Sort_Sheets.bas")

objModule.Name = "ThisName"

Set objModule = Nothing
Exit Sub

This:
Debug.Print Err.Number
Set objModule = Nothing
End Sub

The reason for the error checking is because if you try to rename it to "ThisName" again, you get an application-defined or object-defined error.

nitt1995
06-20-2006, 07:59 AM
Thanks! It works great.

lucas
06-20-2006, 08:00 AM
Please be sure to mark your thread solved.

malik641
06-20-2006, 12:32 PM
:thumb Glad to help. And yes, please mark the thread solved if it is so. Thanks.