Vbscriptexamples
Vbscriptexamples
By Dave Grund
VBScript is a scripting language developed by Microsoft, and modeled after their Visual Basic development language. It is run within a host environment. Windows Scripting Host (WSH) and Internet Explorer (IE) are the two most common hosts, both of which are supplied with Microsoft Windows. VBScript is commonly used to perform quick programming tasks, like reformatting data. It can be used to interface intricately with the Microsoft Office products. Examples to read and update Excel spreadsheets, create Word tables, etc, are included in this document. I learn by example better than any other way. I believe it was Jerry Pournelle who coined one law of documentation: You can never have too many examples. This is a collection of example VBScript files. Most are developed from excerpts of code found in the Public Domain areas on the internet, and are themselves Public Domain. Some of these examples are for demonstration of a feature or technique only, and have little or no true utility value. But most of these examples provide a strong foundation for building a useful tool for your own use. This document contains only examples. It is a live document, and is continuously being updated. For instructional or tutorial information, do a Google search on VBScript xxx, where xxx represents the keyword or subject. The more information you supply with keywords, the closer you will get to finding the information you are looking for.
VBScript Examples
Include Common Code ..................................................................................................................................... 75 Notes ..................................................................................................................................................................... 76 Converting VBA to VBS .................................................................................................................................. 76
VBScript Examples
VBScript Objects
This section illustrates the VBScript Object Model.
VBScript Examples
Excel
A workbook is the actual spreadsheet itself. A worksheet is a sheet of that workbook. objExcel (Set objExcel = CreateObject("Excel.Application") ) .ActiveWindow.FreezePanes = True .Columns(3).AutoFit() .Columns(1).ColumnWidth = 10 .Columns(3).Font.ColorIndex = BLUE .Columns(i).Interior.ColorIndex = num .Rows(i).Interior.ColorIndex = num .visible = true Make Excel visible .workbooks.add Add a new workbook objWorkbook (Set objWorkbook = objExcel.Workbooks.Open(wkbkname) ) objWorkBook (Set objWorkbook = objExcel.Workbooks.Add()) .sheets.count Number of worksheets in the workbook .sheets(i).Name The name of the nth worksheet .Worksheets(wksheetno) objWorkSheet (Set objWorkSheet = objExcel.ActiveWorkbook.Worksheets(Sheet)) .Name = "VBS_Excel_Example" .Cells(row,col).Value = "ColA Hdr" .Range("A1:M1").Font.Bold = True .Range("A1:M1").Font.Size = 14 Set objWorksheet = objWorkbook.Worksheets(1) objRange (Set objRange = objWorksheet.UsedRange) objRange.select Freeze the panes objWorkSheet.Range("A2").Select objExcel.ActiveWindow.FreezePanes = True Cleanup ActiveWorkbook.SaveAs pathname ActiveWorkbook.Close Application.Quit Quit Excel
VBScript Examples
Outlook
Const olFolderCalender = 9 Set objOutlook = CreateObject("Outlook.application") Set objNameSpace = objOutlook.GetNameSpace("MAPI") Set objFolder = objNameSpace.GetDefaultFolder(olFolderCalender) Set MyItems = objFolder.Items MyItems.Subject MyItems.Start MyItems.Duration MyItems.GetRecurrencePattern 3 = weekly, 0 = daily MyItems.BusyStatus MyItems.Sensitivity MyItems.End
VBScript Examples
Word
objWord (Set objWord = CreateObject("Word.Application")) .Visible = True objDoc (Set objDoc = objWord.Documents.Add()) Tables.Add objRange, NUMBER_OF_ROWS, NUMBER_OF_COLUMNS objRange (Set objRange = objDoc.Range()) objTable (Set objTable = objDoc.Tables(1) ' Work with the first (and only) table) For a complete list of the Microsoft Word objects, follow this link: Microsoft Word Objects. Note, however, that some of the links within are broken. For a list of Dialog enumerations, follow this link: Dialog enumerations.
VBScript Examples
VBScript Examples
Set objWorkbook = objExcel.Workbooks.Open(wkbkname) If objWorkbook.sheets.count > 1 then wkSheetno = cInt(inputbox("Enter the worksheet number you wish to work with",WScript.scriptname & " needs some input from you!","1")) else wkSheetNo = 1 end if intLimit = objWorkbook.sheets.count strExtra = "" If intLimit > 10 then intLimit = 10 strExtra = "first ten" end if Msg = "Workbook Name: " & objWorkbook.Name & vbcrlf If wksheetno > objWorkbook.sheets.count then
VBScript Examples
msgbox "You selected worksheet number " & wksheetno & ", and there are only" & objWorkbook.sheets.count ,,"Input Error" wscript.quit end if Set objWorksheet = objWorkbook.Worksheets(wksheetno) ' We already know which rows and columns are DEFINED. Now see which cell is the last to actually ' contain a value. For i = 1 to objWorksheet.UsedRange.Rows.Count OpLine = "" For j = 1 to objWorksheet.UsedRange.Columns.Count OpLine = OpLine & objWorksheet.Cells(i,j).Value If j mod 2 = 0 then OpLine = OpLine & "," next OpLine = left(OpLine,len(OpLine) -1) ' Drop off the last comma objTextFile.writeline(OpLine) next Msg = "Complete!" MsgBox Msg,,WScript.Scriptname objExcel.Application.quit objTextFile.Close Set objWorksheet = nothing Set objWorkbook = nothing Set objExcel = nothing Wscript.quit ' Do not Leave the spreadsheet open
VBScript Examples
Set objRange = objWorksheet.UsedRange objRange.Select Set colCharts = objExcel.Charts colCharts.Add() objWorkBook.sheets(4).Delete ' Sheet3 objWorkBook.sheets(3).Delete ' Sheet2 objWorkBook.sheets(2).Visible = false ' Sheet 1 has the data that is charted objWorkBook.sheets(1).Name = "Exploded Pie Chart" Set objChart = colCharts(1) objChart.Activate objChart.ChartType = EXPLODEDPIECHART objChart.Elevation = 30 objChart.Rotation = 80 objChart.ApplyDataLabels xlDataLabelsShowPercent objChart.PlotArea.Fill.Visible = False objChart.PlotArea.Border.LineStyle = -4142 objChart.SeriesCollection(1).DataLabels.Font.Size = 14 objChart.SeriesCollection(1).DataLabels.Font.ColorIndex = 2 objChart.ChartArea.Fill.ForeColor.SchemeColor = 49 objChart.ChartArea.Fill.BackColor.SchemeColor = 23
VBScript Examples
objChart.ChartArea.Fill.TwoColorGradient 1,1 objChart.ChartTitle.Font.Size = 24 objChart.ChartTitle.Font.ColorIndex = 2 objChart.Legend.Shadow = True
VBScript Examples
Populate a Spreadsheet
This script will populate an Excel spreadsheet, and color the rows and columns. Features: Create a spreadsheet Populate that spreadsheet Delay VBScript processing (sleep).
' Populate a Spreadsheet ' This will demonstrate how to populate a spreadsheet, and to color cells/rows/columns ' Color enums Const Aqua = 42 Const Black = 1 Const Blue = 5 Const BlueGray = 47 Const BrightGreen = 4 Const Brown = 53 Const Cream = 19 Const DarkBlue = 11 Const DarkGreen = 51 Const DarkPurple = 21 Const DarkRed = 9 Const DarkTeal = 49 Const DarkYellow = 12 Const Gold = 44 Const Gray25 = 15 Const Gray40 = 48 Const Gray50 = 16 Const Gray80 = 56 Const Green = 10 Const Indigo = 55 Const Lavender = 39 Const LightBlue = 41 Const LightGreen = 35 Const LightLavender = 24 Const LightOrange = 45 Const LightTurquoise = 20 Const LightYellow = 36 Const Lime = 43 Const NavyBlue = 23 Const OliveGreen = 52 Const Orange = 46 Const PaleBlue = 37 Const Pink = 7 Const Plum = 18 Const PowderBlue = 17 Const Red = 3 Const Rose = 38 Const Salmon = 22 Const SeaGreen = 50 Const SkyBlue = 33 Const TanColor = 40 Const Teal = 14 Const Turquoise = 8 Const Violet = 13 Const White = 2
' Identical to 32
' Identical to 34
VBScript Examples
Const Yellow = 6 Const NUMROWS = 29 Const NUMCOLS = 13 Set objExcel = CreateObject("Excel.Application") ' Bind to the Excel object objExcel.Visible = True objExcel.Workbooks.Add ' Create a new workbook. Sheet = 1 ' Select the first sheet Set objSheet = objExcel.ActiveWorkbook.Worksheets(Sheet) ' Bind to worksheet. objSheet.Name = "VBS_Excel_Example" ' Name the worksheet strExcelPath = "U:\data\VBScript\Vbs_Excel_Example.xls" Randomize '-------------* 'Populate the worksheet with data '-------------* 'Add some titles to row 1 objSheet.Cells(1, 1).Value = "ColA Hdr" objSheet.Cells(1, 2).Value = "ColB Hdr" objSheet.Cells(1, 3).Value = "ColC Hdr" objSheet.Cells(1, 4).Value = "ColD Hdr" objSheet.Cells(1, 5).Value = "ColE Hdr" objSheet.Cells(1, 6).Value = "ColF Hdr" objSheet.Cells(1, 7).Value = "ColG Hdr" objSheet.Cells(1, 8).Value = "ColH Hdr" objSheet.Cells(1, 9).Value = "ColI Hdr" objSheet.Cells(1, 10).Value = "ColJ Hdr" objSheet.Cells(1, 11).Value = "ColK Hdr" objSheet.Cells(1, 12).Value = "ColL Hdr" objSheet.Cells(1, 13).Value = "ColM Hdr" ' Set the save location ' Identical to 27
' ' ' ' ' ' ' ' ' ' ' ' '
Row Row Row Row Row Row Row Row Row Row Row Row Row
1 1 1 1 1 1 1 1 1 1 1 1 1
Column Column Column Column Column Column Column Column Column Column Column Column Column
1 (A) 2 (B) 3 (C) 4 (D) 5 (E) 6 (F) 7 (G) 8 (H) 9 (I) 10 (J) 11 (K) 12 (L) 13 (M)
'Add some data using a loop For row = 2 to NUMROWS objSheet.Cells(row, 1).Value = "Row " & row & " Col A" objSheet.Cells(row, 2).Value = "Row " & row & " Col B" objSheet.Cells(row, 3).Value = "Row " & row & " Col C" objSheet.Cells(row, 4).Value = "Row " & row & " Col D" objSheet.Cells(row, 5).Value = "Row " & row & " Col E" objSheet.Cells(row, 6).Value = "Row " & row & " Col F" objSheet.Cells(row, 7).Value = "Row " & row & " Col G" objSheet.Cells(row, 8).Value = "Row " & row & " Col H" objSheet.Cells(row, 9).Value = "Row " & row & " Col I" objSheet.Cells(row, 10).Value = "Row " & row & " Col J" objSheet.Cells(row, 11).Value = "Row " & row & " Col K" objSheet.Cells(row, 12).Value = "Row " & row & " Col L" objSheet.Cells(row, 13).Value = "Row " & row & " Col M" Next '-------------* ' Format the spreadsheet '-------------* 'Put the first row in bold, font size 14 objSheet.Range("A1:M1").Font.Bold = True objSheet.Range("A1:M1").Font.Size = 14 'Freeze the panes objSheet.Range("A2").Select objExcel.ActiveWindow.FreezePanes = True 'Change column A and B to use a fixed width objExcel.Columns(1).ColumnWidth = 10
VBScript Examples
objExcel.Columns(2).ColumnWidth = 10 objExcel.Columns(3).ColumnWidth = 10 objExcel.Columns(4).ColumnWidth = 10 objExcel.Columns(5).ColumnWidth = 10 objExcel.Columns(6).ColumnWidth = 10 objExcel.Columns(7).ColumnWidth = 10 objExcel.Columns(8).ColumnWidth = 10 objExcel.Columns(9).ColumnWidth = 10 objExcel.Columns(10).ColumnWidth = 10 objExcel.Columns(11).ColumnWidth = 10 objExcel.Columns(12).ColumnWidth = 10 objExcel.Columns(13).ColumnWidth = 10 'Change columns to autofit objExcel.Columns(3).AutoFit() objExcel.Columns(6).AutoFit() 'Change the background color of columns intNext = RN For i = 1 to NUMCOLS intNext = RN objExcel.Columns(i).Interior.ColorIndex = intNext wscript.sleep(400) Next 'Change the background color of rows For i = 1 to NUMROWS intNext = RN objExcel.Rows(i).Interior.ColorIndex = intNext wscript.sleep(300) Next 'Change the font color of column C objExcel.Columns(3).Font.ColorIndex = BLUE ' Now do some specific colorization objSheet.Cells(1,1).Interior.ColorIndex = wscript.sleep(300) objSheet.Cells(2,2).Interior.ColorIndex = wscript.sleep(300) objSheet.Cells(3,3).Interior.ColorIndex = wscript.sleep(300) objSheet.Cells(4,4).Interior.ColorIndex = wscript.sleep(300) objSheet.Cells(5,5).Interior.ColorIndex = wscript.sleep(300) objSheet.Cells(6,6).Interior.ColorIndex = wscript.sleep(300) objSheet.Cells(7,7).Interior.ColorIndex = wscript.sleep(300) objSheet.Cells(8,8).Interior.ColorIndex = wscript.sleep(300) objSheet.Cells(9,9).Interior.ColorIndex = wscript.sleep(300) objSheet.Cells(10,10).Interior.ColorIndex wscript.sleep(300) MsgBox "All done!" '-------------* ' Save the spreadsheet and close the workbook '-------------* 'objExcel.ActiveWorkbook.SaveAs strExcelPath LightYellow LightYellow LightYellow LightYellow LightYellow LightYellow LightYellow LightYellow LightYellow = LightYellow
VBScript Examples
'objExcel.ActiveWorkbook.Close 'objExcel.Application.Quit 'Clean Up 'Set objSheet = Nothing 'Set objExcel = Nothing Function RN() Dim TempRN TempRN = Int((40) * Rnd + 1) ' Get rid of colors that we do not want do while (TempRN = BLACK) or (TempRN = DarkBlue) or (TempRN = DarkPurple) or _ (TempRN = 25) TempRN = Int((40) * Rnd + 1) Loop RN = TempRN end Function 'Quit Excel
VBScript Examples
Spreadsheet Statistics
This script will display statistics about it: the last defined cell, the last used cell, etc. Features: File open dialogue
' Spreadsheet Statistics Option Explicit Dim objFSO, InitFSO Dim objExcel, objWorkbook, objWorksheet, row, col, msg, ThisTxt, ThisLen, i, j Dim wksheetno, wkbkname, intLimit, ColIDs, IDIdx, strExtra Set ObjFSO = CreateObject("UserAccounts.CommonDialog") ObjFSO.Filter = "Excel files|*.xls" InitFSO = ObjFSO.ShowOpen If InitFSO = False Then Wscript.Echo "You did not select a file!" Wscript.Quit Else wkbkname = ObjFSO.Filename End If ' Start the application Set objExcel = CreateObject("Excel.Application") 'objExcel.Application.visible = true ' make Excel visible
Set objWorkbook = objExcel.Workbooks.Open(wkbkname) If objWorkbook.sheets.count > 1 then wkSheetno = cInt(inputbox("Enter the worksheet number you wish to work with","SSStats needs some input from you!","1")) else wkSheetNo = 1 end if intLimit = objWorkbook.sheets.count strExtra = "" If intLimit > 10 then intLimit = 10 strExtra = "first ten" end if Msg = "Workbook Name: " & objWorkbook.Name & vbcrlf Msg = Msg & "No. of worksheets in this workbook: " & objWorkbook.sheets.count & vbcrlf If objWorkbook.sheets.count > 1 then Msg = Msg & "The " & strExtra & " worksheets are:" & vbcrlf for i = 1 to intLimit Msg = Msg & i & ". " & objWorkBook.sheets(i).Name & vbcrlf next end if Msg = Msg & vbcrlf ' Blank line
' Get some stats on a specific worksheet If wksheetno > objWorkbook.sheets.count then
VBScript Examples
msgbox "You selected worksheet number " & wksheetno & ", and there are only" & objWorkbook.sheets.count ,,"Input Error" wscript.quit end if Set objWorksheet = objWorkbook.Worksheets(wksheetno) ColIDs ColIDs ColIDs ColIDs ColIDs ColIDs ColIDs ColIDs ColIDs ColIDs = = = = = = = = = = " A B C D E F G H I J K L M N O P Q R S T U V W X Y Z" ColIDs & "AAABACADAEAFAGAHAIAJAKALAMANAOAPAQARASATAUAVAWAXAYAZ" ColIDs & "BABBBCBDBEBFBGBHBIBJBKBLBMBNBOBPBQBRBSBTBUBVBWBXBYBZ" ColIDs & "CACBCCCDCECFCGCHCICJCKCLCMCNCOCPCQCRCSCTCUCVCWCXCYCZ" ColIDs & "DADBDCDDDEDFDGDHDIDJDKDLDMDNDODPDQDRDSDTDUDVDWDXDYDZ" ColIDs & "EAEBECEDEEEFEGEHEIEJEKELEMENEOEPEQERESETEUEVEWEXEYEZ" ColIDs & "FAFBFCFDFEFFFGFHFIFJFKFLFMFNFOFPFQFRFSFTFUFVFWFXFYFZ" ColIDs & "GAGBGCGDGEGFGGGHGIGJGKGLGMGNGOGPGQGRGSGTGUGVGWGXGYGZ" ColIDs & "HAHBHCHDHEHFHGHHHIHJHKHLHMHNHOHPHQHRHSHTHUHVHWHXHYHZ" ColIDs & "IAIBICIDIEIFIGIHIIIJIKILIMINIOIPIQIRISITIUIV" ' ' ' ' ' ' ' ' ' ' A AA BA CA DA EA FA GA HA IA thru thru thru thru thru thru thru thru thru thru Z AZ BZ CZ DZ EZ FZ GZ HZ IV (230, max)
Msg = Msg & "Worksheet " & wksheetno & " is named " & objWorksheet.Name & vbcrlf Msg = Msg & "The last defined cell is ROW " & objWorksheet.UsedRange.Rows.Count & ", COL " IDIdx = objWorksheet.UsedRange.Columns.Count * 2 - 1 Msg = Msg & mid(ColIDs,IDIDx,2) & vbcrlf Msg = Msg & "and contains " & _ ObjWorksheet.Cells(objWorksheet.UsedRange.Rows.Count, _ objWorksheet.UsedRange.Columns.Count).Value & vbcrlf & vbcrlf ' We already know which rows and columns are DEFINED. Now see which cell is the last to actually ' contain a value. For i = objWorksheet.UsedRange.Rows.Count to 1 step -1 For j = objWorksheet.UsedRange.Columns.Count to 1 step -1 if len(objWorksheet.Cells(i,j).Value) > 0 then Msg = Msg & "The last USED cell is ROW " & i & ", COL " IDIdx = j*2-1 Msg = Msg & mid(ColIds,IDIdx,2) & vbcrlf Msg = Msg & "and contains " & objWorksheet.Cells(i,j).Value & vbcrlf i = 1 : j = 1 ' Set to exit the loop end if next next MsgBox Msg,,WScript.Scriptname objExcel.Application.quit Set objWorksheet = nothing Set objWorkbook = nothing Set objExcel = nothing Wscript.quit ' Do not Leave the spreadsheet open
VBScript Examples
'*------------* '* Proc01 - Initialization '*------------* Sub Proc01 End sub '*------------* '* Proc02 - Copy the output spreadsheet to a new one '*------------* Sub Proc02 Const IPFN = "U:\Assignments\_Open\A002\Template.xls" Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFileCopy = objFSO.GetFile(IPFN) if objFSO.FileExists(OPFN) then objFSO.DeleteFile(OPFN) end if objFileCopy.Copy (OPFN) End sub '*------------* '* Proc03 - Populate the output spreadsheet '*------------* Sub Proc03 Const filename = "U:\Assignments\_Open\A002\FR's from Copy of Requirements from DR1412 20100708 v 1 1.xls" Dim Seq, FrNo, Paragraph, Title, Description, CQI, strModule, Status, row Set objExcel = CreateObject("Excel.Application") ' Start the application Set objWorkBookI = objExcel.Workbooks.Open(filename) Set objWorksheetI = objWorkBookI.Worksheets(1) Set objWorkBookO = objExcel.Workbooks.Open(OPFN) Set objWorksheetO = objWorkBookO.Worksheets(1) For row = 2 to objWorksheetI.UsedRange.Rows.Count Seq = (objWorksheetI.Cells(row,1).Value) FrNo = (objWorksheetI.Cells(row,2).Value) Paragraph = (objWorksheetI.Cells(row,3).Value) Title = (objWorksheetI.Cells(row,4).Value) Description = (objWorksheetI.Cells(row,5).Value) CQI = (objWorksheetI.Cells(row,6).Value) strModule = (objWorksheetI.Cells(row,7).Value)
VBScript Examples
Status = (objWorksheetI.Cells(row,8).Value) ' Move the fields to the output spreadsheet objWorksheetO.Cells(row+7,1).Value = Seq objWorksheetO.Cells(row+7,4).Value = FRNo objWorksheetO.Cells(row+7,5).Value = Title objWorksheetO.Cells(row+7,6).Value = Description Next objWorkBookI.close 'objWorkBookO.close objExcel.Visible = true End sub '*------------* '* Proc04 - Finalization '*------------* Sub Proc04 ' Free the memory MsgBox "Complete",,wscript.scriptname End sub
VBScript Examples
VBScript Examples
end if ctrIP = ctrIP + 1 ' Count IRows processed
' Display where testability is empty If (trim(objWorksheetI.Cells(IRow,7).Value) = "") then strUAMsg = strUAMsg & "Req= " & strReqNo & " (Row=" & IRow & ")" & _ "; Testability was not completed." & vbcrlf ctrFnd = ctrFnd + 1 end if ' Display where Reviewer's Initials cell is is empty If (trim(objWorksheetI.Cells(IRow,9).Value) = "") then strUAMsg = strUAMsg & "Req= " & strReqNo & " (Row=" & IRow & ")" & _ "; Reviewer's initials were not supplied." & vbcrlf ctrFnd = ctrFnd + 1 end if ' If Failed, make sure there is something in cols C, H, and I If (trim(objWorksheetI.Cells(IRow,7).Value) = "FAIL") then If (trim(objWorksheetI.Cells(IRow,3).Value) = "") then strUAMsg = strUAMsg & "Req= " & strReqNo & " (Row=" & IRow & ")" & _ "; Finding is missing." & vbcrlf ctrFnd = ctrFnd + 1 end if If (trim(objWorksheetI.Cells(IRow,8).Value) = "") then strUAMsg = strUAMsg & "Req= " & strReqNo & " (Row=" & IRow & ")" & _ "; Reviewer's Comments missing." & vbcrlf ctrFnd = ctrFnd + 1 end if If (trim(objWorksheetI.Cells(IRow,9).Value) = "") then strUAMsg = strUAMsg & "Req= " & strReqNo & " (Row=" & IRow & ")" & _ "; Reviewer's Initials are missing." & vbcrlf ctrFnd = ctrFnd + 1 end if end if ' If Passed, make sure there is NOTHING in col C If (trim(objWorksheetI.Cells(IRow,7).Value) = "PASS") then If (trim(objWorksheetI.Cells(IRow,3).Value) <> "") then strUAMsg = strUAMsg & "Req= " & strReqNo & "; Finding supplied for passed requirement." vbcrlf ctrFnd = ctrFnd + 1 end if end if ' Now list the failed items to the output spreadsheet If (objWorksheetI.Cells(IRow,7).Value) = "FAIL" then ctrFailed = ctrFailed + 1 : oRow = oRow + 1 objWorksheetO.Cells(oRow,1).Value = strReqNo objExcel.Columns(2).ColumnWidth = 60 objWorksheetO.Cells(oRow,2).Value = Comments set objRange = objExcel.Range("B1").EntireColumn objRange.Wraptext = true objWorksheetO.Cells(oRow,3).Value = Initials end if Next objWorkBookI.close objFSO.deleteFile(OPFN) objWorkbookO.SaveAs(OPFN) objExcel.visible = true Msg = "I processed " & ctrIP & " input rows." & vbcrlf
&
VBScript Examples
Msg = Msg & "I found " & ctrFnd & " problems." & vbcrlf If ctrFnd > 0 then Msg = Msg & "They are: " & vbcrlf & strUAMsg end if Msg = Msg & ctrFailed & " requirements were failed, and written to the output spreadsheet." & vbcrlf MsgBox Msg,,wscript.scriptname
VBScript Examples
ctrCells = 0 Const Threshhold = 1000 For Row = 1 to objWorksheet.UsedRange.Rows.Count For col = 1 to 9 ctrCells = ctrCells + 1 ThisTxt = (objWorksheet.Cells(row,col).Value) ThisLen = len(ThisTxt) If ThisLen > Threshhold then DivideCell end if next next 'msg = msg & "I checked " & ctrCells & " cells." & vbcrlf 'MsgBox(Msg) objExcel.Application.quit ' Close the spreadsheet Set objWorksheet = nothing Set objWorkbook = nothing
VBScript Examples
Set objExcel = nothing objTextFile.close ' Open Notepad, and write the new stuff Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.Run ("%windir%\notepad" & " " & OPFN) Wscript.quit '*------------* Sub DivideCell '*------------* Dim opLine, i, j, strThisLine, opPartNo opLine = "Row=" & row & "; col=" & col & "; length=" & ThisLen objTextFile.writeline(OpLine) objTextFile.writeline("Part 1 " & "------------------------------") opLine = "" : ipLen = 0 : OpLen = 0 : opPartNo = 1 For i = 1 to len(Thistxt) ipLen = ipLen + 1 If mid(ThisTxt,i,1) = vbLF then ipLen = ipLen - 1 If swDebug then opLine = "Line len=" & ipLen & "; line=" & " " & opline end if objTextFile.writeline(OpLine) : OpLine = "" opLen = opLen + ipLen If opLen > 1000 then objTextFile.writeline opLen = 0 opPartNo = opPartNo + 1 objTextFile.writeline("Part " & opPartNo & " ------------------------------") end if ipLen = 0 else opLine = opLine & mid(Thistxt,i,1) end if Next opLine = "------------------------------------------------------------------------------" objTextFile.writeline(OpLine) End Sub
VBScript Examples
VBScript Examples
VBScript Examples
VBScript Examples
Highlight a Cell
' 1=black 2=nothing 3=red 4=green 5=blue 6=yellow objWorkSheetB.Cells(RowB,10).Interior.ColorIndex = 6
VBScript Examples
' Making Word visible will allow you to watch as the words are added to the document, but it ' SIGNIFICANTLY slows down the processing. objWord.Visible = True ' All two-letter combinations: 26**2 = 676 ' All three-letter combinations: 26**3 = 17,576 ' All four-letter combinations: 26**4 = 456,976 Do For L1 = 1 to 26 For L2 = 1 to 26 For L3 = 1 to 26 For L4 = 1 to 26 ctrWord = ctrWord + 1 objword.selection.font.name = "Times New Roman" objword.selection.font.size = 10 objWord.Selection.TypeText ctrWord & vbTab objword.selection.font.name = "Courier New" objword.selection.font.size = 12 objWord.Selection.TypeText mid(Alphabet,L1,1) mid(Alphabet,L2,1) mid(Alphabet,L3,1) mid(Alphabet,L4,1) vbCrLf If ctrWord > 17578 then exit do end if next next next next Loop
_ _ _ _
VBScript Examples
objWord.Visible = True 'Wscript.quit 'objWord.Selection.movedown 'objWord.Selection.typeparagraph()
VBScript Examples
For i = 1 to NUMBER_OF_ROWS For j = 1 to NUMBER_OF_COLUMNS objTable.Cell(i, j).Range.Text = "Row " objTable.Cell(i, j).Range.Text = "Row " objTable.Cell(i, j).Range.Text = "Row " next next 'ObjTable.Rows.add() ' Add a blank objTable.AutoFormat(16)
& i & ", Column " & j & i & ", Column " & j & i & ", Column " & j row
VBScript Examples
objWord.Selection.TypeText "Active Printer: " & objWord.ActivePrinter & vbCRLF For Each objAddIn in objWord.AddIns objWord.Selection.TypeText "AddIn: " & objAddIn & vbCRLF Next objWord.Selection.TypeText "Application: " & objWord.Application & vbCRLF objWord.Selection.TypeText "Assistant: " & objWord.Assistant & vbCRLF objWord.Selection.TypeText vbcrlf objWord.Selection.TypeText "AutoCaptions (" & objWord.AutoCaptions.Count & "):" & vbCRLF ctr = 0 For Each objCaption in objWord.AutoCaptions ctr = ctr + 1 objWord.Selection.TypeText "- " & ctr & ": " & objCaption & vbCRLF Next objWord.Selection.TypeText vbcrlf objWord.Selection.TypeText objWord.Selection.TypeText vbCRLF objWord.Selection.TypeText objWord.Selection.TypeText objWord.Selection.TypeText objWord.Selection.TypeText objWord.Selection.TypeText "Automation Security: " & objWord.AutomationSecurity & vbCRLF "Background Printing Status: " & objWord.BackgroundPrintingStatus & "Background Saving Status: " & objWord.BackgroundSavingStatus & vbCRLF "Browse Extra File Type: " & objWord.BrowseExtraFileTypes & vbCRLF "Build: " & objWord.Build & vbCRLF "Caps Lock: " & objWord.CapsLock & vbCRLF "Caption: " & objWord.Caption & vbCRLF
objWord.Selection.TypeText vbcrlf objWord.Selection.TypeText "Caption Labels (" & objWord.CaptionLabels.Count & "):" & vbCRLF ctr = 0 For Each objLabel in objWord.CaptionLabels ctr = ctr + 1 objWord.Selection.TypeText "- " & ctr & ": " & objLabel & vbCRLF Next objWord.Selection.TypeText vbcrlf objWord.Selection.TypeText "Check Language: " & objWord.CheckLanguage & vbCRLF For Each objAddIn in objWord.COMAddIns objWord.Selection.TypeText "COM AddIn: " & objAddIn & vbCRLF Next objWord.Selection.TypeText "Creator: " & objWord.Creator & vbCRLF For Each objDictionary in objWord.CustomDictionaries
VBScript Examples
objWord.Selection.TypeText "Custom Dictionary: " & objDictionary & vbCRLF Next objWord.Selection.TypeText objWord.Selection.TypeText objWord.Selection.TypeText objWord.Selection.TypeText "Customization Context: " "Default Legal Blackline: "Default Save Format: " & "Default Table Separator: & objWord.CustomizationContext & vbCRLF " & objWord.DefaultLegalBlackline & vbCRLF objWord.DefaultSaveFormat & vbCRLF " & objWord.DefaultTableSeparator & vbCRLF
objWord.Selection.TypeText vbcrlf objWord.Selection.TypeText "Dialogs (" & objWord.Dialogs.Count & "), not listed." & vbCRLF ' Displaying these dialogues as above does funny things to the Word document. ' #68 (199) will wipe out the text in the document and start all over. ' Another will do something with Outlook. 'objWord.Dialogs(80).Show ' Word help dialogue objWord.Selection.TypeText "Display Alerts: " & objWord.DisplayAlerts & vbCRLF objWord.Selection.TypeText "Display Recent Files: " & objWord.DisplayRecentFiles & vbCRLF objWord.Selection.TypeText "Display Screen Tips: " & objWord.DisplayScreenTips & vbCRLF objWord.Selection.TypeText "Display Scroll Bars: " & objWord.DisplayScrollBars & vbCRLF For Each objDocument in objWord.Documents objWord.Selection.TypeText "Document: " & objDocument & vbCRLF Next objWord.Selection.TypeText "Email Template: " & objWord.EmailTemplate & vbCRLF objWord.Selection.TypeText "Enable Cancel Key: " & objWord.EnableCancelKey & vbCRLF objWord.Selection.TypeText "Feature Install: " & objWord.FeatureInstall & vbCRLF objWord.Selection.TypeText vbcrlf objWord.Selection.TypeText "File Converters (" & objWord.FileConverters.Count & "):" & vbCRLF ctr = 0 For Each objConverter in objWord.FileConverters ctr = ctr + 1 objWord.Selection.TypeText "- " & ctr & ": " & objConverter & vbCRLF Next objWord.Selection.TypeText vbcrlf objWord.Selection.TypeText "Focus In MailHeader: " & objWord.FocusInMailHeader & vbCRLF objWord.Selection.TypeText vbcrlf objWord.Selection.TypeText "Font names (" & objWord.Fontnames.Count & "):" & vbCRLF ctr = 0 For Each objFont in objWord.FontNames ctr = ctr + 1 objWord.Selection.TypeText "- " & ctr & ": " & objFont & vbCRLF Next objWord.Selection.TypeText vbcrlf objWord.Selection.TypeText "Height: " & objWord.Height & vbCRLF ' This isn't working. The system complains about objBinding. 'For Each objBinding in objWord.KeyBindings ' objWord.Selection.TypeText "Key Binding: " & objBinding & vbCRLF 'Next objWord.Selection.TypeText vbcrlf objWord.Selection.TypeText "LandscapeFontnames (" & objWord.LandScapeFontnames.Count & "):" & vbCRLF ctr = 0 For Each objFont in objWord.LandscapeFontNames ctr = ctr + 1 objWord.Selection.TypeText "- " & ctr & ": " & objFont & vbCRLF Next objWord.Selection.TypeText vbcrlf
VBScript Examples
objWord.Selection.TypeText "Languages (" & objWord.Languages.Count & "):" & vbCRLF ctr = 0 For Each objLanguage in objWord.Languages ctr = ctr + 1 objWord.Selection.TypeText "- " & ctr & ": " & objLanguage & vbCRLF Next objWord.Selection.TypeText vbcrlf objWord.Selection.TypeText objWord.Selection.TypeText objWord.Selection.TypeText objWord.Selection.TypeText vbCRLF objWord.Selection.TypeText objWord.Selection.TypeText objWord.Selection.TypeText objWord.Selection.TypeText objWord.Selection.TypeText objWord.Selection.TypeText objWord.Selection.TypeText objWord.Selection.TypeText "Left" & objWord.Left & vbCRLF "Mail System: " & objWord.MailSystem & vbCRLF "MAPI Available: " & objWord.MAPIAvailable & vbCRLF "Math Coprocessor Available: " & objWord.MathCoprocessorAvailable & "Mouse Available: " & objWord.MouseAvailable & vbCRLF "Name: " & objWord.Name & vbCRLF "Normal Template: " & objWord.NormalTemplate & vbCRLF "Num Lock: " & objWord.NumLock & vbCRLF "Parent: " & objWord.Parent & vbCRLF "Path: " & objWord.Path & vbCRLF "Path Separator: " & objWord.PathSeparator & vbCRLF "Print Preview: " & objWord.PrintPreview & vbCRLF
objWord.Selection.TypeText vbcrlf objWord.Selection.TypeText "Recent Files (" & objWord.RecentFiles.Count & "):" & vbCRLF ctr = 0 For Each objFile in objWord.RecentFiles ctr = ctr + 1 objWord.Selection.TypeText "- " & ctr & ": " & objFile & vbCRLF Next objWord.Selection.TypeText vbcrlf objWord.Selection.TypeText "Screen Updating: " & objWord.ScreenUpdating & vbCRLF objWord.Selection.TypeText "Show Visual Basic Editor: " & objWord.ShowVisualBasicEditor & vbCRLF objWord.Selection.TypeText "Special Mode: " & objWord.SpecialMode & vbCRLF svFontName = objword.selection.font.name svFontSize = objword.selection.font.size objWord.Selection.TypeText "Startup Path: " objword.selection.font.name = "Courier New" objword.selection.font.size = 8 objWord.Selection.TypeText objWord.StartupPath & vbCRLF objword.selection.font.name = svFontName objword.selection.font.size = svFontSize objWord.Selection.TypeText vbcrlf objWord.Selection.TypeText "Tasks (" & objWord.Tasks.Count & "):" & vbCRLF ctr = 0 For Each objTask in objWord.Tasks ctr = ctr + 1 objWord.Selection.TypeText "- " & ctr & ": " & objTask & vbCRLF Next objWord.Selection.TypeText vbcrlf For Each objTemplate in objWord.Templates objWord.Selection.TypeText "Template: " & objTemplate & vbCRLF Next objWord.Selection.TypeText vbcrlf objWord.Selection.TypeText objWord.Selection.TypeText objWord.Selection.TypeText objWord.Selection.TypeText "Top: " & objWord.Top & vbCRLF "Usable Height: " & objWord.UsableHeight & vbCRLF "Usable Width: " & objWord.UsableWidth & vbCRLF "User Address: " & objWord.UserAddress & vbCRLF
VBScript Examples
objWord.Selection.TypeText "User Control: " & objWord.UserControl & vbCRLF objWord.Selection.TypeText "User Initials: " & objWord.UserInitials & vbCRLF objWord.Selection.TypeText "User Name: " svFontName = objword.selection.font.name svFontSize = objword.selection.font.size objword.selection.font.name = "Times New Roman" objword.selection.font.size = 18 objWord.Selection.TypeText objWord.UserName & vbCRLF objword.selection.font.name = svFontname objword.selection.font.size = svFontSize objWord.Selection.TypeText "Version: " & objWord.Version & vbCRLF objWord.Selection.TypeText "Visible: " & objWord.Visible & vbCRLF objWord.Selection.TypeText "Width: " & objWord.Width & vbCRLF For Each objWindow in objWord.Windows objWord.Selection.TypeText "Window: " & objWindow & vbCRLF Next objWord.Selection.TypeText "Window State: " & objWord.WindowState & vbCRLF 'objWord.Quit objWord.Selection.TypeText "*--- END OF LIST ---*" & vbCRLF WScript.quit Sub CheckError(ErrSrc) If Err.Number <> 0 then Msg = "Exception:" & vbCrLf &_ " Error number: " & Err.Number & vbCrLf &_ " Error description: '" & Err.Description & vbCrLf & _ " Source" & ErrSrc MsgBox Msg,,"Error?" end if End Sub
VBScript Examples
MsgBox Msg,,Wscript.Scriptname & " completed." Set objFSO = nothing WScript.quit '*------------* '* Initialization '*------------* Sub ProcInit If Wscript.Arguments.Count = 0 then wscript.echo "Please drag a file to the icon!" wscript.quit end if IpPath = wscript.arguments(0) ' Complete input file name Msg = "IpFile: " & IPPath & vbCRLF Set objFSO = CreateObject("Scripting.FileSystemObject") Set objWord = CreateObject("Word.Application") Set objDoc = objWord.Documents.Add objWord.Visible = True objword.ActiveDocument.pagesetup.leftmargin = 50 objword.ActiveDocument.pagesetup.rightmargin = 50 ' Launch Microsoft Word ' Create a new document ' Pixels??? ' Pixels???
' Header objWord.ActiveWindow.ActivePane.View.SeekView = wdSeekPrimaryHeader objword.selection.font.name = "Times New Roman" objword.selection.font.size = 14 objWord.selection.Paragraphs.Alignment = wdAlignParagraphCenter objWord.Selection.TypeText IPPath
VBScript Examples
ProcFooter End Sub '*------------* '* Add all of the Assembler statements to an array '*------------* Sub Proc01 Dim objIpFile, ipLine, swInStmts, ctrIP, stmtno Set objIpFile = objFSO.OpenTextFile(IPPath) ctrIp = 0 : ctrStmts = 0 swInStmts = "N" Do Until objIPFile.AtEndOfStream ipLine = RTrim(objIPFile.ReadLine) : CtrIP = CtrIP + 1 if swInStmts = "N" then If mid(IpLine,37,4) = "STMT" then swInStmts = "Y" end if end if if swInStmts = "Y" then If mid(IpLine,51,21) = "RELOCATION DICTIONARY" then swInStmts = "X" ' We are done end if end if if swInStmts = "Y" then ' Lines to skip if (mid(IpLine,42,1) = "*") or _ (left(IpLine,1) = "1") or _ (mid(ipLine,4,14) = "ACTIVE USINGS:") then else stmtno = mid(IpLine,36,5) If IsNumeric(stmtno) then ctrStmts = ctrStmts + 1 arStmts(stmtno) = mid(IpLine,36,78) ' Add it to the nth entry end if end if end if loop objIPfile.Close() Set objIPFile = nothing Msg = "Records read: " & ctrIP & vbcrlf Msg = Msg & "arStmts added: " & ctrStmts & vbcrlf End Sub '*------------* '* Process the variables (via the Cross-Reference) '*------------* Sub Proc02 Dim objIpFile, swInXref, ctrIP, ctrXRef Set objIpFile = objFSO.OpenTextFile(IPPath) ctrIp = 0 swInXRef = "N" ctrXref = 0 Do Until objIPFile.AtEndOfStream ipLine = RTrim(objIPFile.ReadLine) : CtrIP = CtrIP + 1 if swInXref = "N" then If mid(IpLine,33,43) = "ORDINARY SYMBOL AND LITERAL CROSS REFERENCE" then swInXref = "Y" end if end if if swInXref = "Y" then
VBScript Examples
If mid(IpLine,2,1) = "=" then ' First literal. We are done. 'wscript.echo "I found the END of the cross-ref section (the first literal)" swInXref = "X" end if end if if swInXref = "Y" then ctrXRef = ctrXRef + 1 ' Lines to skip if (left(IpLine,8) = "1 ") or _ (left(IpLine,7) = "-SYMBOL") then else Proc021 ' Process this variable end if end if if ctrXref > OPLIMIT then exit do end if loop objIPfile.Close() Set objIPFile = nothing Msg = "XRef recs read: " & ctrXRef & vbcrlf End Sub '*------------* '* Process one variable '*------------* Sub Proc021 Dim ipLabel, ipLength, ipAddress, ipType, ipDefn, ipRefs, Msg2, i, strWk Dim stmtno, stmtbody, arWord, refNo if mid(IpLine,2,8) <> space(8) then ipLabel = mid(IpLine,2,8) ' Assembler label end if ipLength = mid(IpLine,12,5) ' Length ipAddress = mid(IpLine,18,8) ' Address ipType = mid(IpLine,40,1) ' Type ipDefn = mid(IpLine,56,6) ' Defined at statement no. if mid(IpLine,2,8) = space(8) then ipRefs = ipRefs & mid(IpLine,63,55) ' References else ipRefs = mid(IpLine,63,55) ' References end if ' Process the definition statement If trim(ipDefn) <> "" then objword.selection.font.name = "Courier New" objword.selection.font.size = 10 Msg2 = "Variable=" & trim(ipLabel) & "; " Msg2 = Msg2 & "length=" & ipLength & "; " Msg2 = Msg2 & "Address=" & ipAddress & "; " Msg2 = Msg2 & "type=" & ipType objWord.Selection.TypeText Msg2 & vbcrlf objword.selection.font.size = 9 Msg2 = " DEFN (" & trim(ipdefn) & "):" & vbTab strWk = arStmts(ipdefn) & space(7) stmtbody = Right(strWk,len(strWk)-6) Msg2 = Msg2 & stmtbody objWord.Selection.TypeText Msg2 & vbcrlf end if ' Process the references now. IpRefs = trim(IpRefs)
VBScript Examples
arWord = Split(IpRefs) for each RefNo in arWord Refno = trim(Refno) If Refno <> "" then If right(RefNo,1) = "B" then Refno = left(RefNo,len(RefNo) If right(RefNo,1) = "D" then Refno = left(RefNo,len(RefNo) If right(RefNo,1) = "M" then Refno = left(RefNo,len(RefNo) If right(RefNo,1) = "U" then Refno = left(RefNo,len(RefNo) objword.selection.font.size = 9 Msg2 = " REF (" & RefNo & "):" & vbTab strWk = arStmts(RefNo) & space(7) stmtbody = Right(strWk,len(strWk)-6) Msg2 = Msg2 & stmtbody objWord.Selection.TypeText Msg2 & vbcrlf end if next objWord.Selection.TypeText vbcrlf End Sub '*------------* '* Process the Footer '*------------* Sub ProcFooter Dim strWk With objWord .ActiveWindow.ActivePane.View.SeekView = wdSeekPrimaryFooter .selection.font.size = 08 .selection.Paragraphs.Alignment = wdAlignParagraphCenter .Selection.TypeText Now() & " - Page " .Selection.Fields.Add .Selection.Range,wdFieldPage .Selection.TypeText " of " .Selection.Fields.Add .Selection.Range,wdFieldNumPages end with 'objWord.Selection.TypeText strwk objWord.ActiveWindow.ActivePane.View.Seekview = wdSeekMainDocument End Sub
1) 1) 1) 1)
VBScript Examples
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objIpFile = objFSO.OpenTextFile(IPPath) Set objWord = CreateObject("Word.Application") Set objDoc = objWord.Documents.Add objWord.Visible = True objword.ActiveDocument.pagesetup.leftmargin = 50 objword.ActiveDocument.pagesetup.rightmargin = 50 ProcHeader ProcFooter CtrIP = 0 : CtrOP = 0 Do Until objIPFile.AtEndOfStream ipLine = RTrim(objIPFile.ReadLine) : CtrIP = CtrIP + 1 If (left(IpLine,1) = "<") or _ (instr(1,IpLine,"<html>",vbTextCompare) > 0) or _ (instr(1,IpLine,"<tt>",vbTextCompare) > 0) or _ (instr(1,IpLine,"<td w",vbTextCompare) > 0) then ctrSkipped = ctrSkipped + 1 else opLine = ipLine objword.selection.font.size = 12 objWord.selection.TypeText opLine & vbcrlf ' Launch Microsoft Word ' Create a new document ' Pixels??? ' Pixels???
VBScript Examples
CtrOP = CtrOP + 1 if ctrOP > opLimit then wscript.quit end if end if loop objIPfile.Close() Msg = "" Msg = Msg & "IpFile: " & IPPath & vbCRLF Msg = Msg & CtrIP & " records read. " & vbCRLF MsgBox Msg,,Wscript.Scriptname Set objFSO = nothing Set objIPFile = nothing Set objOPFile = nothing wscript.quit '*------------* '* Process the Header '*------------* Sub ProcHeader With objWord .ActiveWindow.ActivePane.View.SeekView = wdSeekPrimaryHeader .selection.font.name = "Times New Roman" .selection.Paragraphs.Alignment = wdAlignParagraphCenter .selection.font.size = 14 .Selection.TypeText "Module Linkage Report" & vbcrlf .selection.font.size = 12 .Selection.TypeText "Input: " & IPPath end with End sub '*------------* '* Process the Footer '*------------* Sub ProcFooter With objWord .ActiveWindow.ActivePane.View.SeekView = wdSeekPrimaryFooter .selection.font.size = 08 .selection.Paragraphs.Alignment = wdAlignParagraphCenter .Selection.Fields.Add .Selection.Range,wdFieldFileName,"\p",false .Selection.TypeText " - " & Now() & " - Page " .Selection.Fields.Add .Selection.Range,wdFieldPage .Selection.TypeText " of " .Selection.Fields.Add .Selection.Range,wdFieldNumPages end with objWord.ActiveWindow.ActivePane.View.Seekview = wdSeekMainDocument End Sub
VBScript Examples
' Word has created strContents, and separated each text line by ONLY a carriage return. ' We need to add line feeds. strContents2 = "" For i = 1 to len(strContents) ThisChar = mid(strContents,i,1) If ThisChar = vbCR then strContents2 = strContents2 & vbcrlf else strContents2 = strContents2 & ThisChar end if Next OpPath = "\\Dmvfsp08\mwdxg12$\Assignments\Misc\document.txt" Set objFSO = CreateObject("Scripting.FileSystemObject") Set objOPFile = objFSO.CreateTextFile(OPPath) objOPFile.write(strContents2) objOPfile.Close()
VBScript Examples
Msg = "Command complete!" MsgBox Msg,,Wscript.Scriptname Set Set Set Set Set Set objOPFile = nothing objFSO = nothing objOPFile = nothing objSelection = nothing objDoc = nothing objWord = nothing
VBScript Examples
dtDate = #01/01/2011# objWord.selection.font.size = 12 objWord.selection.font.name = "Times New Roman" For i = 1 to 16 objWord.selection.font.bold = true objWord.Selection.TypeText FormatDateTime(dtDate,vbLongDate) & vbcrlf objWord.selection.font.bold = false objWord.Selection.TypeText vbcrlf dtDate = dtDate + 1 Next Msg = "Done" MsgBox Msg,,Wscript.Scriptname wscript.quit
VBScript Examples
VBScript Examples
objword.selection.font.size = 9 ipLine = RTrim(objIPFile.ReadLine) : CtrIP = CtrIP + 1 ctlchar = left(IpLine,1) if ctlchar = "1" then if ctrIP > 1 then objword.Selection.InsertBreak(wdPageBreak) end if If ctlchar = "0" then objWord.selection.TypeText " " & vbcrlf ' Blank line CtrOP = CtrOP + 1 end if If len(IpLine) > 0 then opLine = right(ipLine,len(IpLine)-1) else opLine = "" end if objWord.selection.TypeText opLine & vbcrlf CtrOP = CtrOP + 1 loop objIPfile.Close() Msg = "" Msg = Msg & "IpFile: " & IPPath & vbCRLF Msg = Msg & "- " & CtrIP & " records read. " & vbCRLF MsgBox Msg,,Wscript.Scriptname Set objFSO = nothing Set objIPFile = nothing wscript.quit '*------------* '* Process the Header '*------------* Sub ProcHeader exit sub ' If you want a heading later, comment this statement With objWord .ActiveWindow.ActivePane.View.SeekView = wdSeekPrimaryHeader .selection.font.name = "Times New Roman" .selection.Paragraphs.Alignment = wdAlignParagraphCenter .selection.font.size = 14 .Selection.TypeText ipPath .selection.font.size = 12 end with End sub '*------------* '* Process the Footer '*------------* Sub ProcFooter With objWord .ActiveWindow.ActivePane.View.SeekView = wdSeekPrimaryFooter .selection.font.size = 08 .selection.Paragraphs.Alignment = wdAlignParagraphCenter .Selection.Fields.Add .Selection.Range,wdFieldFileName,"\p",false .Selection.TypeText " - " & Now() & " - Page " .Selection.Fields.Add .Selection.Range,wdFieldPage .Selection.TypeText " of " .Selection.Fields.Add .Selection.Range,wdFieldNumPages end with objWord.ActiveWindow.ActivePane.View.Seekview = wdSeekMainDocument End Sub
VBScript Examples
borderSize = 1 borderColor = DefaultCalendarBorderColor thisday = Day(Date) myDate = Date myDay = DatePart("D", Date) iThisMonth = Month(Date) iThisYear = Year(Date) strFirstmdy = (iThisMonth & "/1/" & iThisYear) iFirstDayofThisMonth = DatePart("W", strFirstmdy) ' Store the month names into an array. ReDim monthName(13) monthName(0) = "Space" 'Set element 0 to garbage so I don't have to do math later monthName(1) = "January" monthName(2) = "February" monthName(3) = "March" monthName(4) = "April" monthName(5) = "May" monthName(6) = "June" monthName(7) = "July" monthName(8) = "August" monthName(9) = "September" monthName(10) = "October" monthName(11) = "November" monthName(12) = "December" 'Calculate number of days this month
VBScript Examples
If iThisMonth = 12 Then iDaysThisMonth = DateDiff("d",strFirstmdy,("1/1/" & (iThisYear+1))) Else iDaysThisMonth = DateDiff("d",strFirstmdy,((iThisMonth+1) & "/1/" & iThisYear)) End If '*------------*& '* Begin creation of the output file here '*------------*& Set ObjFSO = CreateObject("Scripting.FileSystemObject") ' We don't use "temporary" file names, because they really aren't, and they hang around forever, ' or until someone specifically deletes them. strWebPagename = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".") & _ "\VBSCalendar.html" Set objTF = objFSO.CreateTextFile(strWebPageName) objTF.writeline("<%@ LANGUAGE=""VBSCRIPT"" %>") objTF.writeline("<HTML>") objTF.writeline("<HEAD>") objTF.writeline("<TITLE>My Calendar</TITLE>") objTF.writeline("</HEAD>") objTF.writeline("<body bgcolor=""#FFFFD8"">") Msg = FormatDateTime(Now(),vbLongDate) objTF.writeline("<center><h1>" & msg & "</h1>") OpLine = "<table cellpadding=""4"" cellspacing=""1"" border=""0"" bgcolor=""#ffffff"">" OpLine = OpLine & "<tr><td colspan=""7""align=""center"" bgcolor=Yellow><b>" OpLine = OpLine & (monthName(iThisMonth) & " " & iThisYear) & "</b></td></tr>" objTF.writeLine(OpLine) ' Write the row of weekday initials objTF.writeLine("<tr>") objTF.writeLine("<td align=""center"" objTF.writeLine("<td align=""center"" objTF.writeLine("<td align=""center"" objTF.writeLine("<td align=""center"" objTF.writeLine("<td align=""center"" objTF.writeLine("<td align=""center"" objTF.writeLine("<td align=""center"" objTF.writeLine("</tr>") objTF.writeLine("<tr>")
'Now write the first row For i = 1 to 7 if i = iFirstDayofThisMonth Then iDayToDisplay = 1 elseif i > iFirstDayofThisMonth Then iDayToDisplay = iDayToDisplay + 1 else iDayToDisplay=" " end if if iDayToDisplay = thisDay Then Msg = "<td align=center bgcolor=Yellow><b>" & iDayToDisplay & "</b></td>" else Msg = "<td align=center>" & iDayToDisplay & "</td>" end If objTF.writeLine(Msg) Next ' Now, display the rest of the month. ' First figure out how many weeks are left to write daysOffSet = 8 - iFirstDayofThisMonth daysLeft = iDaysThisMonth - daysOffset decWeekstogo = Round((daysLeft/7),2)
VBScript Examples
' I think this logic is screwy. If decweekstogo > 4 Then weekstogo = 5 ElseIf decweekstogo > 3 and decweekstogo <= 4 Then weekstogo = 4 Else weekstogo = 3 End if ' Now write the rows and populate the data For x = 1 To weekstogo objTF.writeLine("<tr>") For i = 1 To 7 If iDayToDisplay < iDaysThisMonth then iDayToDisplay = iDayToDisplay + 1 else iDayToDisplay = " " End If if iDayToDisplay = thisDay then Msg = "<td align=center bgcolor=Yellow><b>" & iDayToDisplay & "</b></td>" else Msg = "<td align=center>" & iDayToDisplay & "</td>" end If objTF.writeLine(Msg) Next objTF.writeLine("</tr>") Next objTF.writeLine("</table>") objTF.writeLine("</center>") ' The calendar is finished displaying. Now display some information that *might* be useful. iDayofYear = DateDiff("d","01/01/" & year(now),month(now) & "/" & day(now) & "/" & year(now)) + 1 objTF.writeLine("The Day of the Year is " & iDayofYear) ProcessOutlook objTF.writeLine("</BODY>") objTF.writeLine("</HTML>") objTF.close '*------------*& '* Now display the web page '*------------*& Set wshShell = WScript.CreateObject ("WSCript.shell") Set IE = CreateObject("InternetExplorer.Application") IE.visible = 1 IE.navigate("file:" & strWebPagename) '* We can't delete the file because we get here right after the web page is displayed, and it is still in use. 'objFSO.DeleteFile(strWebPagename) WScript.quit '*-------------* '* Go to Outlook for appointments '*-------------* Sub ProcessOutlook Dim objOutlook, objNameSpace, objFolder 'Const olMailItem = 0 'Const olTaskItem = 3 Const olFolderTasks = 13 Const olFolderCalender = 9 '* Display any meetings from Outlook
VBScript Examples
'Create Outlook, Namespace, Folder Objects and Task Item Set objOutlook = CreateObject("Outlook.application") Set objNameSpace = objOutlook.GetNameSpace("MAPI") Set objFolder = objNameSpace.GetDefaultFolder(olFolderCalender) Set MyItems = objFolder.Items MyItems.IncludeRecurrences = True myItems.Sort "[Start]" ' Check for meetings THIS week dtThisMonday = dateadd("d", 1 - weekday(date), date) + 1 strOutput = strOutput & "<Center><h3> Meetings This Week </h3></center>" DispOneWeek ' Check for meetings NEXT week dtThisMonday = dateadd("d", +7, dtThisMonday) strOutput = strOutput & "<Center><h3> Meetings NEXT Week </h3></center>" DispOneWeek ' Check for meetings NEXT week dtThisMonday = dateadd("d", +7, dtThisMonday) strOutput = strOutput & "<Center><h3> And, the week AFTER that </h3></center>" DispOneWeek 'Display results to user, if any. If strOutput > "" Then objTF.writeLine(strOutput) Else objTF.writeLine("Meetings for this week: NONE<br>") End If 'Clean up Set objFolder = Nothing Set objNameSpace = Nothing set objOutlook = Nothing End sub '*-------------* '* Sub DispOneWeek '*-------------* ' This routine will display one week's worth of Outlook reminders. Sub DispOneWeek oCount = 0 : iCount = 0 dtTheSundayAfter = DateAdd("d", +6, dtThisMonday) For Each CurrAppt in MyItems 'If CurrAppt.BusyStatus = 2 and CurrAppt.Sensitivity = 0 then ???? iCount = iCount + 1 If iCount > 365 then ' Limit the number of recurring entries to look at exit for ' Bail on THIS item only end if If CurrAppt.Start >= dtThisMonday And _ CurrAppt.Start <= dttheSundayAfter Then CrOpLine End If Next End sub '*-------------* '* Sub CrOpLine - Create an Output line for DispOneWeek '*-------------* Sub CrOpLine oCount = oCount + 1 strOutput = strOutput & oCount & ". " & _
VBScript Examples
"<b>Subject:</b> " & CurrAppt.Subject & _ " <b>Date/Time:</b> " & CurrAppt.Start & _ " <b>Duration</b> " & CurrAppt.Duration & "<br>" "; recurrence pattern=" & CurrAppt.GetRecurrencePattern & "<br><br>"
VBScript Examples
'Create Outlook, Namespace, Folder Objects and Task Item Set objOutlook = CreateObject("Outlook.application") Set objNameSpace = objOutlook.GetNameSpace("MAPI") Set objFolder = objNameSpace.GetDefaultFolder(olFolderCalender) Set MyItems = objFolder.Items dtLastWeek = DateAdd("d", -7, date) dtNextWeek = DateAdd("d", +7, date) strOutput = strOutput & "<h2> Meetings This Week </h2>" icount = 0 For Each CurrentAppointment in MyItems If currentAppointment.BusyStatus = 2 and currentAppointment.Sensitivity=0 then If CurrentAppointment.Start >= dtLastWeek And CurrentAppointment.Start <= Date+1 Then icount = icount + 1 strOutput = strOutput & icount & ". " & CurrentAppointment.Subject & vbTab & _ " <b>Time:</b> " & CurrentAppointment.Start & _ " <b>Duration</b> " & CurrentAppointment.Duration& vbCRLF txtNames = txtNames & CurrentAppointment.Subject & vbTab & _ " <b>Time:</b> " & CurrentAppointment.Start & _ " <b>duration</b> " & CurrentAppointment.Duration& vbCRLF End If End If Next ' Create (but don't send) the e-mail Set objMsg = objOutlook.CreateItem(olMailItem) objMsg.To = "e-mail recipient address" objMsg.Subject = "Subject of message on " & Date() objMsg.Display strOutput = replace(strOutput,vbCrLF,"<br>") objMsg.HTMLBody = strOutput 'Display results to user, if any. 'If strOutput > "" Then ' Msgbox strOutput, vbExclamation, "Meetings for this week" 'Else
VBScript Examples
' Msgbox "No Tasks Today", vbInformation,"No Meetings for this week" 'End If 'Clean up Set objFolder = Nothing Set objNameSpace = Nothing set objOutlook = Nothing set objMsg = Nothing
VBScript Examples
VBScript Examples
'unique id
values (1,'Grund','1234 W 5th Street')" values (2,'Smith','4523 N 6th Street')" values (3,'Jones','7890 S 1st Street')" values (4,'Blake','6543 E 2nd Street')"
VBScript Examples
Msg = "" while rs.EOF <> true and rs.BOF <> True Msg = Msg & "ID=" & rs(0) & "; Surname=" & rs(1) & "; Address=" & rs(2) & vbcrlf rs.movenext wend conn.close MsgBox Msg,,"Table contents" ' Free the memory set tblData = nothing set catalog = nothing set conn = nothing MsgBox "Database created, populated, and read!",,wscript.scriptname
VBScript Examples
VBScript Examples
End Function
VBScript Examples
Element 1</DataElement1> Element 2</DataElement2> Element 1</DataElement1> Element 2</DataElement2> Element 1</DataElement1> Element 2</DataElement2>
VBScript Examples
VBScript Examples
DispOneRec c.DriverName = "Maria Schriver" c.DriverLNo = "CA123457" c.IncreaseCitations(2) DispOneRec MsgBox "Complete! I wrote " & intRecNum & " records.",,WScript.scriptname Sub DispOneRec intRecNum = intRecNum + 1 Msg = "Driver name=" & c.Drivername & ";" & vbcrlf Msg = Msg & "Driver License No.=" & c.DriverLNo & ";" & vbcrlf Msg = Msg & "No. of citations=" & c.CitationCount & vbcrlf MsgBox Msg,,WScript.Scriptname c.ClearCitationCount End sub
VBScript Examples
Duration
This script asks the user for a start time and an end time, and will display the difference. Features: Date and time difference calculation
' Duration - Calculate how long something has taken Option Explicit Dim tmStart, tmEnd, tmDur tmStart = trim(InputBox("What is the start time?","Start Time",FormatDateTime(now(),4))) tmEnd = trim(InputBox("What is the end time?","End Time")) If (TmStart = null) or (TmStart = "") or (TmEnd = null) or (TmEnd = "") then MsgBox "Please enter a valid non-blank time",,"Error!" wscript.quit end if tmDur = DateDiff("n",tmStart,tmEnd) If tmDur < 0 then MsgBox "The start time should be earlier than the end time." & vbcrlf & "Please try again.",,"Error!" wscript.quit end if MsgBox "That task took " & tmDur & " minutes.",,wscript.scriptname
VBScript Examples
MyRec("Col22") MyRec("Col23") MyRec("Col28") MyRec("Col30") end if next = = = = objWorksheet.Cells(row,22).Value objWorksheet.Cells(row,23).Value objWorksheet.Cells(row,28).Value objWorksheet.Cells(row,30).Value
'msg = "I found " & Row & " rows in the spreadsheet and " 'msg = msg & ctrArrayElems & " GroupIDs" 'MsgBox(Msg) objExcel.Application.quit Set objWorksheet = nothing Set objWorkbook = nothing Set objExcel = nothing '*------------* '* Count the records in the recordset '*------------* 'MyRec.movefirst 'i = 0 'while not MyRec.eof ' i = i + 1 ' MyRec.Movenext 'wend 'MsgBox ("Before deduping, I saw " & i & " records") '*------------* '* Now remove duplicates from the recordset '*------------* Dim Lastrec, ThisRec LastRec = "" myrec.sort = "Col19,Col18" MyRec.movefirst while not MyRec.eof ThisRec = trim(MyRec("Col19")) & trim(MyRec("Col18")) If LastRec = ThisRec then myrec.delete else LastRec = ThisRec end if MyRec.Movenext wend '*------------* '* Count the records in the recordset '*------------* MyRec.movefirst Dim Numrows : numRows = 0 while not MyRec.eof numRows = numRows + 1 MyRec.Movenext wend 'MsgBox ("After deduping, I saw " & numRows & " records") '*------------* '* Now create a Word table with the fields
VBScript Examples
'*------------* Dim objWord, objDoc, objRange, objTable Const NUMBER_OF_COLUMNS = 7 Set objWord = CreateObject("Word.Application") objWord.Visible = True Set objDoc = objWord.Documents.Add() ' Create a NEW document Set objRange = objDoc.Range() objDoc.Tables.Add objRange, numRows, NUMBER_OF_COLUMNS Set objTable = objDoc.Tables(1) ' Work with the first (and only) table objTable.Cell(1, 1).Range.Text = "STIG ID" objTable.Cell(1, 2).Range.Text = "VULID" objTable.Cell(1, 3).Range.Text = "ID10" objTable.Cell(1, 4).Range.Text = "Severity" objTable.Cell(1, 5).Range.Text = "Weight" objTable.Cell(1, 6).Range.Text = "FixRef" objTable.Cell(1, 7).Range.Text = "System" objTable.Cell(2, objTable.Cell(2, objTable.Cell(2, objTable.Cell(2, objTable.Cell(2, objTable.Cell(2, objTable.Cell(2, 1).Range.Text 2).Range.Text 3).Range.Text 4).Range.Text 5).Range.Text 6).Range.Text 7).Range.Text = = = = = = = "Col "Col "Col "Col "Col "Col "Col S" R" U" V" W" AB" AD"
MyRec.movefirst Row = 3 while not MyRec.eof objTable.Cell(row, 1).Range.Text objTable.Cell(row, 2).Range.Text objTable.Cell(row, 3).Range.Text objTable.Cell(row, 4).Range.Text objTable.Cell(row, 5).Range.Text objTable.Cell(row, 6).Range.Text objTable.Cell(row, 7).Range.Text MyRec.Movenext : row = row + 1 wend objTable.AutoFormat(16) MsgBox("Your Word table is ready!") Wscript.quit
= = = = = = =
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objIpFile = objFSO.OpenTextFile(IPPath) Set objOPFile = objFSO.CreateTextFile(OPPath) CtrIP = 0 : CtrOP = 0 Do Until objIPFile.AtEndOfStream ipLine = RTrim(objIPFile.ReadLine) : CtrIP = CtrIP + 1 If (left(IpLine,1) = "<") or _ (instr(1,IpLine,"<html>",vbTextCompare) > 0) or _ (instr(1,IpLine,"<tt>",vbTextCompare) > 0) or _ (instr(1,IpLine,"<td w",vbTextCompare) > 0) then ctrSkipped = ctrSkipped + 1 else objOPFile.writeline(iPLine) : CtrOP = CtrOP + 1 end if loop objIPfile.Close() objOPfile.Close() Msg = "" Msg = Msg & "IpFile: " & IPPath & vbCRLF Msg = Msg & "OpFile: " & OPPath & vbCRLF Msg = Msg & CtrIP & " records read. " & vbCRLF Msg = Msg & CtrSkipped & " records skipped." & vbCrLF Msg = Msg & CtrOP & " records written." & vbCrLF MsgBox Msg,,Wscript.Scriptname Set objFSO = nothing Set objIPFile = nothing Set objOPFile = nothing
VBScript Examples
VBScript Examples
Snippets
Change the Format of a Column
This snippet will set the width of a column, and change the format (of an entire column) so it wraps the text.
objExcel.Columns(2).ColumnWidth = 60 objWorksheetO.Cells(oRow,2).Value = (text field) set objRange = objExcel.Range("B1").EntireColumn objRange.Wraptext = true
VBScript Examples
Notes
Converting VBA to VBS
Many times, you can find exactly what you want by searching the web. Sometimes, however, the exact combination of features that you want to use arent readily available in an example form. I have found that ONE way to accomplish what you want to accomplish in VBScript is to write a macro, and then convert that macro from VBA to VBS. Usually, this entails only syntactical changes. For example, the following VBA code:
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldPage Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldNumPages