Convert VBA to VBS

I really need help here. I have this code in VBA and works like a champ.  But I need it in VBS or any other scripting language so that I can run it as a job. (I prefer VBS or ASP). The code to translate is listed below.  Code listed under the 'cmdGenerateLetters' Subroutine is what needs to run when the script is loaded.  

Private Sub cmdGenerateLetters_Click()
    Dim objWord As Word.Application
    Dim objExcel As Excel.Application
    Dim strBasePath, strSource, strSheet, strSaveAs As String
    strBasePath = "C:\Enrollments\"
    strMainDoc = strBasePath & "Template.doc"
    strSaveAs = "GeneratedFiles\"
    With Application.FileSearch
        .LookIn = strBasePath
        .SearchSubFolders = False
        .MatchTextExactly = False
        .FileName = "*.xls"
        If .Execute(msoSortOrderDescending) <> 1 Then
            MsgBox "Please make sure only 1 (ONE) Excel File is under the '" & strBasePath & "' Directory.", vbExclamation
            Exit Sub
            strSource = .FoundFiles(1)
            Set objExcel = New Excel.Application
            objExcel.Workbooks.Open strSource
            strSheet = objExcel.ActiveWorkbook.Sheets(1).Name & "$"
            Set objExcel = Nothing
        End If
    End With
    strSQL = "SELECT * FROM `'" & strSheet & "'`"
    Set objWord = New Word.Application
    objWord.Documents.Open strMainDoc
    objWord.Visible = False
    With objWord.ActiveDocument.MailMerge
        .OpenDataSource strSource, wdOpenFormatAuto, False, False, True, False, "", "", False, "", "", "Provider=Microsoft.Jet.OLEDB.4.0;Password="""";User ID=Admin;Data Source=" & strSource & ";Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";Jet OLEDB:Regist", strSQL, , , wdMergeSubTypeAccess
        .DataSource.firstrecord = wdDefaultFirstRecord
        .DataSource.lastrecord = wdDefaultLastRecord
        .Destination = wdSendToNewDocument
        .SuppressBlankLines = True
    End With
    objWord.ActiveDocument.SaveAs strBasePath & strSaveAs & Mid(strSheet, 21, 10) & "Letter.doc"
    objWord.ActiveDocument.Close                      'Closes the Merged Document
    objWord.ActiveDocument.Close wdDoNotSaveChanges   'Closes the Main Document
    Set objWord = Nothing
    If Not MoveFile(strSource, strBasePath, strBasePath & "Archive\") Then
        MsgBox "The Excel File was not moved. Please manually move file into 'Archive' directory.", vbExclamation
    End If
    MsgBox "New Letters have been successfully generated!", vbExclamation
End Sub

Function MoveFile(file, sfol, dfol) As Boolean
    Dim fso As Object
    Dim blnFileMoved As Boolean
    Set fso = CreateObject("Scripting.FileSystemObject")
    If Not fso.FileExists(file) Then
        MsgBox file & " does not exist!", vbExclamation, "Source File Missing"
        blnFileMoved = False
        fso.MoveFile (file), dfol
        blnFileMoved = True
    End If
    MoveFile = blnFileMoved
End Function
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Why not creating a VB-App ... ?

I think you can just copy/paste the code in a VB-Project ... compile it and you have an EXE-file that you can use for your job ...

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
tuttiwalaAuthor Commented:
I havent created too many VB apps... will the code just transfer over?

I will try and see if it works.
Some general changes when transporting it to VBS (if the VB-Option won't work ...)

- Always use CreateObject("") to create objects
      Set fso = CreateObject("Scripting.FileSystemObject")
      Set objWord = CreateObject("Word.Application")
- Remove all your datatypes (everything starting with AS), because script-languages don't use datatypes.

I think you don't have to change much ... Just rename your first function and call it in the first line of your VBS, something like this:
Call GenerateLetters

Sub GenerateLetters
End Sub

Function MoveFile(file, sfol, dfol) As Boolean
End Sub

But, to alter your code, I should first do it in VBA (Access) because it can also run VBS-code. It is more easy to handle and debug then in a text-file ...
Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

tuttiwalaAuthor Commented:
i tried it.. and gave me a bunch of errors... starting at the top is:

Type: Word.Application is not defined
Type: Excel.Application is not defined
Name 'Application' is not declared.

and soo on...

any ideas?
tuttiwalaAuthor Commented:
hey.. so i switched thiings to createobject. that seemed to help some...

but... now. most of my errors are with regards to constants... i think i need to include some library files..

Here are the remaining errors that I get. I can't seem to figure out how to include libraries.. (like in access or whatever, you can just make sure u include them in your references or what not... but.. how do i do that here?)

Name 'Application' is not declared
Name 'msoSortOrderDescending' is not declared.
Name 'wdOpenFormatAuto' is not declared.
Name 'wdMergeSubTypeAccess' is not declared.
Name 'wdDefaultFirstRecord' is not declared.
Name 'wdDefaultLastRecord' is not declared.
Name 'wdSendToNewDocument' is not declared.
Name 'wdDoNotSaveChanges' is not declared.
Indeed ... you have to REFERENCE the Word and Excel Library ... just like you did in VBA
Menu: Project -> References...

When you reference this libraries, you also don't have to use the CreateObject, but you can stay using your first code ...
tuttiwalaAuthor Commented:
hmm.. did it.. and your're right. now i can have the 'as word.application' syntax still in there.

but.. it still doesnt see the constants... nor does it like the 'Application.Filesearch' object.

still getting the same errors as above.


What are the references now in your VB-Project ...?

I copied and pasted your code in a new VB-Project and compiled it -> no errors ...

The references in my project are:
- Visual Basic for Applications
- Visual Basic Runtime Objects and Procedures
- Visual Basic Objects and Procedures
- OLE Automation
- Microsoft Excel 10.0 Object Library
- Microsoft Word 10.0 Object Library
tuttiwalaAuthor Commented:
Are you serious?

Got These
- OLE Automation
- Microsoft Excel 10.0 Object Library
- Microsoft Word 10.0 Object Library
- Visual Basic for Applications 6.0

Can't Find These
- Visual Basic Runtime Objects and Procedures
- Visual Basic Objects and Procedures
Using Visual Basic 6.0 (SP5)?

By default, you have
- VB For App
- VB Runttime Obj and Proc
- VB Obj and Proc
- OLE Automation

Strange ... anyways, I will have a look later, so we can maybe just translate it to VBS ...
tuttiwalaAuthor Commented:
i think u might beat me for this one... i am using

we have Visual Studio .Net, so I just plopped the code into the VB .Net Console Application thing.

what should have I done?
Oh, that explains a lot ... :-)

Your VBA-code is almost compatible with VB 6 code.

VB.Net is another story ... VB.Net code is really not compatible any more with the 'old' VB and VBA, because VB.Net is really more object oriënted and stuff like that ... So, to easely convert your code, you must use VB 6, or we have to make a VBS-file ...

Come to you later with the VBS-code, if you want ... or if you have VB 6, try that ...
tuttiwalaAuthor Commented:
i would much rather have the VBS code. appreciate it.
tuttiwalaAuthor Commented:
Hey steegmans! I GOT IT!!!

I just declared those constansts in my code... and played around with the code.. but i got to work in VB.Net! thanks for all the help.

I am gonna give you the points cause you helped out so much. appreciate it. thanks.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Development

From novice to tech pro — start learning today.