Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
809 views
in Technique[技术] by (71.8m points)

excel - Creating a self install macro?

Hello I create many macros for my co workers. The current method I have for distributing to another computer is going into the vba editor and importing.

I would really like to make a kind of "installer" for macros that would allow the user to install a new macro without having to go into the editor. I'm not sure this is even possible but any ideas are welcome!

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to enable Microsoft Scripting Runtime library under references. (VBE -> Tools -> References. Check the box.)

Basically, you create a string that holds the code of the macro you want to install. Obviously, the string could be really long with many lines of code so you might need several string variables.

Dim toF As Workbook
Dim codeMod As CodeModule
Dim code As String
Dim fso As Scripting.FileSystemObject
Dim folder As folder
Dim name As String, file As String

Application.ScreenUpdating = False

Set fso = New FileSystemObject
Set folder = fso.GetFolder("C:folderhere")
name = nameOfFileHere
file = folder & "" & name

Set toF = Workbooks.Open(file)
'modify ThisWorkbook  to place it elsewhere
Set codeMod = toF.VBProject.VBComponents("ThisWorkbook").CodeModule

'erase everything if code already exists
If codeMod.CountOfLines > 0 Then
    codeMod.DeleteLines 1, codeMod.CountOfLines
End If

'dump in new code
code = _
"Private Sub Workbook_Open()" & vbNewLine & _
"   Dim user as String" & vbNewLine & _
"   Dim target as String" & vbNewLine & _
"   user = Application.UserName" & vbNewLine & _
"   target = """ & findUser & """" & vbNewLine & _
"   If user = target then" & vbNewLine & _
"   MsgBox ""I just dumped in some code.""" & vbNewLine & _
"   End if" & vbNewLine & _
"End Sub" & vbNewLine

With codeMod
    .InsertLines .CountOfLines + 1, code
End With

Application.ScreenUpdating = True

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...