我堅(jiān)持在VB的路上走到黑………… 清單1.1 從應(yīng)用程序?qū)ο髮?dǎo)航到Excel中的工作表 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) 如果代碼不需要在變量中緩存每個(gè)對(duì)象模型對(duì)象,但只需要獲取一個(gè)Worksheet對(duì)象,則編寫此代碼的更有效的方法如下所示: Dim myWorksheet As Excel.Worksheet myWorksheet = CType(app.Workbooks.Item(1).Worksheets.Item(1), Excel.Worksheet) 活代碼:第一步:創(chuàng)建visual basic 2017的窗體應(yīng)用程序(運(yùn)行環(huán)境:win 10+visual studio 2017+office 2010) 第二步:添加引用:COM的 "Microsoft Office 14.0 Object Library 2.5"(指的是Office 2010)和“程序集”的"擴(kuò)展"中的"Microsoft.office.Interop.Excel 14.0.0.0" 第三步:代碼 Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 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 Class 第四步:運(yùn)行結(jié)果
清單1.2 使用整數(shù)或String作為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 活代碼: 活代碼:第一步:創(chuàng)建visual basic 2017的窗體應(yīng)用程序(運(yùn)行環(huán)境:win 10+visual studio 2017+office 2010) 第二步:添加引用:COM的 "Microsoft Office 14.0 Object Library 2.5"(指的是Office 2010)和“程序集”的"擴(kuò)展"中的"Microsoft.office.Interop.Excel 14.0.0.0" 第三步:代碼 Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 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 '以整數(shù)作為索引 MessageBox.Show(str, "獲取工作表名稱") Next For i As Integer = 1 To worksheetCount Dim str As String str = myWorkbook.Worksheets.Item("sheet" & i).Name MessageBox.Show(str, "獲取工作表名稱") '以字符串作為索引 Next End Sub End Class 第四步:運(yùn)行結(jié)果
拓展假如要編輯工作表sheet2中D3單元格,并填入“我是丑丑”,該如何實(shí)現(xiàn)呢 Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 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個(gè)參數(shù)表示添加多少工作表,這里添加3個(gè), Dim C4_sheet As Excel.Worksheet = myWorkbook.Worksheets.Item("sheet2") '工作表的索引從0開始, C4_sheet.Cells(3, 4) = "我是丑丑" 'Cells(行,列),也就是D3單元格 End Sub End Class 運(yùn)行結(jié)果:
清單1.3 使用For Each結(jié)構(gòu)遍歷工作簿集合 Dim myWorkbooks As Excel.Workbooks = app.Workbooks For Each workbook As Excel.Workbook In myWorkbooks MsgBox(String.Format("Workbook {0}", workbook.Name)) Next 活代碼:略 清單1.4 當(dāng)刪除對(duì)象時(shí)使用輔助集合
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
活代碼:第一步:創(chuàng)建visual basic 2017的窗體應(yīng)用程序(運(yùn)行環(huán)境:win 10+visual studio 2017+office 2010) 第二步:添加引用:COM的 "Microsoft Office 14.0 Object Library 2.5"(指的是Office 2010)和“程序集”的"擴(kuò)展"中的"Microsoft.office.Interop.Excel 14.0.0.0" 第三步:代碼 Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim app As Excel.Application = New Excel.Application Dim myWorkbook As Excel.Workbook = app.ActiveWorkbook app.Visible = True myWorkbook = app.Workbooks.Add("E:\工作簿1") Dim myCollection As New Collections.Generic.List(Of Excel.Range) For Each Name As Excel.Range In myWorkbook.Worksheets("Sheet1").Range("A1:D5") '由于是刪除,所以下面的行會(huì)自動(dòng)向上縮進(jìn) myCollection.Add(Name) Next For Each name As Excel.Range In myCollection name.Delete() '由于是刪除,所以下面的行會(huì)自動(dòng)向上縮進(jìn) Next End Sub End Class 運(yùn)行結(jié)果: 原圖:
表1.2 從Word的應(yīng)用程序?qū)ο笾羞x擇的屬性,方法和事件
清單1.5 返回值類型的屬性:Word應(yīng)用程序?qū)ο笊系牟紶朇apsLock屬性 If app.CapsLock Then MsgBox("CapsLock is on") Else MsgBox("CapsLock is off") End If 清單1.6 返回枚舉的屬性:Word應(yīng)用程序?qū)ο笊系腤indowState屬性
Select Case app.WindowState Case Word.WdWindowState.wdWindowStateMaximize MsgBox("Maximized") Case Word.WdWindowState.wdWindowStateMinimize MsgBox("Minimized") Case Word.WdWindowState.wdWindowStateNormal MsgBox("Normal") End Select
清單1.7 返回另一個(gè)對(duì)象模型對(duì)象的屬性:Word應(yīng)用程序?qū)ο笊系腁ctiveDocument屬性
Dim myDocument As Word.Document = app.ActiveDocument MsgBox(myDocument.Name) 列表1.8 可能拋出異常的屬性:Word應(yīng)用程序?qū)ο笊系腁ctiveDocument屬性
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
清單1.9 可以返回的屬性:Excel應(yīng)用程序?qū)ο笊系腁ctiveWorkbook屬
Dim myWorkbook As Excel.Workbook = app.ActiveWorkbook If myWorkbook Is Nothing Then MsgBox("No active workbook") Else MsgBox(myWorkbook.Name) End If
清單1.10 枚舉參數(shù)并返回對(duì)象模型對(duì)象的參數(shù)化屬性:Word應(yīng)用程序?qū)ο笊系腇ileDialog屬性 Dim dialog As Office.FileDialog dialog = app.FileDialog(Office.MsoFileDialogType. _ msoFileDialogFilePicker) dialog.Show() 清單1.11 具有可選參數(shù)的參數(shù)化屬性:Excel應(yīng)用程序?qū)ο笊系姆秶鷮傩?/span> ' 刪除第二個(gè)可選參數(shù) Dim myRange As Excel.Range = app.Range("A1") ' 指定第二個(gè)可選參數(shù) Dim myRange2 As Excel.Range = app.Range("A1", "B2") 默認(rèn)參數(shù)化屬性
Dim myWorksheet As Excel.Worksheet myWorksheet = CType(app.Workbooks.Item(1).Worksheets.Item(1), Excel.Worksheet) '重寫上面的代碼 Dim myWorksheet As Excel.Worksheet myWorksheet = CType(app.Workbooks(1).Worksheets(1), Excel.Worksheet)
清單1.12 無參數(shù)無返回類型的方法:Word應(yīng)用對(duì)象的激活方法
MsgBox("Activating the Word window.") app.Activate() 清單1.13 具有參數(shù)和無返回類型的方法:Word應(yīng)用程序?qū)ο笊系腃hangeFileOpenDirectory方法 app.ChangeFileOpenDirectory("c:\temp") MsgBox("Will open out of temp for this session.") 清單1.14 無參數(shù)和返回類型的方法:Word應(yīng)用程序?qū)ο蟮腄efaultWebOptions方法
Dim options As Word.DefaultWebOptions = app.DefaultWebOptions() MsgBox(String.Format("Pixels per inch is {0}.", options.PixelsPerInch)) 清單1.15 具有參數(shù)和返回類型的方法:Word應(yīng)用程序?qū)ο笊系腃entimetersToPoints方法 Dim centimeters As Single = 15.0 Dim points As Single = app.CentimetersToPoints(centimeters) MsgBox(String.Format("{0} centimeters is {1} points.", centimeters, points)) '將計(jì)量單位從厘米轉(zhuǎn)換為磅。1磅=0.035厘米 '將Excel表的左邊距設(shè)置為5厘米 Worksheets("Sheet1").PageSetup.LeftMargin = Application.CentimetersToPoints(5) 清單1.16 具有可選參數(shù)和返回類型的方法:Excel應(yīng)用程序?qū)ο笊系腃heckSpelling方法 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) '用法 expression.CheckSpelling(Word, CustomDictionary, IgnoreUppercase) 'Word String 類型(僅與 Application對(duì)象一起使用),必需。要檢查的單詞。 'CustomDictionary Variant 類型,可選。用于表示自定義詞典文件名的字符串,如果在主詞典中找不到單詞,則會(huì)到此詞典中查找。如果忽略此參數(shù),則將使用當(dāng)前指定詞典。 'IgnoreUppercase Variant 類型,可選。如果為 True,則 Microsoft Excel 忽略那些所有字母都是大寫的單詞。如果為 False 則 Microsoft Excel 檢查那些所有字母都是大寫的單詞。如果省略該參數(shù),則使用當(dāng)前設(shè)置。 表1.3 Excel應(yīng)用對(duì)象引發(fā)的事件
申明事件處理
Public WithEvents app As Excel.Application 'WithEvents表明Excel.Aplication的實(shí)例對(duì)象是一個(gè)可以引發(fā)事件的對(duì)象
Event WindowActivate(ByVal Wb As Excel.Workbook, ByVal Wn As Excel.Window) 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 清單1.17 處理Excel應(yīng)用程序?qū)ο蟮腤indowActivate事件的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 高級(jí)主題:動(dòng)態(tài)處理事件
AddHandler app.WindowActivate, AddressOf Me.MyWindowActivateHandler 'AddHandler和RemoveHandler語句將傳遞要處理的事件以及將處理事件的事件處理程序方法。 當(dāng)指定事件處理程序方法時(shí),使用AddressOf關(guān)鍵字。 以下代碼使用AddHandler動(dòng)態(tài)添加事件處理程序MyWindowActivateHandler來處理應(yīng)用程序?qū)ο蟮腤indowActivate事件:
RemoveHandler app.WindowActivate, AddressOf Me.MyWindowActivateHandler '刪除事件處理方法 Private Sub app_WindowActivate(ByVal Wb As Excel.Workbook, ByVal Wn As Excel.Window) MsgBox("The window " & Wn.Caption & " was just activated.") End Sub '與動(dòng)態(tài)事件處理程序一樣,事件處理程序簽名必須與事件的預(yù)期簽名相匹配。 但是,當(dāng)您動(dòng)態(tài)處理事件時(shí),Handles關(guān)鍵字不會(huì)用于事件處理程序簽名。 因此,WindowActivate事件的動(dòng)態(tài)事件處理程序看起來像聲明性事件處理程序,但省略了Handles子句: 清單1.18 動(dòng)態(tài)添加和刪除Excel應(yīng)用程序?qū)ο蟮腤indowActivate事件的事件處理程序的VSTO自定義
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 '本示例使工作簿窗口激活時(shí)最大化。 Private Sub Workbook_WindowActivate(ByVal Wn As Excel.Window) Wn.WindowState = xlMaximized End Sub 清單1.19 一個(gè)無法處理CommandBarButton單擊事件的類
Imports Excel = Microsoft.Office.Interop.Excel Imports Office = Microsoft.Office.Core Class SampleListener Private app As Excel.Application Public Sub New(ByVal application As Excel.Application) app = application End Sub ' 這里的作用是關(guān)聯(lián)Click事件,但會(huì)失敗,因?yàn)閎tn沒有放在一個(gè)更永久的變量中。 Public Sub ConnectEvents() Dim bar As Office.CommandBar = app.CommandBars("Standard") Dim btn As Office.CommandBarButton = bar.Controls.Add(1) If btn IsNot Nothing Then btn.Caption = "My Button" btn.Tag = "SampleListener.btn" AddHandler btn.Click, AddressOf Me.btn_Click End If End Sub ' Click事件永遠(yuǎn)不會(huì)到達(dá)此處理程序. Public Sub btn_Click(ByVal ctrl As Office.CommandBarButton, ByRef cancelDefault As Boolean) MessageBox.Show("Button was clicked") End Sub End Class 清單1.20 一個(gè)無法處理Outlook檢查器對(duì)象的NewInspectorEvent的類
Imports Outlook = Microsoft.Office.Interop.Outlook Class SampleListener Private app As Outlook.Application Public Sub New(ByVal application As Outlook.Application) app = application End Sub ' This will appear to connect to the NewInspector event, but ' will fail because Inspectors is not put in a more permanent ' variable. Public Sub ConnectEvents() AddHandler app.Inspectors.NewInspector, _ AddressOf Me.MyNewInspectorHandler End Sub ' The NewInspector event will never reach this handler. Public Sub MyNewInspectorHandler(ByVal inspector As Outlook .Inspector) MessageBox.Show("New inspector.") End Sub End Class
清單1.21 一個(gè)類成功處理CommandBarButton單擊事件,因?yàn)樗鼘ommandBarButton對(duì)象存儲(chǔ)在一個(gè)類成員變量中
Imports Excel = Microsoft.Office.Interop.Excel Imports Office = Microsoft.Office.Core Class SampleListener Private app As Excel.Application Private myBtn As Office.CommandBarButton Public Sub New(ByVal application As Excel.Application) app = application End Sub Public Sub ConnectEvents() Dim bar As Office.CommandBar = app.CommandBars("Standard") myBtn = bar.Controls.Add(1) If myBtn IsNot Nothing Then myBtn.Caption = "My Button" myBtn.Tag = "SampleListener.btn" AddHandler myBtn.Click, AddressOf Me.myBtn_Click End If End Sub Public Sub myBtn_Click(ByVal ctrl As Office.CommandBarButton, ByRef cancelDefault As Boolean) MessageBox.Show("Button was clicked") End Sub End Class 清單1.22 一個(gè)類成功處理Outlook檢查器對(duì)象的NewInspector事件,因?yàn)樗鼘z查器對(duì)象存儲(chǔ)在一個(gè)類成員變量中 Imports Outlook = Microsoft.Office.Interop.Outlook Class SampleListener Private app As Outlook.Application Private myInspectors As Outlook.Inspectors Public Sub New(ByVal application As Outlook.Application) app = application End Sub Public Sub ConnectEvents() myInspectors = app.Inspectors AddHandler myInspectors.NewInspector, _ AddressOf Me.MyNewInspectorHandler End Sub Public Sub MyNewInspectorHandler( _ ByVal inspector As Outlook.Inspector) MessageBox.Show("New inspector.") End Sub End Class
|
|