VBScript的常用COM對(duì)象列表
本帖最后由 ghouse 于 2014-11-29 19:01 編輯 有時(shí)會(huì)在論壇中看到一些很妙的寫法,有許多其實(shí)是vbs的原有功能 他們會(huì)在腳本中創(chuàng)建一些對(duì)象來實(shí)現(xiàn)某些特定的功能。 而其實(shí)我們都知道,從按鍵8之後,就已經(jīng)完整支持vbs了, 可是在按鍵裡面的教程對(duì)於vbs比較特殊的方式,很難找到 所以啦!~~~~就把一些比較常用的vbs的功能寫下來囉!~~順便自己研究研究 下邊是經(jīng)常在VBScript中用到的對(duì)象列表: Set objEmail = CreateObject("CDO.Message" ) Set objIE = CreateObject("InternetExplorer.Application" ) Set objInet = CreateObject("InetCtls.Inet.1" ) Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1" ) Set objExcel =CreateObject("Excel.Application" ) Set objOutlook = CreateObject("Outlook.Application" ) Set objPpt = CreateObject( " PowerPoint.Application") Set objWord = CreateObject("Word.Application" ) Set objCal = CreateObject("MSCAL.Calendar" ) Set objQPro = CreateObject("QuattroPro.PerfectScript") Set objWP = CreateObject("WordPerfect.PerfectScript」") Set objConn = CreateObject("ADODB.Connection" ) Set objRecSet = CreateObject("ADODB.Recordset" ) Set objDic = CreateObject("Scripting.Dictionary") Set objFSO = CreateObject("Scripting.FileSystemObject" ) Set wshNetwork = CreateObject("WScript.Network" ) Set wshShell = CreateObject("WScript.Shell") Set objRandom = CreateObject("System.Random" ) Set objArrList = CreateObject("System.Collections.ArrayList") Set objSortList = CreateObject("System.Collections.SortedList" ) Set xmlDoc = CreateObject( "Microsoft.XmlDom") Set xml2Doc = CreateObject("Msxml2.DOMDocument.5.0") Set objiTunes = CreateObject("iTunes.Application") Set objPlayer = CreateObject("WMPlayer.OCX" ) Set objWMPlayer = CreateObject("WMPlayer.OCX.7" ) Set objReal = CreateObject( "rmocx.RealPlayerG2 Control.1") Set objFSDialog = CreateObject("SAFRCFileDlg.FileSave") Set objFODialog = CreateObject("SAFRCFileDlg.FileOpen" ) Set objDialog = CreateObject("UserAccounts.CommonDialog") Set SOAPClient = CreateObject("MSSOAP.SOAPClient") Set objWOL = CreateObject("UltraWOL.ctlUltraWOL") Set objSearcher = CreateObject("Microsoft.Update.Searcher") Set objShell = CreateObject("Shell.Application") SetobjDeviceReplay=CreateObject("Mercury.DeviceReplay") 以下是示例演示: [hr] 描述:創(chuàng)建和返回一個(gè)自動(dòng)化對(duì)象的引用 語法: CreateObject(class) class 參數(shù)使用了語法servername.typename servername: 提供對(duì)象的應(yīng)用程序的名稱 typename: 對(duì)象的類型或類 說明:每個(gè)自動(dòng)化對(duì)象至少提供一種對(duì)象類型。例如,一個(gè)文字處理程序可能會(huì)提供一個(gè)應(yīng)用程序?qū)ο?,一個(gè)文件對(duì)象和一個(gè)工具欄對(duì)象。要?jiǎng)?chuàng)建一個(gè)自動(dòng)化對(duì)象,需要把CreateObject創(chuàng)建的對(duì)象變量賦給一個(gè)對(duì)象變量。 示例1: 創(chuàng)建一個(gè)Excel應(yīng)用程序?qū)ο?(「Excel.Application」 ) //關(guān)閉桌面上打開的所有Excel表格 Systemutil.CloseProcessByName"excel.exe" //創(chuàng)建一個(gè)新的Excel對(duì)象 Set Excel =CreateObject("Excel.Application") //打開Excel表格 Set SExcelSheet =Excel.Workbooks.Open("C:\Users\djiao\Documents\ella\CR_Report.xlsx") //設(shè)置表格可見 SExcelSheet.Application.visible=true //關(guān)閉任何Excel的錯(cuò)誤窗口或提示信息 Excel.DisplayAlerts = False //重命名並保存Excel到不同的路徑下 SExcelSheet.SaveAs"C:\BaseLine.xlsx" //關(guān)閉Excel的表格 SExcelSheet.Close //退出Excel應(yīng)用程序 Excel.Quit 示例3A: 創(chuàng)建文件系統(tǒng)對(duì)象 (「Scripting.FileSystemObject」) //將要?jiǎng)?chuàng)建的文件夾的存放路徑 strDrive = "D:\DATA" //要?jiǎng)?chuàng)建的文件夾名稱 strfoldername= "New Folder" //獲取文件夾的絕對(duì)路徑 strPath=strDrive&"\"&strfoldername //創(chuàng)建 FileSystemObject 對(duì)象Set objFSO =CreateObject("Scripting.FileSystemObject") //文件夾不存在時(shí),創(chuàng)建文件夾If NOT objFSO.FolderExists(strPath) Then objFSO.CreateFolder strPath End If //釋放文件系統(tǒng)對(duì)象Set objFSO = nothing 示例3B: //Get the name of file extention msgbox GetAnExtension("C:\ProgramFiles (x86)\HP\QuickTest Professional\bin\QTPro.exe") Function GetAnExtension(DriveSpec) Dimfso Setfso = CreateObject("Scripting.FileSystemObject") GetAnExtension= fso.GetExtensionName(Drivespec) Setfso = nothing End Function 示例4: 郵件發(fā)送對(duì)象(「CDO.Message」) Dim objMessage //創(chuàng)建郵件發(fā)送對(duì)象 Set objMessage =CreateObject("CDO.Message") //給郵件添加主題 objMessage.Subject = "QTP Results –Automated Testing" objMessage.From ="QTPTesting@address.com" ' 改為你自己的郵箱地址 objMessage.To = "your@email.com"'收件人郵箱地址 objMessage.CC = "your@email.com"'CC to email id //郵件內(nèi)容objMessage.TextBody ="N.B. – Please DoNot Reply This Message Directly." //添加附件objMessage.AddAttachment"D:\Data\file.text" //這部分提供了遠(yuǎn)程SMTP server的配置信息objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing")= 2 //設(shè)置SMTP server的name或IP objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver")= "smtp.163.com" //服務(wù)器端口號(hào)(通常是 25) objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport")= "someserver.domain.com" objMessage.Configuration.Fields.Update //發(fā)送郵件objMessage.Send //釋放郵件對(duì)象Set objMessage = nothing 示例5: 創(chuàng)建WshShell對(duì)象 (「Wscript.Shell」) 說明:WScript.Shell是WshShell對(duì)象的ProgID,創(chuàng)建WshShell對(duì)象可以運(yùn)行程序、操作註冊(cè)表、創(chuàng)建快捷方式、訪問系統(tǒng)文件夾、管理環(huán)境變量。 Set WshShell =CreateObject("Wscript.Shell") Dim Response //顯示一個(gè)帶有yes和no的消息框 Response = MsgBox(" Please Select yourchoice as 『Yes' or 『No'.", vbYesNo) If Response = vbYes Then //消息框會(huì)顯示3秒鐘 WshShell.Popup"You Have Been Selected 「Yes」. Please wait.", 3, "YourSelection" Else //消息框會(huì)顯示5秒 WshShell.Popup"You Have Been Selected 「No」", 5, "Your Selection" End If Set WshShell = nothing 示例6A: Mercury.DeviceReplay對(duì)象 (「Mercury.DeviceReplay」) 說明:這個(gè)對(duì)象用來模擬鼠標(biāo)的單擊和移動(dòng)、鍵盤輸入等。使用該對(duì)象前,需要保證鍵盤狀態(tài)正確,如NUMLOCK是否打開等,DeviceReplay不能檢測(cè)鍵盤狀態(tài)。 //定義坐標(biāo) Dim abs_x, abs_y abs_x = 200 abs_y = 200 //創(chuàng)建Mercury.DeviceReplay對(duì)象 Set objMercuryMouse = CreateObject("Mercury.DeviceReplay") //移動(dòng)鼠標(biāo)到指定坐標(biāo) objMercuryMouse.MouseMove abs_x,abs_y //鼠標(biāo)左擊 objMercuryMouse.MouseClick abs_x,abs_y,LEFT_MOUSE_BUTTON //釋放Mercury.DeviceReplay對(duì)象 Set objMercuryMouse = nothing 示例7: 字典對(duì)象(「Scripting.Dictionary」) //創(chuàng)建dictionary對(duì)象 Dim d Set d =CreateObject("Scripting.Dictionary") //給dictionary添加key和value d.Add "a","Athens" d.Add "b", "Belgrade" d.Add "c", "Cairo" //獲取所有的item a = d.Items For i = 0 To d.Count -1 ' Iterate thearray. s =s & a(i) & VBCrLF ' Create return string. Next print s //根據(jù)key獲取item print d.Item("a") //釋放dictionary對(duì)象 Set d = nothing Example 8A: Connection對(duì)象,數(shù)據(jù)集對(duì)象("ADODB.Connection")/("ADODB.Recordset") Function database() v_DBInstance= "RENPCRT8" v_MHXMLDBPwd= "grudge" v_MHXMLDBSchema= "Mhxmledit" //創(chuàng)建數(shù)據(jù)庫連接對(duì)象和數(shù)據(jù)集對(duì)象 ConstadOpenStatic = 3 ConstadLockOptimistic = 3 ConstadUseClient = 3 SetobjConnection = CreateObject("ADODB.Connection") SetobjRecordset = CreateObject("ADODB.Recordset") objConnection.Open"DRIVER={Microsoft ODBC for Oracle};UID="& v_MHXMLDBSchema&" ; PWD="& v_MHXMLDBPwd & ";SERVER="&v_DBInstance &」;" objRecordset.CursorLocation= adUseClient objRecordset.CursorType= adopenstatic objRecordset.LockType= adlockoptimistic objRecordset.Source= "select SOP from MHXML.FIRMS_STG where org_id in 681915" ObjRecordset.ActiveConnection= ObjConnection //執(zhí)行查詢語句 ObjRecordset.Open IfObjRecordset.recordcount>0 then Field1= ObjRecordset("SOP").Value msgboxField1 Endif End Function Example 8B: (「Database connection withoutADODB.Connection Object」) 此方法可以從數(shù)據(jù)庫中獲取值為空或者null的數(shù)據(jù) Function GetAttorneyInfo(InField,ALid) v_DBInstance="RENPCRT8" v_MHXMLDBPwd="creek" v_MHXMLDBSchema="lbmgradmin" GetAttorneyInfo="" //創(chuàng)建數(shù)據(jù)庫連接 MHXMLconnection_string="DRIVER={MicrosoftODBC for Oracle};UID="& v_MHXMLDBSchema &" ; PWD="&v_MHXMLDBPwd &";SERVER=" & v_DBInstance &";" isMHXMLConnected= db_connect ( MHXMLConnection ,MHXMLconnection_string ) IfisMHXMLConnected=0Then '從表中獲取數(shù)據(jù) v_Exe_SQL2="Selectlength(NVL(" & InField & ",'Data Not Found')) fromlbmgradmin.ilv_vw where ilisting_id = " & ALid setRecSet_SOPInfo_LEN = db_execute_query( MHXMLConnection , v_Exe_SQL2 ) d_SOPInfo_Length= db_get_field_value( RecSet_SOPInfo_LEN , 0 , 0 ) v_Exe_SQL2="selectsubstr(to_char(NVL(" & InField & ",'Data NotFound')),1," & d_SOPInfo_Length & ") from lbmgradmin.ilv_vwwhere ilisting_id = " & ALid setRecSet_SOPInfo = db_execute_query( MHXMLConnection , v_Exe_SQL2 ) RowCnt= db_get_rows_count( RecSet_SOPInfo ) IfRowCnt=1Then d_SOPInfo=db_get_field_value(RecSet_SOPInfo , 0 , 0 ) else datatable.SetCurrentRow(1) d_SOPInfo=db_get_field_value(RecSet_SOPInfo , 0 , 0 ) EndIf else EndIf GetAttorneyInfo=d_SOPInfo End Function //打開數(shù)據(jù)庫連接 Function db_connect( byRef curSession,connection_string) Dimconnection onerror Resume next //創(chuàng)建數(shù)據(jù)庫連接對(duì)象 setconnection = CreateObject("ADODB.Connection") IfErr.Number <> 0 then db_connect="Error # " & CStr(Err.Number) &" " &Err.Description err.clear ExitFunction EndIf connection.Openconnection_string IfErr.Number <> 0 then db_connect="Error # " & CStr(Err.Number) & " " &Err.Description err.clear ExitFunction EndIf setcurSession=connection db_connect=0 End Function //關(guān)閉數(shù)據(jù)庫連接 Function db_disconnect( byRef curSession ) curSession.close setcurSession = Nothing End Function //執(zhí)行查詢語句 Function db_execute_query ( byRefcurSession , SQL) setrs = curSession.Execute( SQL ) setdb_execute_query = rs End Function //獲取數(shù)據(jù)集的行數(shù) Function db_get_rows_count( byRef curRS ) dimrows rows= 0 curRS.MoveFirst DoUntil curRS.EOF rows= rows+1 curRS.MoveNext Loop db_get_rows_count= rows End Function Example 8C: (「ADODB.Connection」)/(「ADODB.Recordset」) 此示例從Excel表單中獲取數(shù)據(jù) //創(chuàng)建數(shù)據(jù)庫連接對(duì)象 Dim Get_Field set connectToDB =CreateObject("ADODB.Connection") connectToDB.Provider ="Microsoft.Jet.OLEDB.4.0" connectToDB.Properties("ExtendedProperties").Value = "Excel 8.0" connectToDB.Open "D:\Documents andSettings\pauldx\Desktop\Data.xls" strQuery="Select Age from [Data$]WHERE Name ='Joli'" //創(chuàng)建數(shù)據(jù)集對(duì)象 Set rsRecord =CreateObject("ADODB.Recordset") rsRecord.Open strQuery,connectToDB,1,1 If rsRecord.RecordCount>0 Then fori= 1 to rsRecord.RecordCount Get_Field=rsRecord.Fields(0) printGet_Field rsRecord.movenext next Else Get_Field="FieldNot Present" End If Example 9: ("AcroExch.App"/"AcroExch.AVDoc") 此段代碼可以從pdf 文件中搜索Software單詞 備註:這段代碼只有當(dāng)你安裝了acrobat 專業(yè)版安裝的時(shí)候才可以使用。如果只安裝了adobe 閱讀器的標(biāo)準(zhǔn)版,你會(huì)看到如下報(bào)錯(cuò)「ActiveX component can't create object: 『AcroExch.PDDoc」」 Option Explicit Dim accapp, acavdocu Dim pdf_path, bReset, Wrd_count pdf_path="C:\test.pdf" //創(chuàng)建AcroExch i應(yīng)用程序?qū)ο?br> Setaccapp=CreateObject("AcroExch.App") accapp.Show() //創(chuàng)建AVDoc對(duì)象 Setacavdocu=CreateObject("AcroExch.AVDoc") //打開PDF文件 If acavdocu.Open(pdf_path,"")Then acavdocu.BringToFront() bReset=1 : Wrd_count = 0 //查找,定位並高亮指定文本 Do Whileacavdocu.FindText("software", 1, 1, bReset) bReset=0: Wrd_count=Wrd_count+1 Wait 0, 200 Loop End If accapp.CloseAllDocs() accapp.Exit() msgbox "The word 'software' was found" & Wrd_count & "times" Set accap=nothing Set accapp=nothing Example 10: .Net 對(duì)象("DotNetFactory") 說明:DotNetFactory對(duì)象允許創(chuàng)建一個(gè).NET對(duì)象,並訪問其方法和屬性 //創(chuàng)建.Net的form對(duì)象 Dim var_CreateInstance Set var_CreateInstance =DotNetFactory.CreateInstance("System.Windows.Forms.Form","System.Windows.Forms") //顯示form var_CreateInstance.Show wait 2 //關(guān)閉form var_CreateInstance.Close //釋放.Net對(duì)象 Set var_CreateInstance = nothing? |
|