Workbook對象代表一個工作簿,Workbooks集合對象則代表同一Excel進(jìn)程中打開的所有工作簿對象。 Sub CreateNewWorkbook1() MsgBox "將創(chuàng)建一個新工作簿." Workbooks.Add End Sub 應(yīng)用示例2:創(chuàng)建一個新工作簿并命名工作表且添加數(shù)據(jù) Sub CreateNewWorkbook2() Dim wb As Workbook Dim ws As Worksheet Dim i As Long MsgBox "將創(chuàng)建一個新工作簿,并預(yù)設(shè)工作表格式." Set wb = Workbooks.Add Set ws = wb.Sheets(1) ws.Name = "產(chǎn)品匯總表" ws.Cells(1, 1) = "序號" ws.Cells(1, 2) = "產(chǎn)品名稱" ws.Cells(1, 3) = "產(chǎn)品數(shù)量" For i = 2 To 10 ws.Cells(i, 1) = i - 1 Next i End Sub 應(yīng)用示例3:創(chuàng)建帶有指定數(shù)量工作表的工作簿 Sub testNewWorkbook() MsgBox "創(chuàng)建一個帶有10個工作表的新工作簿" Dim wb As Workbook Set wb = NewWorkbook(10) End Sub Function NewWorkbook(wsCount As Integer) As Workbook '創(chuàng)建帶有由變量wsCount提定數(shù)量工作表的工作簿,工作表數(shù)在1至255之間 Dim OriginalWorksheetCount As Long Set NewWorkbook = Nothing If wsCount < 1 Or wsCount > 255 Then Exit Function OriginalWorksheetCount = Application.SheetsInNewWorkbook Application.SheetsInNewWorkbook = wsCount Set NewWorkbook = Workbooks.Add Application.SheetsInNewWorkbook = OriginalWorksheetCount End Function 自定義函數(shù)NewWorkbook可以創(chuàng)建最多帶有255個工作表的工作簿。本測試示例創(chuàng)建一個帶有10個工作表的新工作簿。 Workbooks.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)
可以看到,該方法具有很多參數(shù),但大多數(shù)參數(shù)都很少用到。在這些參數(shù)中,除參數(shù)FileName必須外,其它參數(shù)都可選。 Sub openWorkbook2() Dim fname As String MsgBox "將D盤中的<測試.xls>工作簿以只讀方式打開" fname = "D:\測試.xls" Workbooks.Open Filename:=fname, ReadOnly:=True End Sub [應(yīng)用3] 訪問特定的工作簿 Workbooks.Item(1) 返回Workbooks集合中的第一個工作簿。由于Item屬性是缺省的屬性,因此上述代碼也可以簡寫為: Workbooks(1) 然而,使用索引號來指定工作簿是不可靠的,最好使用工作簿的具體名稱來指定特定的工作簿,例如: Workbooks("MyBook.xlsx")
注意,當(dāng)用戶使用“新建”命令創(chuàng)建一個新工作簿(假設(shè)該工作簿系統(tǒng)默認(rèn)名稱為Book2)時,在沒有保存該工作簿前,應(yīng)該使用下面的代碼指定該工作簿: Workbooks("Book2")
此時,如果使用下面的代碼指定該工作簿: Workbooks("Book2.xlsx")
將會產(chǎn)生運(yùn)行時錯誤:下標(biāo)越界。 Workbooks("MyWorkbook").Activate
[應(yīng)用5] 獲得當(dāng)前打開的工作簿數(shù)(Count屬性) Workbooks.Count [應(yīng)用6] 判斷工作簿是否是只讀的(ReadOnly屬性) Function MyName() As String MyName = ThisWorkbook.Name End Function 使用Workbook對象的FullName屬性可以返回工作簿的路徑和名稱。例如,下面的函數(shù)可以返回當(dāng)前工作簿的路徑和名稱: Function MyName() As String MyName = ThisWorkbook.Name End Function 使用Workbook對象的Path屬性可以返回工作簿文件的路徑。使用Workbook對象的CodeName屬性返回工作簿對象的代碼名。 Sub testGeneralWorkbookInfo() MsgBox "本工作簿的名稱為" & ActiveWorkbook.Name MsgBox "本工作簿帶完整路徑的名稱為" & ActiveWorkbook.FullName MsgBox "本工作簿對象的代碼名為" & ActiveWorkbook.CodeName MsgBox "本工作簿的路徑為" & ActiveWorkbook.Path If ActiveWorkbook.ReadOnly Then MsgBox "本工作簿已經(jīng)是以只讀方式打開" Else MsgBox "本工作簿可讀寫." End If If ActiveWorkbook.Saved Then MsgBox "本工作簿已保存." Else MsgBox "本工作簿需要保存." End If End Sub [應(yīng)用8] 保存工作簿(Save方法) Workbook.Save 應(yīng)用示例6:保存已存在的所有工作簿 Sub SaveAllWorkbooks() Dim wbk As Workbook For Each wbk In Workbooks If wbk.Path <> "" Then wbk.Save Next wbk End Sub 如果某工作簿的Path屬性值為空,則表明該工作簿為新建工作簿,還沒有保存。而本過程僅保存所有已存在的(即已經(jīng)保存過的)工作簿。 Workbook.SaveAs(FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AccessMode, ConflictResolution, AddToMru, TextCodepage, TextVisualLayout, Local) 所有參數(shù)均為可選參數(shù)。其中參數(shù)FileName指定要保存文件的文件名,可以包含完整的路徑,如果不指定路徑,Excel將文件保存到當(dāng)前文件夾中。參數(shù)FileFormat指定保存文件時使用的文件格式。如果文件夾中存在相同名稱的工作簿,則提示是否替換原工作簿。 Sub AddSaveAsNewWorkbook() Dim Wk As Workbook Set Wk = Workbooks.Add Application.DisplayAlerts = False Wk.SaveAs Filename:="D:\SalesData.xlsx" End Sub 這里使用了Add方法和SaveAs方法,添加一個新工作簿并將該工作簿以文件名SalesData.xlsx保存在D盤中。其中,語句Application.DisplayAlerts = False表示禁止彈出警告對話框。 Sub SaveWorkbook2() Dim oldName As String, newName As String Dim folderName As String, fname As String oldName = ActiveWorkbook.Name newName = "new" & oldName MsgBox "將<" & oldName & ">以<" & newName & ">的名稱保存" folderName = Application.DefaultFilePath fname = folderName & "\" & newName ActiveWorkbook.SaveAs fname End Sub 上述代碼將當(dāng)前工作簿以一個新名(即new加原名)保存在默認(rèn)文件夾中。 Sub CreateBak1() MsgBox "保存工作簿并建立備份工作簿" ActiveWorkbook.SaveAs CreateBackup:=True End Sub 上述代碼在當(dāng)前文件夾中建立工作簿的備份。 Sub CreateBak2() MsgBox "保存工作簿時,若已建立了備份,則將出現(xiàn)包含True的信息框,否則出現(xiàn)False." MsgBox ActiveWorkbook.CreateBackup End Sub [應(yīng)用10] 保存工作簿副本(SaveCopyAs方法) Workbook.SaveCopyAs(Filename) 參數(shù)Filename用來指定副本的文件名。 Sub SaveWorkbookBackup() Dim awb As Workbook, BackupFileName As String, i As Integer, OK As Boolean If TypeName(ActiveWorkbook) = "Nothing" Then Exit Sub Set awb = ActiveWorkbook If awb.Path = "" Then Application.Dialogs(xlDialogSaveAs).Show Else BackupFileName = awb.FullName i = 0 While InStr(i + 1, BackupFileName, ".") > 0 i = InStr(i + 1, BackupFileName, ".") Wend If i > 0 Then BackupFileName = Left(BackupFileName, i - 1) BackupFileName = BackupFileName & ".bak" OK = False On Error GoTo NotAbleToSave With awb Application.StatusBar = "正在保存工作簿..." .Save Application.StatusBar = "正在備份工作簿..." .SaveCopyAs BackupFileName OK = True End With End If NotAbleToSave: Set awb = Nothing Application.StatusBar = False If Not OK Then MsgBox "備份工作簿未保存!", vbExclamation, ThisWorkbook.Name End If End Sub 在當(dāng)前工作簿中運(yùn)行本示例代碼后,將以與工作簿相同的名稱但后綴名為.bak備份工作簿,且該備份與當(dāng)前工作簿在同一文件夾中。 Sub SaveWorkbookBackupToFloppyD() Dim awb As Workbook, BackupFileName As String, i As Integer, OK As Boolean If TypeName(ActiveWorkbook) = "Nothing" Then Exit Sub Set awb = ActiveWorkbook If awb.Path = "" Then Application.Dialogs(xlDialogSaveAs).Show Else BackupFileName = awb.Name OK = False On Error GoTo NotAbleToSave If Dir("D:\" & BackupFileName) <> "" Then Kill "D:\" & BackupFileName End If With awb Application.StatusBar = "正在保存工作簿..." .Save Application.StatusBar = "正在備份工作簿..." .SaveCopyAs "D:\" & BackupFileName OK = True End With End If NotAbleToSave: Set awb = Nothing Application.StatusBar = False If Not OK Then MsgBox "備份工作簿未保存!", vbExclamation, ThisWorkbook.Name End If End Sub 上述程序?qū)?dāng)前工作簿進(jìn)行復(fù)制并以與當(dāng)前工作簿相同的名稱保存在D盤中。其中,使用了Kill方法來刪除已存在的工作簿。 Workbooks.Close
使用Workbook對象的Close方法關(guān)閉指定的工作簿,其語法為: Workbook.Close(SaveChanges, Filename, RouteWorkbook)
參數(shù)均為可選參數(shù)。其中,參數(shù)SaveChanges用于在關(guān)閉工作簿前保存工作簿所發(fā)生的變化。特別地,如果工作簿中沒有變化,則忽略該參數(shù);如果工作簿中有變化但工作簿顯示在其他打開的窗口中,則忽略該參數(shù);如果工作簿中有改動且工作簿未顯示在任何其他打開的窗口中,則由該參數(shù)指定是否應(yīng)保存更改。如果將該參數(shù)設(shè)置為True,則保存對工作簿所做的更改;如果工作簿尚未命名,則使用參數(shù)FileName指定的名稱保存。如果忽略參數(shù)Filename,則要求用戶提供文件名。如果將該參數(shù)設(shè)置為False,則不會保存工作簿中的變化。如果忽略該參數(shù),那么Excel將顯示一個對話框詢問是否保存工作簿中的變化。 Sub SaveAndCloseAllWorkbooks() Dim wbk As Workbook For Each wbk In Workbooks If wbk.Name <> ThisWorkbook.Name Then wbk.Close SaveChanges:=True End If Next wbk ThisWorkbook.Close SaveChanges:=True End Sub 應(yīng)用示例13:不保存而關(guān)閉工作簿 Sub CloseWorkbook1() MsgBox "不保存所作的改變而關(guān)閉本工作簿" ActiveWorkbook.Close False '或ActiveWorkbook.Close SaveChanges:=False '或ActiveWorkbook.Saved=True End Sub<pre> <span style="color: #0000ff;">應(yīng)用示例14:保存而關(guān)閉工作簿</span> <pre lang="vb">Sub CloseWorkbook2() MsgBox "保存所作的改變并關(guān)閉本工作簿" ActiveWorkbook.Close True End Sub 應(yīng)用示例15:關(guān)閉工作簿并將其徹底刪除 Sub KillMe() With ThisWorkbook .Saved = True .ChangeFileAccess Mode:=xlReadOnly Kill .FullName .Close False End With End Sub [應(yīng)用13] 打印預(yù)覽工作簿(PrintPreview方法) Workbook.PrintPreview(EnableChanges) 參數(shù)EnableChanges指定用戶是否可更改邊距和打印預(yù)覽中可用的其他頁面設(shè)置選項(xiàng)。 Workbook.PrintOut(From, To, Copies, Preview, ActivePrinter, PrintToFile, Collate, PrToFileName, IgnorePrintAreas)
所有參數(shù)均為可選參數(shù)。參數(shù)From指定需要打印第一頁的頁碼,參數(shù)To指定要打印的最后一頁的頁碼,如果忽略這些參數(shù),將打印整個對象。 Workbook.Protect(Password, Structure, Windows) 所有參數(shù)均為可選參數(shù)。其中,參數(shù)Password用來指定一個密碼,所設(shè)置的密碼區(qū)分大小寫。如果省略該參數(shù),不用密碼就可以取消對工作簿的保護(hù)。否則,必須指定密碼才能取消對工作簿的保護(hù)。 Sub ProtectWorkbook() MsgBox "保護(hù)工作簿結(jié)構(gòu),密碼為123" ActiveWorkbook.Protect Password:="123", Structure:=True MsgBox "保護(hù)工作簿窗口,密碼為123" ActiveWorkbook.Protect Password:="123", Windows:=True MsgBox "保護(hù)工作簿結(jié)構(gòu)和窗口,密碼為123" ActiveWorkbook.Protect Password:="123", Structure:=True, Windows:=True End Sub [應(yīng)用16] 解除工作簿保護(hù)(Unprotect方法) Workbook.Unprotect(Password) 參數(shù)Password為一個字符串,指定用于解除工作表或工作簿保護(hù)的密碼,區(qū)分大小寫。如果工作簿不設(shè)密碼保護(hù),則省略該參數(shù)。如果對工作簿省略該參數(shù),而該工作簿又設(shè)有密碼保護(hù),則該方法將失效。 Sub UnprotectWorkbook() MsgBox "取消工作簿保護(hù)" ActiveWorkbook.Unprotect "123" End Sub [應(yīng)用17] 判斷工作簿是否有密碼保護(hù)(HasPassword屬性) Sub IsPassword() If ActiveWorkbook.HasPassword = True Then MsgBox "本工作簿有密碼保護(hù),請?jiān)诠芾韱T處獲取密碼." Else MsgBox "本工作簿無密碼保護(hù),您可以自由編輯." End If End Sub [應(yīng)用18] ThisWorkbook對象和ActiveWorkbook對象 Sub LastSaved() Dim SaveTime As String On Error Resume Next SaveTime = ActiveWorkbook.BuiltinDocumentProperties("Last Save Time").Value If SaveTime = "" Then MsgBox ActiveWorkbook.Name & "還沒有被保存." Else MsgBox "保存于:" & SaveTime, , ActiveWorkbook.Name End If End Sub 如果沒有保存過工作簿,那么對Last Save Time屬性的訪問將產(chǎn)生錯誤,使用On Error語句忽略這個錯誤。 Sub listWorkbookProperties() On Error Resume Next '在名為"工作簿屬性"的工作表中添加信息,若該工作表不存在,則新建一個工作表 Worksheets("工作簿屬性").Activate If Err.Number <> 0 Then Worksheets.Add after:=Worksheets(Worksheets.Count) ActiveSheet.Name = "工作簿屬性" Else ActiveSheet.Clear End If On Error GoTo 0 ListProperties End Sub Sub ListProperties() Dim i As Long Cells(1, 1) = "名稱" Cells(1, 2) = "類型" Cells(1, 3) = "值" Range("A1:C1").Font.Bold = True With ActiveWorkbook For i = 1 To .BuiltinDocumentProperties.Count With .BuiltinDocumentProperties(i) Cells(i + 1, 1) = .Name Select Case .Type Case msoPropertyTypeBoolean Cells(i + 1, 2) = "Boolean" Case msoPropertyTypeDate Cells(i + 1, 2) = "Date" Case msoPropertyTypeFloat Cells(i + 1, 2) = "Float" Case msoPropertyTypeNumber Cells(i + 1, 2) = "Number" Case msoPropertyTypeString Cells(i + 1, 2) = "string" End Select On Error Resume Next Cells(i + 1, 3) = .Value On Error GoTo 0 End With Next i End With Range("A:C").Columns.AutoFit End Sub [應(yīng)用20] 重命名工作簿(Name方法) Name oldpathname As newpathname
應(yīng)用示例21:重命名未打開的工作簿 Sub rename() Name "<工作簿路徑>\<舊名稱>.xlsx" As "<工作簿路徑>\<新名稱>.xlsx" End Sub 代碼中<>的內(nèi)容為需要重命名的工作簿所在路徑及新舊名稱。該方法只是對未打開的文件進(jìn)行重命名,如果該文件已經(jīng)打開,使用該方法會提示錯誤。 Sub UsePassword() Dim wb As Workbook Set wb = Application.ActiveWorkbook wb.Password = InputBox("請輸入密碼:") wb.Close End Sub 代碼運(yùn)行后,提示設(shè)置密碼,然后關(guān)閉工作簿;再次打開工作簿時,要求輸入密碼。 Sub testDraw() MsgBox "隱藏當(dāng)前工作簿中的所有圖形" ActiveWorkbook.DisplayDrawingObjects = xlHide MsgBox "僅顯示當(dāng)前工作簿中所有圖形的占位符" ActiveWorkbook.DisplayDrawingObjects = xlPlaceholders MsgBox "顯示當(dāng)前工作簿中的所有圖形" ActiveWorkbook.DisplayDrawingObjects = xlDisplayShapes End Sub [應(yīng)用23] 工作簿文件格式(FileFormat屬性) Sub SetPrecision() Dim pValue MsgBox "在當(dāng)前單元格中輸入1/3,并將結(jié)果算至小數(shù)點(diǎn)后兩位" ActiveCell.Value = 1 / 3 ActiveCell.NumberFormatLocal = "0.00" pValue = ActiveCell.Value * 3 MsgBox "當(dāng)前單元格中的數(shù)字乘以3等于:" & pValue MsgBox "然后,將數(shù)值分類設(shè)置為[數(shù)值],即單元格中顯示的精度" ActiveWorkbook.PrecisionAsDisplayed = True pValue = ActiveCell.Value * 3 MsgBox "此時,當(dāng)前單元格中的數(shù)字乘以3等于:" & pValue & "而不是1" ActiveWorkbook.PrecisionAsDisplayed = False End Sub 上述代碼在計(jì)算前將PrecisionAsDisplayed屬性的值設(shè)置為True,則表明采用單元格中所顯示的數(shù)值進(jìn)行計(jì)算。 Workbook.DeleteNumberFormat(NumberFormat) 參數(shù)NumberFormat為要刪除的數(shù)字格式。 Sub DeleteNumberFormat() MsgBox "從當(dāng)前工作簿中刪除000-00-0000的數(shù)字格式" ActiveWorkbook.DeleteNumberFormat ("000-00-0000") End Sub [應(yīng)用26] 添加名稱(Names屬性) Sub testNames() MsgBox "將當(dāng)前工作簿中工作表Sheet1內(nèi)單元格A1命名為myName." ActiveWorkbook.Names.Add Name:="myName", RefersToR1C1:="=Sheet1!R1C1" End Sub 上述代碼將活動工作簿單元格A1命名為MyName。 Sub UsePassword() Dim Users As Variant Dim Row As Long Users = ActiveWorkbook.UserStatus Row = 1 With Workbooks.Add.Sheets(1) .Cells(Row, 1) = "用戶名" .Cells(Row, 2) = "日期和時間" .Cells(Row, 3) = "使用方式" For Row = 1 To UBound(Users, 1) .Cells(Row + 1, 1) = Users(Row, 1) .Cells(Row + 1, 2) = Users(Row, 2) Select Case Users(Row, 3) Case 1 .Cells(Row + 1, 3).Value = "個人工作簿" Case 2 .Cells(Row + 1, 3).Value = "共享工作簿" End Select Next End With Range("A:C").Columns.AutoFit End Sub 示例代碼運(yùn)行后,將創(chuàng)建一個新工作簿并帶有用戶使用當(dāng)前工作簿的信息,即用戶名、打開的日期和時間及工作簿使用方式。 Styles.Add(Name, BasedOn) 參數(shù)Name必需,用來指定樣式的名稱。參數(shù)BasedOn可選,用來指定單元格,新樣式即基于該單元格生成。如果省略此參數(shù),就基于“常規(guī)”樣式創(chuàng)建新樣式。 Sub test() Dim st As Style '如果該樣式已存在則刪除 For Each st In ActiveWorkbook.Styles If st.Name = "Bordered" Then st.Delete Next st '創(chuàng)建新樣式 With ActiveWorkbook.Styles.Add(Name:="Bordered") .Borders(xlTop).LineStyle = xlDouble .Borders(xlBottom).LineStyle = xlDouble .Borders(xlLeft).LineStyle = xlDouble .Borders(xlRight).LineStyle = xlDouble .Font.Bold = True .Font.Name = "Arial" .Font.Size = 36 End With '應(yīng)用樣式 Application.ActiveSheet.Range("A1:B3").Style = "Bordered" End Sub [應(yīng)用29] 打開文本文件(OpenText方法) Workbooks.OpenText(Filename, Origin, StartRow, DataType, TextQualifier, ConsecutiveDelimiter, Tab, Semicolon, Comma, Space, Other, OtherChar, FieldInfo, TextVisualLayout, DecimalSeparator, ThousandsSeparator, TrailingMinusNumbers, Local) 與Open方法一樣,除參數(shù)Filename必須外,其它參數(shù)都可選。 Array(Array(1,2),Array(3,9)) 參數(shù)TextVisualLayout代表文本的可視布局,參數(shù)DecimalSeparator指定小數(shù)分隔符,參數(shù)ThousandsSeparator指定千位分隔符,參數(shù)TrailingMinusNumbers用于處理末尾為減號的數(shù)字。參數(shù)Local用來指定是否分隔符、數(shù)字和數(shù)據(jù)格式應(yīng)使用計(jì)算機(jī)的區(qū)域設(shè)置。 "張三","工人","A工廠",1/2/2009 "李四","職員","B公司",3/3/2009 "王五","教師","C學(xué)校",2/2/2009 "趙六","學(xué)生","D學(xué)院",1/1/2009 在Excel工作簿中放置下面的代碼: Sub test() Workbooks.OpenText Filename:="D:\excel\temp1.txt", _ Origin:=xlMSDOS, _ StartRow:=1, _ DataType:=xlDelimited, _ TextQualifier:=xlTextQualifierDoubleQuote, _ ConsecutiveDelimiter:=True, _ Comma:=True, _ FieldInfo:=Array(Array(1, 2), Array(2, 2), Array(3, 2), Array(4, 6)) End Sub 運(yùn)行后,將生成如下圖1所示的工作表。注意,列D中的單元格放置日期。 0-125-689 2-523-489 3-424-664 4-125-160 在Excel工作簿中放置下面的代碼: Sub test() Workbooks.OpenText Filename:="D:\excel\temp2.txt", _ Origin:=xlMSDOS, _ StartRow:=1, _ DataType:=xlFixedWidth, _ FieldInfo:=Array(Array(0, 2), Array(1, 9), Array(2, 2), Array(5, 9), Array(6, 2)) End Sub 運(yùn)行后,將生成如下圖2所示的工作表。注意看代碼是如何使用數(shù)組跳過這些連字符的。 Application.ActiveWorkbook.SaveAs _
Filename:="D:\excel\temp.xlsx", FileFormat:=xlWorkbookNormal
[應(yīng)用30] 判斷工作簿是否存在 Sub testFileExists() MsgBox "如果文件不存在則用信息框說明,否則打開該文件." If Not FileExists("C:\文件夾\子文件夾\文件.xls") Then MsgBox "這個工作簿不存在!" Else Workbooks.Open "C:\文件夾\子文件夾\文件.xls" End If End Sub Function FileExists(FullFileName As String) As Boolean '如果工作簿存在,則返回True FileExists = Len(Dir(FullFileName)) > 0 End Function 聲明:本文由完美Excel網(wǎng)站整理,完美Excel保留本文的所有權(quán)利,未經(jīng)許可,任何組織或個人不得以任何方式將本文用于商業(yè)作途。其他網(wǎng)站或博客引用本文,請注明原文鏈接和版權(quán)聲明。 |
|