WshShell對象實例(VBA)

shShell對象實例(VBA)

 

WshSell作爲WSH對象一個組成部分,主要可以實現如下功能:

 

1.   在本地運行程序

2.   操縱註冊表內容。

3.   創建快捷方式

4.   訪問系統文件夾

5.   操縱環境變量(如 WINDIR、PATH 或 PROMPT)

 

先來看一下WshShell都有哪些方法和屬性

 

AppActivate

方法

激活一應用程序窗口

CreateShortcut

方法

創建並返回 WshShortcut 對象。

Exec

方法

執行一個外部命令,返回一個對象。

ExpandEnvironmentStrings

方法

擴展 PROCESS 環境變量並返回結果字符串。

LogEvent

方法

寫入事件查看器日誌

Popup

方法

顯示包含指定消息的消息窗口。

RegDelete

方法

從註冊表中刪除指定的鍵或值。

RegRead

方法

從註冊表中返回指定的鍵或值。

RegWrite

方法

在註冊表中設置指定的鍵或值。

Run

方法

創建新的進程,該進程用指定的窗口樣式執行指定的命令。

SendKeys

方法

發送按鍵消息

CurrentDirectory

屬性

當前目錄

Environment

屬性

返回 WshEnvironment 集合對象。

SpecialFolders

屬性

使用 WshSpecialFolders 對象提供對Windows shell 文件夾的訪問,如桌面文件夾,開始菜單文件夾和個人文檔文件夾。

 

下面,我們進入VBE來進行WshShell對象代碼的實例練習。

 

先在工具->引用中建立對WshShell對象的引用

 

 

2012年06月16日 - V.S.林 - V.S.林 V.S.EXCEL V視覺

 

代碼1

 

Sub testAppActivate()

  Dim WshShell As Object

  Set WshShell = CreateObject("WScript.Shell")

  WshShell.AppActivate ("無標題 - 記事本")

End Sub

 

運行結果:將Windows("無標題 - 記事本")設爲當前活動窗口。

 

代碼2

 

Sub testCreateShortcut()

 

  Dim WshShell As Object, oShellLink As Object, oUrlLink As Object

  Set WshShell = CreateObject("WScript.Shell")

 

  Set oShellLink = WshShell.CreateShortcut("F:\test.lnk")

  oShellLink.TargetPath = ThisWorkbook.FullName

  oShellLink.Save

 

  Set oUrlLink = WshShell.CreateShortcut("F:\VSEXCEL.URL")

  oUrlLink.TargetPath = "http://visardwl.blog.163.com"

  oUrlLink.Save

    

End Sub

 

運行結果:在F盤根目錄下建立兩個超鏈接

          test.lnk 指向 包含代碼的工作簿

          VSEXCEL.RUL 指向 網站http://visardwl.blog.163.com

 

代碼3

 

Sub testExec()

  Dim WshShell As Object

  Set WshShell = CreateObject("WScript.Shell")

  WshShell.Exec "calc"

End Sub

 

運行結果:打開Windows操作系統自帶計算器。

 

代碼4

 

Sub testPopup()

  Dim WshShell As Object

  Set WshShell = CreateObject("WScript.Shell")

  WshShell.Popup "2秒後自動關閉", 2, "提示"

End Sub

 

運行結果:彈出消息窗,2秒種後自動關閉。

 

代碼5

 

Sub testRun()

  Dim WshShell As Object

  Set WshShell = CreateObject("WScript.Shell")

  WshShell.Run "F:\123.txt", 3

End Sub

 

運行結果:打開F盤根目錄下名爲123.txt的文本文件,並最大化顯示。

 

Sub testRun()

  Dim WshShell As Object

  Set WshShell = CreateObject("WScript.Shell")

  WshShell.Run "F:\fly.exe"

End Sub

 

運行結果:運行F盤根目錄下可執行文件fly.exe

 

代碼6

 

Sub testSendKeys()

  Dim WshShell As Object

  Set WshShell = CreateObject("WScript.Shell")

  WshShell.SendKeys "^{ESC}u"

End Sub

 

運行結果:發送按鍵信息,Ctrl+ESC再按U,相當於點開始,再點關閉計算機


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章