Calling an External VBA from VBScript - vba

I am using a program called mathtype to pull some equation objects out of a word document. I've written code in VBA that works perfectly using their API, but I have to translate it to a VBScript file. I have looked all over google, but have not found any solution on how (If it is even possible) to call a VBA library from VBScript.
VBScript can't see the MathTypeSDK Objects/Functions.
If not possible, how would I encase the macro I need to run in a globally available word file and call it from the VBScript?
Edit: Got it! Unfortunately the approaches below, while helpful, did not work for my situation. I found something closer: Embedding the macro in a global file and calling it through the Word Objects Run command.
objWord.Run "Normal.NewMacros.RunMain"

Here is an approach which might work for you. I tested this simple example.
Class "clsTest" in file "Tester.docm":
Public Sub Hello()
MsgBox "Hello"
End Sub
Class "Instancing" is marked "PublicNotCreatable".
Module in "Tester.docm":
Public Function GetClass() As clsTest
Set GetClass = New clsTest
End Function
In your vbscript:
Dim fPath, fName
fPath = "C:\Documents and Settings\twilliams\Desktop\"
fName = "Tester.docm"
Dim wdApp, o
Set wdApp = CreateObject("word.application")
wdApp.visible=true
wdapp.documents.open fPath & fName
Set o = wdApp.Run("GetClass")
o.Hello
Set o=nothing
Again - I only tested this simple example: you'll have to adapt it to your situation and try it out.

