完美地將visual basic和office 辦公軟件結合起來。來自微軟公司VSTO小組的權威專家所編著。windows
全書共712頁,內容極其全面而深刻,猛一看,厚地猶如龐然大物。看完離大神就不遠了哦<^ . ^>!!!!!session
《VSTO開發指南》是2008年2月電子工業出版社出版的圖書,app
做者是(美國)Eric Carter Eric Lippert學習
實例1:從Excel程序到Excel表 書本中的內容(第7頁):this
程序清單1.1. 在Excel中從Application對象到Worksheetspa
Dim myWorkbooks As Excel.Workbooks = app.Workbooks Dim myWorkbook As Excel.Workbook = myWorkbooks.Item(1) Dim myWorksheets As Excel.Sheets = myWorkbook.Worksheets Dim myWorksheet As Excel.Worksheet myWorksheet = CType(myWorksheets.Item(1), Excel.Worksheet)
Visual basic 2013 中的控制檯應用程序:3d
實現目標:獲取第一個工做表的名稱。excel
實現步驟:項目——>添加引用——>程序集——>擴展——>Microsoft.Office.Interop.Excel——>肯定code
實例代碼:orm
Imports excel = Microsoft.Office.Interop.Excel Module Module1 Sub Main() Dim app As excel.Application = New excel.Application Dim myWorkbooks As excel.Workbooks = app.Workbooks Dim myWorkbook As excel.Workbook = myWorkbooks.Add() Dim myWorkbook1 As excel.Workbook = myWorkbooks.Item(1) Dim myWorksheets As excel.Sheets = myWorkbook1.Worksheets Dim myWorksheet As excel.Worksheet myWorksheet = CType(myWorksheets.Item(1), excel.Worksheet) MsgBox(myWorksheet.Name) End Sub End Module
也能夠爲代碼:
Imports excel = Microsoft.Office.Interop.Excel Module Module1 Sub Main() Dim app As excel.Application = New excel.Application Dim myWorkbooks As excel.Workbooks = app.Workbooks Dim myWorkbook As excel.Workbook = myWorkbooks.Add() Dim myWorksheet As excel.Worksheet myWorksheet = CType(myWorkbook.Worksheets.Item(1), excel.Worksheet) MsgBox(myWorksheet.Name) End Sub End Module
也能夠爲代碼:
Imports excel = Microsoft.Office.Interop.Excel Module Module1 Sub Main() Dim app As excel.Application = New excel.Application Dim myWorkbooks As excel.Workbooks = app.Workbooks Dim myWorksheet As excel.Worksheet myWorksheet = CType(myWorkbooks.Add().Worksheets.Item(1), excel.Worksheet) MsgBox(myWorksheet.Name) End Sub End Module
也能夠爲代碼:
Imports excel = Microsoft.Office.Interop.Excel Module Module1 Sub Main() Dim app As excel.Application = New excel.Application Dim myWorksheet As excel.Worksheet myWorksheet = CType(app.Workbooks.Add().Worksheets.Item(1), excel.Worksheet) MsgBox(myWorksheet.Name) End Sub End Module
實例效果:
簡化程序清單1.1中的代碼爲:
書中的內容:
Dim myWorksheet As Excel.Worksheet myWorksheet = CType(app.Workbooks.Item(1).Worksheets.Item(1), Excel.Worksheet)
編寫代碼:
Imports excel = Microsoft.Office.Interop.Excel Module Module1 Sub Main() Dim app As excel.Application = New excel.Application Dim myWorksheet As excel.Worksheet myWorksheet = CType(app.Workbooks.Add().Worksheets.Add(), excel.Worksheet) MsgBox(myWorksheet.Name) End Sub End Module
實例效果:
注:區分程序、工做簿、工做表的概念,程序就是咱們安裝的Excel,程序能夠建立多個工做簿,一個工做簿能夠建立多個工做表。咱們平時所說的Excel文件就是工做簿,而工做簿是要用程序來建立的。
實例1自續:建立Excel工做簿,再建立工做表,並在A1單元格中輸入內容「這是A1」
實例代碼:
Imports excel = Microsoft.Office.Interop.Excel Module Module1 Sub Main() Dim app As excel.Application = New excel.Application Dim myWorkbook As excel.Workbook Dim myWorksheet As excel.Worksheet app.Visible = True myWorkbook = app.Workbooks.Add() myWorksheet = CType(myWorkbook.Sheets.Add(), excel.Worksheet) myWorksheet.Cells(1, 1) = "這是A1" End Sub End Module
實例效果:
實例2:Excel表的count屬性和item屬性 書本中的內容(第7頁):
程序清單1.2 以整數或字符串索引形式使用count和item屬性對集合進行循環處理
Dim myWorkbooks As Excel.Workbooks = app.Workbooks Dim workbookCount As Integer = myWorkbooks.Count For i As Integer = 1 To workbookCount ' Get the workbook by its integer index Dim myWorkbook As Excel.Workbook = myWorkbooks.Item(i) ' Get the workbook by its string index Dim workbookName As String = myWorkbook.Name Dim myWorkbook2 As Excel.Workbook = _ myWorkbooks.Item(workbookName) MsgBox(String.Format("Workbook {0}", myWorkbook2.Name)) Next
實例代碼:
Imports excel = Microsoft.Office.Interop.Excel Module Module1 Sub Main() Dim app As excel.Application = New excel.Application Dim myWorkbook As excel.Workbook Dim myWorksheet As excel.Worksheet app.Visible = True myWorkbook = app.Workbooks.Add() myWorksheet = CType(myWorkbook.Sheets.Add(), excel.Worksheet) myWorksheet.Cells(1, 1) = "這是A1" Dim worksheetCount As Integer = myWorkbook.Worksheets.Count For i As Integer = 1 To worksheetCount Dim str As String str = myWorkbook.Worksheets.Item(i).Name '以整數做爲索引 MsgBox(str, , "獲取工做表名稱") Next For i As Integer = 1 To worksheetCount Dim str As String str = myWorkbook.Worksheets.Item("sheet" & i).Name MsgBox(str, , "獲取工做表名稱") '以字符串做爲索引 Next End Sub End Module
實例效果:
實例2自續:編輯工做表sheet2中D3單元格,並填入「我是醜醜」
Imports excel = Microsoft.Office.Interop.Excel Module Module1 Sub Main() Dim app As excel.Application = New excel.Application Dim myWorkbook As excel.Workbook 'Dim myWorksheet As excel.Worksheet app.Visible = True myWorkbook = app.Workbooks.Add() 'myWorksheet = CType(myWorkbook.Sheets.Add(, , 3,), Excel.Worksheet) '第3個參數表示添加多少工做表,這裏添加3個, Dim C4_sheet As excel.Worksheet = myWorkbook.Worksheets.Item("sheet2") '工做表的索引從0開始, C4_sheet.Cells(3, 4) = "我是醜醜" 'Cells(行,列),也就是D3單元格 這裏不能用range屬性代替,應爲range屬性是隻讀屬性 End Sub End Module
實例效果:
實例3:學習For each循環結構 書本內容(第8頁)
程序清單1.3 使用for each循環處理集合
Dim myWorkbooks As Excel.Workbooks = app.Workbooks For Each workbook As Excel.Workbook In myWorkbooks MsgBox(String.Format("Workbook {0}", workbook.Name)) Next
實例代碼;
Imports excel = Microsoft.Office.Interop.Excel Module Module1 Sub Main() Dim app As excel.Application = New excel.Application Dim myWorkbooks As excel.Workbooks = app.Workbooks Dim myWorkbook As excel.Workbook = myWorkbooks.Add() 'Dim myWorkbook As excel.Workbook = myWorkbooks.Add("D:\職工人員表.xls") For Each workbook As excel.Workbook In myWorkbooks MsgBox(String.Format("Workbook {0}", workbook.Name)) Next End Sub End Module
實例效果(不盡如人意):
改進實例:刪除工做表
實例代碼:
Imports excel = Microsoft.Office.Interop.Excel Module Module1 Sub Main() Dim app As excel.Application = New excel.Application Dim myWorkbook As excel.Workbook = app.ActiveWorkbook app.Visible = True myWorkbook = app.Workbooks.Add("E:\工做簿1") '"工做簿1.xls"是一個模板,至關另外新建了一個"工做簿11.xls"並打開了 Dim myCollection As New Collections.Generic.List(Of excel.Worksheet) For Each Name As excel.Worksheet In myWorkbook.Worksheets myCollection.Add(Name) Next For Each name As excel.Worksheet In myCollection name.Delete() Next End Sub End Module
實例效果:
實例4:刪除對象用集合 書本內容(8頁)
程序清單1.4 刪除對象時使用另外一個集合
Dim myWorkbook As Excel.Workbook = app.ActiveWorkbook Dim myCollection As New Collections.Generic.List(Of Excel.Name) For Each name As Excel.Name In myWorkbook.Names myCollection.Add(name) Next For Each name As Excel.Name In myCollection name.Delete() Next
注:代碼中的Excel.Name並不字符串,而是一個對象。
實例代碼:
Imports excel = Microsoft.Office.Interop.Excel Module Module1 Sub Main() Dim app As excel.Application = New excel.Application Dim myWorkbook As excel.Workbook = app.ActiveWorkbook app.Visible = True myWorkbook = app.Workbooks.Add("E:\工做簿1") '"工做簿1.xls"是一個模板,至關另外新建了一個"工做簿11.xls"並打開了 Dim myCollection As New Collections.Generic.List(Of excel.Range) For Each Name As excel.Range In myWorkbook.Worksheets("Sheet1").Range("A1:D5") '因爲是刪除,因此下面的行會自動向上縮進 myCollection.Add(Name) Next For Each name As excel.Range In myCollection name.Delete() '因爲是刪除,因此下面的行會自動向上縮進 Next End Sub End Module
實例效果:
實例7:Word的application判斷CapsLock屬性值,書本第9頁。
注:從實例7開始了Word,因此在引用裏要添加「Microsoft.Office.Interop.Word」
程序清單1.5 返回值類型的屬性:Word應用程序對象上的布爾型CapsLock屬性
If app.CapsLock Then MsgBox("CapsLock is on") Else MsgBox("CapsLock is off") End If
實例代碼:
Imports word = Microsoft.Office.Interop.Word Module Module1 Sub Main() Dim app As word.Application = New word.Application If app.CapsLock Then MsgBox("CapsLock is on") Else MsgBox("CapsLock is off") End If End Sub End Module
實例效果:
實例7:判斷word文檔是最大化、最小化仍是常規化,書本第11頁
程序清單1.6 返回枚舉的屬性:Word應用程序對象上的windowstate屬性
Select Case app.WindowState Case Word.WdWindowState.wdWindowStateMaximize MsgBox("Maximized") Case Word.WdWindowState.wdWindowStateMinimize MsgBox("Minimized") Case Word.WdWindowState.wdWindowStateNormal MsgBox("Normal") End Select
實例代碼:
Imports word = Microsoft.Office.Interop.Word Module Module1 Sub Main() Dim APP As word.Application = New word.Application Dim myDocuments As word.Documents = APP.Documents Dim myDocument As word.Document = myDocuments.Add() APP.Visible = True Select Case app.WindowState Case word.WdWindowState.wdWindowStateMaximize MsgBox("Maximized") Case word.WdWindowState.wdWindowStateMinimize MsgBox("Minimized") Case word.WdWindowState.wdWindowStateNormal MsgBox("Normal") End Select End Sub End Module
實例效果:
實例7:活動文檔(ActiveDocument),書本第11頁
程序清單1.7 返回對象模型中的另外一個對象屬性:Word應用程序對象中的ActiveDocument屬性
Dim myDocument As Word.Document = app.ActiveDocument MsgBox(myDocument.Name)
實例代碼:
Imports word = Microsoft.Office.Interop.Word Module Module1 Sub Main() Dim APP As word.Application = New word.Application Dim myDocuments As word.Documents = APP.Documents Dim myDocument As word.Document = myDocuments.Add() APP.Visible = True Dim myDocument1 As word.Document = APP.ActiveDocument MsgBox(myDocument1.Name) End Sub End Module
實例效果:
實例8:沒有活動文檔的異常,書本第11頁
程序清單1.8 可能拋出異常的屬性:Word應用程序對象上的ActiveDocument屬性
Dim myDocument As Word.Document Try myDocument = app.ActiveDocument MsgBox(myDocument.Name) Catch ex As Exception MsgBox(String.Format("No active document: {0}", ex.Message) End Try
示例代碼:
Imports word = Microsoft.Office.Interop.Word Module Module1 Sub Main() Dim APP As word.Application = New word.Application Dim myDocument As word.Document APP.Visible = True Try myDocument = APP.ActiveDocument MsgBox(myDocument.Name) Catch ex As Exception MsgBox(String.Format("No active document: {0}", ex.Message)) End Try End Sub End Module
實例效果:
實例9:沒有打開Excel,就返回nothing書本第11頁。
程序清單1.9 可能返回Nothing的屬性:Excel應用程序對象中的ActiveWorkBook屬性
Dim myWorkbook As Excel.Workbook = app.ActiveWorkbook If myWorkbook Is Nothing Then MsgBox("No active workbook") Else MsgBox(myWorkbook.Name) End If
實例代碼:
Imports excel = Microsoft.Office.Interop.Excel Module Module1 Sub Main() Dim APP As excel.Application = New excel.Application Dim myWorkbook As Excel.Workbook = app.ActiveWorkbook If myWorkbook Is Nothing Then MsgBox("No active workbook") Else MsgBox(myWorkbook.Name) End If End Sub End Module
實例效果:
實例10:Word應用程序的文件對話框(FileDialog)屬性 第12頁
注:實例10中出現了文件對話框,因此引用裏要添加「Microsoft office 14.0 object library」,FileDialog來源於Microsoft.office.core.Filedialog。
程序清單1.10 須要枚舉型參數並返回對象模型的屬性:Word應用程序對象上的FileDialog屬性
Dim dialog As Office.FileDialog dialog = app.FileDialog(Office.MsoFileDialogType. _ msoFileDialogFilePicker) dialog.Show()
實例代碼:
Imports word = Microsoft.Office.Interop.Word Module Module1 Sub Main() Dim app As word.Application = New word.Application Dim dialog As word.Dialog dialog = app.Dialogs(word.WdWordDialog.wdDialogFileOpen) dialog.Show() End Sub End Module
實例效果:
實例拓展(來自MSDN):
Imports word = Microsoft.Office.Interop.Word Module Module1 Sub Main() Dim app As word.Application = New word.Application Dim dlg As word.Dialog = app.Dialogs(word.WdWordDialog.wdDialogFileOpen) Dim dlgType As Type = GetType(word.Dialog) ' Set the Name property of the dialog box. dlgType.InvokeMember("Name", _ Reflection.BindingFlags.SetProperty Or _ Reflection.BindingFlags.Public Or _ Reflection.BindingFlags.Instance, _ Nothing, dlg, New Object() {"Testing"}, _ System.Globalization.CultureInfo.InvariantCulture) ' Display the dialog box. dlg.Show() ' Show the Name property. MsgBox(dlgType.InvokeMember("Name", _ Reflection.BindingFlags.GetProperty Or _ Reflection.BindingFlags.Public Or _ Reflection.BindingFlags.Instance, _ Nothing, dlg, Nothing, _ System.Globalization.CultureInfo.InvariantCulture)) End Sub End Module
實例效果:
實例11:Excel應用程序對象上的Range屬性 書本第13頁
程序清單1.11 具備可選參數的屬性:Excel應用程序對象上的Range屬性
' Omit the optional second parameter Dim myRange As Excel.Range = app.Range("A1") ' Specify the optional second parameter Dim myRange2 As Excel.Range = app.Range("A1", "B2")
實例代碼:
Imports excel = Microsoft.Office.Interop.Excel Module Module1 Sub Main() Dim app As excel.Application = New excel.Application Dim myWorkbooks As excel.Workbooks = app.Workbooks Dim myWorkbook As excel.Workbook = myWorkbooks.Add("E:\工做簿1.xlsx") app.Visible = True Dim myRange As String = myWorkbook.Worksheets("sheet1").Range("A1").text 'Dim myRange2 As String = myWorkbook.Worksheets("sheet1").Range("A1", "B2").text MsgBox(String.Format("單元格中的值:{0}", myRange)) End Sub End Module
實例效果:
小結一下:
最單的一步到位的一種從程序到咱們常見的工做表的代碼寫法:
'Earlier in this chapter, we presented this code as a simple way of navigating the object hierarchy of Excel to get a Worksheet object: Dim myWorksheet As excel.Worksheet myWorksheet = CType(app.Workbooks.Item(1).Worksheets.Item(1), excel.Worksheet) 'There is an even simpler way to write this code. It can be rewritten like this: Dim myWorksheet As excel.Worksheet myWorksheet = CType(app.Workbooks(1).Worksheets(1), excel.Worksheet)
Imports excel = Microsoft.Office.Interop.Excel Module Module1 Sub Main() Dim app As excel.Application = New excel.Application Dim myWorksheet As excel.Worksheet myWorksheet = CType(app.Workbooks.Add("E:\工做簿1.xlsx").Worksheets.Item("sheet1"), excel.Worksheet) Dim myRange As String = myWorksheet.Range("A1").text MsgBox(String.Format("單元格中的值:{0}", myRange)) End Sub End Module
實例12 activate方法激活Word 書本第14頁
程序清單 1.12 沒有參數沒有返回類型的方法:Word應用程序對象中的Activate方法
MsgBox("Activating the Word window.") app.Activate()
實例代碼:
Imports word = Microsoft.Office.Interop.Word Module Module1 Sub Main() Dim app As word.Application = New word.Application Dim myDocuments As word.Documents = app.Documents Dim myDocument As word.Document = myDocuments.Add() app.Visible = True MsgBox("Activating the Word window.") app.Activate() End Sub End Module
實例效果:
實例13 Word程序改變打開路徑 書本第14頁
程序清單1.13 具備參數但沒有返回值的方法:Word應用程序對象中的ChangeFileOpenDirectory方法
app.ChangeFileOpenDirectory("c:\temp") MsgBox("Will open out of temp for this session.")
實例代碼:
Imports word = Microsoft.Office.Interop.Word Module Module1 Sub Main() Dim app As word.Application = New word.Application app.ChangeFileOpenDirectory("c:\temp") Dim dialog As word.Dialog dialog = app.Dialogs(word.WdWordDialog.wdDialogFileOpen) dialog.Show() End Sub End Module
實例效果:
實例14 得到Word的像素值
程序清單1.14 沒有參數但有返回值的方法:Word應用程序對象中的DefaultWebOptions方法
Dim options As Word.DefaultWebOptions = app.DefaultWebOptions() MsgBox(String.Format("Pixels per inch is {0}.", _ options.PixelsPerInch))
實例代碼:
Imports word = Microsoft.Office.Interop.Word Module Module1 Sub Main() Dim app As word.Application = New word.Application Dim options As word.DefaultWebOptions = app.DefaultWebOptions MsgBox(String.Format("pixels per inch is {0}", options.PixelsPerInch)) End Sub End Module
實例效果:
實例15 Word的屬性CentimetersToPoints將釐米轉換爲對應的點數 書本第14頁
程序清單1.15 具備參數和返回值的方法:Word應用程序對象中的CentimetersToPoints方法
Dim centimeters As Single = 15.0 Dim points As Single = app.CentimetersToPoints(centimeters) MsgBox(String.Format("{0} centimeters is {1} points.", _ centimeters, points))
實例代碼:
Imports word = Microsoft.Office.Interop.Word Module Module1 Sub Main() Dim app As word.Application = New word.Application Dim centimeters As Single = 15.0 Dim points As Single = app.CentimetersToPoints(centimeters) MsgBox(String.Format("{0} centimeters is {1} points.", centimeters, points)) '1 centimeter = 28.34646 point End Sub End Module
實例效果:
實例16 Excel程序的CheckSpelling方法檢查單詞拼寫 書本第15頁
程序清單1.16 具備可選參數和返回值的方法:Excel應用程序對象中的CheckSpelling方法
Dim phrase1 As String = "Thes is spelled correctly." Dim phrase2 As String = "This is spelled correctly AFAIK." Dim isCorrect1 As Boolean = app.CheckSpelling(phrase1) Dim isCorrect2 As Boolean = app.CheckSpelling(phrase2, , True)
示例代碼:
Imports excel = Microsoft.Office.Interop.Excel Module Module1 Sub Main() Dim app As excel.Application = New excel.Application Dim phrase1 As String = "Thes is spelled correctly." Dim phrase2 As String = "This is spelled correctly AFAIK." Dim isCorrect1 As Boolean = app.CheckSpelling(phrase1) Dim isCorrect2 As Boolean = app.CheckSpelling(phrase2, , True) MsgBox("phrase1: " & isCorrect1 & Chr(13) & Chr(10) & "phrase2: " & isCorrect2) End Sub
實例效果:
實例17 處理Excel Application 對象中WindowActivate事件 書本第17頁
程序清單 1.17 處理Excel Application對象中WindowActivate事件的VSTO自定義機制
Public Class Sheet1 Public WithEvents app As Excel.Application Private Sub app_WindowActivate(ByVal Wb As Excel.Workbook, _ ByVal Wn As Excel.Window) Handles app.WindowActivate MsgBox("The window " & Wn.Caption & " was just activated.") End Sub Private Sub Sheet1_Startup(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Startup app = Me.Application End Sub End Class
實例代碼:
Public Class sheet1 Public WithEvents app As Excel.Application Private Sub app_WindowActivate(ByVal Wb As Excel.Workbook, ByVal Wn As Excel.Window) Handles app.WindowActivate MsgBox("The window " & Wn.Caption & " was just activated.") End Sub Private Sub Sheet1_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup app = Me.Application End Sub End Class
實例效果:
實例18 WindowActivate事件動態添加和刪除事件處理器 書本第19頁
程序清單1.18 VSTO自定義機制,用於爲Excel應用程序對象的WindowActivate事件動態添加和刪除事件處理器
Public Class Sheet1 Public app As Excel.Application Private Sub MyWindowActivateHandler(ByVal Wb As _ Excel.Workbook, ByVal Wn As Excel.Window) MsgBox("The window " & Wn.Caption & " was just activated.") RemoveHandler app.WindowActivate, _ AddressOf Me.MyWindowActivateHandler End Sub Private Sub Sheet1_Startup(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Startup app = Me.Application AddHandler app.WindowActivate, _ AddressOf Me.MyWindowActivateHandler End Sub End Class
實例代碼:
Public Class Sheet1 Public app As Excel.Application Private Sub MyWindowActivateHandler(ByVal Wb As Excel.Workbook, ByVal Wn As Excel.Window) MsgBox("The window " & Wn.Caption & " was just activated.") RemoveHandler app.WindowActivate, AddressOf Me.MyWindowActivateHandler End Sub Private Sub Sheet1_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup app = Me.Application AddHandler app.WindowActivate, AddressOf Me.MyWindowActivateHandler End Sub End Class
實例效果: