1. Trang chủ
  2. » Công Nghệ Thông Tin

Microsoft WSH and VBScript Programming for the Absolute Beginner Part 49 doc

10 81 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 205,09 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Using the properties and methods associ-ated with the lower-level objects, you can automate any number of Excel tasks.. TerminateScript ‘Procedure Section Function CreateAndHideNewSheet

Trang 1

‘Save the new document to C:\Temp

objWord.ActiveDocument.SaveAs(“c:\Temp\TextFile.doc”)

End Function

Function CloseDocAndEndWord()

‘Use the Document object’s Close() method to close the document

objWord.ActiveDocument.Close()

‘Terminate Word

objWord.Quit()

End Function

Function TerminateScript()

WScript.Quit() ‘Terminate script execution

End Function

Figure A.2 shows how the Word document created by this script looks after it has been created.

Figure A 2

Automating the

creation of a

Word document

Trang 2

Automating the Creation of Microsoft Excel Spreadsheets

As you probably expect, the Excel object model is very similar to the Word object model At the top of its model is the Application object, which is automatically instantiated when Excel is started Using the properties and methods associated with the Applicationobject, you can access lower-level objects and collections Using the properties and methods associ-ated with the lower-level objects, you can automate any number of Excel tasks.

The following script provides you with a working example of how to use VBScript and the WSH to automate the creation of an Excel spreadsheet Refer to comments embedded throughout the script for more detailed information about the Excel object model.

‘*************************************************************************

‘Script Name: ExcelObjectModelDemo.vbs

‘Author: Jerry Ford

‘Created: 11/13/04

‘Description: This script demonstrates how to use VBScript to interact

‘ with the Microsoft Excel object model

‘*************************************************************************

‘Initialization Section

Option Explicit

On Error Resume Next

Dim objExcel ‘Used to establish a reference to Excel Application object

Set objExcel = WScript.CreateObject(“Excel.Application”)’Instantiate Excel

‘Main Processing Section

CreateAndHideNewSheet()

WriteExcelData()

SaveExcelSheet()

Trang 3

TerminateScript()

‘Procedure Section

Function CreateAndHideNewSheet()

‘Visible is a property of the Application object It cab be used to

‘prevent Excel from appearing as the script executes

objExcel.Visible = False

‘WorkBooks is a collection Add() is a method belonging to the

‘WorkBooks collection that opens a new empty spreadsheet

objExcel.WorkBooks.Add

End Function

Function WriteExcelData()

‘Use the Columns object’s ColumnWidth property to set column widths

objExcel.Columns(1).ColumnWidth = 15

objExcel.Columns(2).ColumnWidth = 35

objExcel.Columns(3).ColumnWidth = 6

‘Use the Range object’s Select method to select a range of cells

objExcel.Range(“A1:C1”).Select()

‘Set the Font object’s Bold property

objExcel.Selection.Font.Bold = True

‘Use the Cells object’s Value property to enter text into the

‘spreadsheet

objExcel.Cells(1,1).Value = “Name”

objExcel.Cells(1,2).Value = “Description”

objExcel.Cells(1,3).Value = “Rating”

Trang 4

‘Enter additional text

objExcel.Cells(2,1).Value = “Hangman”

objExcel.Cells(2,2).Value = “A word guessing game”

objExcel.Cells(2,3).Value = “5”

‘Enter additional text

objExcel.Cells(3,1).Value = “TicTacToe”

objExcel.Cells(3,2).Value = “Two player board game”

objExcel.Cells(3,3).Value = “5”

‘Enter additional text

objExcel.Cells(4,1).Value = “Blackjack”

objExcel.Cells(4,2).Value = “Player versus computer card came”

objExcel.Cells(4,3).Value = “5”

End Function

Function SaveExcelSheet()

‘Use the ActiveWorkBook property to reference the current WorkBook

‘Use the WorkBook object’s SaveAs() method to save the WorkBook

objExcel.ActiveWorkBook.SaveAs(“C:\Temp\ExcelFile.xls”)

End Function

Function CloseSheetAndEndExcel()

‘Use the WorkBook object’s Close() method to close the spreadsheet

objExcel.ActiveWorkBook.Close()

objExcel.Quit() ‘Terminate Excel

End Function

Function TerminateScript()

Trang 5

WScript.Quit() ‘Terminate script execution

End Function

Figure A.3 shows how the Word document created by this script appears after it has been created.

Automating the Execution of Third-Party Applications

Using VBScript and the WSH, you can automate the functionality of any application that exposes its object model However, not every Windows application does this Instead, many applications provide the capability to automate function via built-in command line inter-faces, meaning that you can send commands to the application that the application then processes A good example of one such application is WinZip For example, you can send command to WinZip by executing its WinZip32.exeprogram and passing it arguments The following VBScript demonstrates how to create a script that automates the creation of a new Zip file named VBScripts.Zip The syntax for WinZip32.exeis embedded as comments within the script.

‘*************************************************************************

‘Script Name: WinZipDemo.vbs

‘Author: Jerry Ford

‘Created: 11/13/04

‘Description: This script creates a new Zip file made up of all the

‘ VBScripts found in the C:\VBScriptsGames folder

‘*************************************************************************

Figure A 3

Automating

the creation of

an Excel

spreadsheet

Trang 6

‘Initialization Section

Option Explicit

Dim intUserResponse, objWshShl

‘Instantiate the Windows Shell Object

Set objWshShl = WScript.CreateObject(“WScript.Shell”)

‘Main Processing Section

PromptForPermission()

If intUserResponse = vbYes Then

CreateZipFile()

End If

TerminateScriptExecution()

‘Procedure Section

Function PromptForPermission() ‘Ask user for permission to continue

intUserResponse = MsgBox(“This script creates a ZIP file containing” & _

“ all the VBScripts found in C:\VBScriptGames.” & vbCrLf & vbCrLf & _

“Do you wish to continue?”, 36, “VBScript Zipper!”)

End Function

Function CreateZipFile() ‘Create the new Zip file

‘WINZIP32 Command Syntax:

‘WINZIP32 [-min] action [options] filename[.zip] files

‘ -min - Tells WinZip to run minimized

‘ action – Represents any one of the following arguments

Trang 7

‘ -a Create new Zip file

‘ -f Refresh existing archive

‘ -u Update an existing archive

‘ -m Move archive to specified location

‘ options - Optional arguments that include

‘ -r Add files and folders when adding to Zip file

‘ -p Include information about any added folders

‘ filename[.zip] – name of Zip file to be created

‘ files – names of file to be added to the Zip file

objWshShl.Run _

“WINZIP32 -a C:\Temp\VBScripts.zip D:\VBScriptGames\*.vbs”, 0, True

End Function

Function TerminateScriptExecution() ‘Terminate the script’s execution

WScript.Quit()

End Function

Trang 8

Built-In VBScript

Functions

B

V BScript provides an enormous collection of built-in functions as outlined

in Table B.1 You can use these functions in your VBScripts to shorten your development time and save yourself from having to reinvent the wheel.

VBScript Functions

Function Name Description

Abs Returns a number’s absolute value

Array Returns an array based on the supplied argument list

Asc Returns the ANSI code of the first letter in the supplied

argument Atn Inverse trigonometric function that returns the arctangent of the

argument CBool Converts an expression to a Boolean value and returns the result CByte Converts an expression to a variant subtype of Byte and returns

the result CCur Converts an expression to a variant subtype of Currency and

returns the result Cdate Converts an expression to a variant subtype of Date and returns

the result

TA B L E B 1 BU I LT- IN V B SC R I P T FU N C T I O N S

(continues)

Trang 9

Function Name Description

CDbl Converts an expression to a variant subtype of Double and returns the result Chr Returns a character based on the supplied ANSI code

Cint Converts an expression to a variant subtype of Integer and returns the result CLng Converts an expression to a variant subtype of Long and returns the result Cos Trigonometric function that returns the cosine of the argument

CreateObject Creates an automation object and returns a reference to it

CSng Converts an expression to a variant subtype of Single and returns the result Date Returns the current date

DateAdd Adds an additional time interval to the current date and returns the result DateDiff Compares two dates and returns the number of intervals between them DatePart Returns a portion of the specified date

DateSerial Returns a variant (subtype Date) based on the supplied year, month, and day DateValue Converts a string expression into a variant of type Date and returns the result Day Converts an expression representing a date into a number between 1 and 31

and returns the result Eval Returns the results of an evaluated expression

Exp Returns the value of an argument raised to a power

Filter Returns an array based on a filtered set of elements using supplied filter

criteria FormatCurrency Returns an expression that has been formatted as a currency value

FormatDateTime Returns an expression that has been formatted as a date or time value

FormatNumber Returns an expression that has been formatted as a numeric value

FormatPercent Returns an expression that has been formatted as a percentage (including the

accompanying %) GetLocale Returns the locale ID

GetObject Returns a reference for an automation object

GetRef Returns a reference for a procedure

Hex Returns a hexadecimal string that represents a number

Hour Returns a whole number representing an hour in a day (0 to 23)

InputBox Returns user input from a dialog box

TA B L E B 1 BU I LT- IN V B SC R I P T FU N C T I O N S (C O N T I N U E D)

Trang 10

Function Name Description

InStr Returns the starting location of the first occurrence of a substring within

a string InStrRev Returns the ending location of the first occurrence of a substring within a

string Int Returns the integer portion from the supplied number

IsArray Returns a value of True or False, depending on whether a variable is an array IsDate Returns a value of True or False, depending on whether an expression is

properly formatted for a data conversion IsEmpty Returns a value of True or False, depending on whether a variable is

initialized IsNull Returns a value of True or False, depending on whether an expression is set

to Null IsNumeric Returns a value of True or False, depending on whether an expression

evaluates to a number IsObject Returns a value of True or False, depending on whether an expression

has a valid reference for an automation object Join Returns a string that has been created by concatenating the contents of

an array Lbound Returns the smallest possible subscript for the specified array dimension

Lcase Returns a lowercase string

Left Returns characters from the left side of a string

Len Returns a number or string’s character length

LoadPicture Returns a picture object

Log Returns the natural log of the specified argument

LTrim Trims any leading blank spaces from a string and returns the result

Mid Returns a number of characters from a string based on the supplied start and

length arguments Minute Returns a number representing a minute within an hour in range of 0 to 59 Month Returns a number representing a month within a year in the range of 1 to 12 MonthName Returns a string containing the name of the specified month

MsgBox Returns a value specifying the button users click in a dialog box

Now Returns the current date and time

TA B L E B 1 BU I LT- IN V B SC R I P T FU N C T I O N S (C O N T I N U E D)

(continues)

Ngày đăng: 03/07/2014, 18:20

TỪ KHÓA LIÊN QUAN