Word-VBA was not made to create reusable libraries, I suppose (for usage in external programs).
One way to reuse existing Word-VBA code is, however, run Word via WScript.Shell.Run using the /m<macroname> command line switch (see http://support.microsoft.com/kb/210565/en-us for details). This, has the restriction that evertime you need to call a specific macro, a Word process is started again, running that macro, and ends afterwards. Means, if you need just one call to your Word.VBA for a specfific task, this may be ok, but if you need a lot of interprocess communication between your VBScript and your VBA macro, you should look for a different solution.

Related

Import source from txt or bas file

I want to store source code of VBA macro in .bas or .txt file and run it when user runs macro. I have macro that is used by multiple people, and I would like to store file on server to prevent them to use older versions of same macro. I found following line in stackoverflow and placed it in module code that should import code
'Library should be turned on Microsoft Visual Basic for Applications Extensibility 5.3
Option Explicit
Sub main()
Dim VBPrj As VBIDE.VBProject
Dim VBCom As VBIDE.VBComponent
Set VBPrj = Application.VBE.ActiveVBProject
Set VBCom = VBPrj.VBComponents("Module1")
VBCom.CodeModule.AddFromFile ("C:\Users\lietu\OneDrive\Documents\tests\Module1.txt")
End Sub
then I created txt file with following code in right location
Attribute VB_Name = "Module1"
Sub main()
MsgBox "Hello World"
End Sub
What I'm doing wrong?
It is not possible to execute code in a text file as a VBA "macro". The programming language/environment/interface simply does not work that way - no ifs, ands or buts - no workarounds.
The content of a text or bas file must be imported into a VBA project, using code similar to what's in the question.
In order to be able to use the VB Extensibility libraries that this code depends on, a specific security setting in the host Office application must be disabled, making this kind of approach unreliable, at best. The setting cannot be disabled using code, for understandable reasons.
Indeed, the approach proposed in the question would be a massive security risk...

Is there any benefit to opening a file in VBA using a Sub vs using FollowHyperlink

So a little background - I have been using VBA for a few months now to write a program to speed up some of the work I do. This involves opening files, and at the moment I have been opening files with Autocad using the following sub:
Sub OpenAutocadFile(AutocadFile)
If AutocadVariable Is Nothing Then
Set AutocadVariable = CreateObject("AutoCAD.Application")
If AutocadVariable Is Nothing Then
MsgBox "Could not start Autocad"
Exit Sub
End If
Else
Set AutocadVariable = GetObject(, "AutoCAD.Application")
End If
Set AutocadApp = AutocadVariable
AutocadApp.Visible = True
AutocadApp.Documents.Open (AutocadFile)
End sub
Not perfect I know, but it works the majority of the time.
I also have been opening PDF files using:
ActiveWorkbook.FollowHyperlink(PDFFile)
Now my question is, is there any advantage to using one method or the other for opening a file in VBA?
I already know that with the dedicated sub, you can specify what program you want to use whereas with the hyperlink method it uses the default one.
So other than that am I missing something? Does one run faster than the other? Is one method preferable for certain file types whereas the other is for other file types?
The difference is functional, as they do different things to get similar results.
The CreateObject method uses an explicit application to open the reference, while FollowHyperlink uses the default application registered for that protocol, and passes the reference to that.
Which one is preferable is up to the developer, as sometimes you want user expected behaviour ("Open a PDF in my fave PDF viewer") and other times you may not want this. For example, maybe you know that the "open with" handler for this system doesn't do what you or the user wants.
Whether one is faster than the other isn't actually that important, as they are intended for different use cases.

Writing VBA procedure/function to an .xlam addin

I have created a VBA project in Excel and within said project is a module that writes code to another module. I eventually password protected the project so as to keep the code hidden (not realizing right away that this would pose some pretty obvious issues).
When the user interacts with the file, the module attempts to run the code but, encounters an error (a password protected project can't modify itself! Hey we all have our duh moments :p).
So, as a way around this, I figured 'why not make the portion that is edited unprotected', whilst keeping the remainder of the file locked. So I figured I would create an unprotected .xlam add-in, then write said code to this portion. I am having some difficulty figuring how to do this though however. Below is the code I have written that writes code to another module:
Public Sub errorWrite()
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Dim s As String
Dim d As String
Dim lineNumb As Long
With ThisWorkbook.VBProject.VBComponents.item("NewModule")
.CodeModule.InsertLines j, "Public sub newModule()"
j = j + 1
With ThisWorkbook.VBProject.VBComponents.item("NewModule")
.CodeModule.InsertLines j, "(my code etc..)"
j = j + 1
With ThisWorkbook.VBProject.VBComponents.item("NewModule")
.CodeModule.InsertLines j, "end sub"
end sub
While I have found some info on Stack and elsewhere regarding .xlam add-ins (Updating an xlam add-in using VBA) for example, I'd rather just keep it as simple as possible. Suggestions and hints are much appreciated. Thanks!
Using an unprotected Addin seems like a reasonable approach. But the code you have posted writes to another Module within the Protected addin. You need to reference the other AddIn as a VBProject
Change the name of your Unprotected AddIn to a unique Name (it defaults to VBAProject and does not have to be unique)
Then create a reference to it like this
Dim VBP As VBProject
Set VBP = ThisWorkbook.VBProject.VBE.VBProjects("NameOfYourUnprotectedAddin")
Then all your code uses this reference instead of ThisWorkbook.VBProject
Eg
With VBP.VBComponents.item("NewModule")
.CodeModule.InsertLines j, "Public sub newModule()"
' etc
End With
so I was able to find a way that seems to work, I wrote the code using FSO, then save the file as a .bas module. From there I used the below to have the module imported directly into the .xlam addin as a module:
Public Sub importBas()
Dim VBP As VBProject
Set VBP = Workbooks("example.xlam").VBProject
VBP.VBComponents.Import ("C:\Users\...example.bas")
VBP.VBComponents.Remove
End Sub
Then, in the original module, I deleted procedure within the xlam after execution was finished. Therefore no code can be seen (assuming I remember to use error-handling and disable break mode :p)
I am still curious how to write it 'directly', so I will play around with it more and see if I get it, although this way works
Thank you :)

How to access a Word public variable in Excel VBA

I'm trying to automate some report generation where Excel VBA is doing all the work. My employer has a standardized set of templates of which all documents are supposed to be generated from. I need to populate one of these templates from Excel VBA. The Word templates utilize VBA extensively.
This is (some of) my Excel VBA code:
Sub GenerateReport() ' (Tables, InputDataObj)
' code generating the WordApp object (works!)
WordApp.Documents.Add Template:="Brev.dot"
' Getting user information from Utilities.Userinfo macro in Document
Call WordApp.Run("Autoexec") ' generating a public variable
Call WordApp.Run("Utilities.UserInfo")
' more code
End sub
In the Word VBA Autoexec module, a public variable named user is defined and declared. The Userinfo sub from the Utilities module populates user. Both these routines are run without any complaints from VBA. I would then like to be able to access the user variable in my Excel VBA, but I get the following error
Compile Error: Variable not yet created in this context.
How can I access the Word VBA variable in Excel VBA? I thought it more or less was the same?
EDIT: the user variable is a user defined Type with only String attributes. Copying the Word VBA functions that populate the user variable is absolutely doable, just more work than I though was necessary...
In a Word module:
Public Function GetUserVariable() As String '// or whatever data type
GetUserVariable = user
End Function
In an Excel module:
myUser = WordApp.Run("GetUserVariable")
Alternatively, you could be able to replicate the variables value - as it's called user I suspect it is returning some information about a user, or author, of a document. In which case one of the following might be what you're after:
'// Username assigned to the application
MsgBox WordApp.UserName
'// Username defined by the system
MsgBox Environ$("USERNAME")
'// Name of the author of the file specified
MsgBox CreateObject("Shell.Application").Namespace("C:\Users\Documents").GetDetailsOf("MyDocument.doc", 9)
Another option - if you could only add a line of code to the Utilities.UserInfo sub (after setting your public variable):
ActiveDocument.Variables("var_user") = user
Then you could access it easily afterwards in Excel:
Sub GenerateReport() ' (Tables, InputDataObj)
' code generating the WordApp object (works!)
'I am assuming your WordApp object is public, as you don't declare it.
'Capture the new document object
Dim newdoc as Object
set newdoc = WordApp.Documents.Add(Template:="Brev.dot")
' Getting user information from Utilities.Userinfo macro in Document
Call WordApp.Run("Autoexec") ' generating a public variable
Call WordApp.Run("Utilities.UserInfo")
'Get and show the value of "user"
Dim user as String
user = newdoc.Variables("var_user")
msgbox, user
End Sub
This is assuming that useris a string.
EDIT: As it is a requirement to work only on the Excel VBA, I would definely try the approach suggested by Scott and MacroMan - replicating the same functionality of the Word macros in Excel - if possible.
I assume that you've already ruled out the possibility of using an edited copy of the original template, set in a public folder...
For the sake of completness, there is another possibility: actually it is possible to inject VBA code in a Word document without the VBProject Object Model, by "brute force". If you rename a Word document as a .zip file and open it, you will notice a \word\vbaProject.bin file in it. This file contains the VBA project for the document and, in principle, one could add or change VBA code by modifying or replacing it.
I did some tests transplanting code from one document to another by simply copying the vbaProject.bin file, and the concept works. If you are interested in learning more about this file, this topic could be of use.
Notice, however, that to do what you want with such a technique would be somewhat complex (it would involve, for starters, updating zip files from your Excel VBA), and would require a lot of experimentation to mitigate the risk of accidentally corrupting your files. Definetly not recommended if you are looking for an easy and simple solution - but it is possible.

How do I programatically add a reference to a VBA project?

I'm deploying an early bound styled VBA module that needs Scripting.Dictionary and RegExp.
The script, predictably, fails when it runs on another computer.
The user has to go to Tools->Reference in the VBA IDE and add a reference to those two libraries manually to make it work.
Hence lies the problem. Asking the non-technical end user to go to the IDE and manually add references is asking way too much of them.
The other alternative is to rewrite the whole (very long script written by someone else) to use late binding. I rather not take this path if there are other methods.
As an altervative, some people suggest adding a reference programatically like so:
Application.VBE.ActiveVBProject.References.AddFromFile [Path to library]
Is this the correct solution and if so are there any downsides of this strategy?
If not, are there other methods that will to enable the code to remain early bound yet does not require references to be added manually by the user.
Suggestions involving direct calls to the Win32/64 API are also welcome.
Thanks.
In my own limited environment (small # of other people using spreadsheets I develop, relatively standard machine setups), if I create the file and add the references, and then give a copy to someone else, they can open it with no problems and not have to do anything, so keep that in mind with this answer. (I'm wondering why that doesn't work for you.) Also, this was with Excel.
Rather than adding a reference from a file path, you might consider using the GUID property instead.
Here is some code I once used to automatically create references in a newly created workbook. (It's part of a script that would export code, references, and unit tests on worksheets to text for use with Subversion and then later reconstitute the workbook from the text files.) You might find it useful to your situation. (EH and cleanup removed to keep it short...)
'Export refs in existing workbook to text file
Private Sub exportRefs_(srcWbk As Workbook)
Dim fs As FileSystemObject
Set fs = New FileSystemObject
Dim tsout As TextStream
Set tsout = fs.CreateTextFile(fs.BuildPath(getTargetPath_(srcWbk), "refs.refs"))
Dim ref As Reference
For Each ref In Application.ThisWorkbook.VBProject.References
Call tsout.WriteLine(ref.GUID)
Next ref
'<EH + cleanup...>
End Sub
'Add refs to newly created workbook based on previously exported text file
Private Sub importRefs_(wbk As Workbook, path As String)
Dim fs As FileSystemObject
Set fs = New FileSystemObject
Dim tsin As TextStream
Set tsin = fs.OpenTextFile(path)
Dim line As String
Dim ref As Reference
While Not tsin.AtEndOfStream
line = tsin.ReadLine()
Set ref = Nothing
On Error Resume Next
Set ref = wbk.VBProject.References.AddFromGuid(line, 0, 0)
On Error GoTo 0
If ref Is Nothing Then
Debug.Print "add failed: " & line
End If
Wend
'<EH + cleanup...>
End Sub
Like, I said, limited environment, but hopefully it helps.