Skip to content

Instantly share code, notes, and snippets.

@pamolloy
Last active December 31, 2015 03:49
Show Gist options
  • Save pamolloy/7929843 to your computer and use it in GitHub Desktop.
Save pamolloy/7929843 to your computer and use it in GitHub Desktop.
Using VBScript function procedures open a text file and also modify one cell in an Excel worksheet
' Introduction to Scripting Microsoft Office - http://technet.microsoft.com/en-us/library/ee176994.aspx
strExcelFilename = "C:\Users\Philip\Desktop\report_template.xls"
strPLNFilename = "C:\Users\Philip\Desktop\sample.pln"
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const row = 13, col = 1, text = "Test"
Function OpenFileRead(FileName)
Set objFileSystemObject = CreateObject("Scripting.FileSystemObject")
If objFileSystemObject.FileExists(FileName) Then ' Check if the file exists
Set objFile = objFileSystemObject.OpenTextFile(FileName, ForReading)
Set OpenFileRead = objFile
Else
WScript.Echo "File not found"
End If
End Function
Function StartExcel()
Set objExcel = CreateObject("Excel.Application") ' Create an instance of Excel
objExcel.DisplayAlerts = False ' Supress alerts (e.g. Prompt to save)
objExcel.Visible = False ' Make instance not visible
Set StartExcel = objExcel
End Function
Function QuitExcel(objExcel, objWorkBook)
objWorkbook.SaveAs(strExcelFilename) ' Write over the template
objExcel.Quit ' Close the instance
End Function
Function Main()
Set objFile = OpenFileRead(strPLNFilename)
Set objExcel = StartExcel()
Set objWorkbook = objExcel.Workbooks.Open(strExcelFilename) ' Open the template
Set objWorksheet = objWorkbook.Worksheets(2) ' Open the second sheet
objWorksheet.Cells(row, col) = text ' Add value to row and column
Call QuitExcel(objExcel, objWorkBook)
End Function
Main() ' Run the script
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment