Workbook工作簿的常用功能:
1. 新建工作簿
- Dim wb As Workbook
- Application.SheetsInNewWorkbook = 1 '設(shè)置初始工作簿中的工作表數(shù)
- Set wb = Application.WorkBooks.Add
- wb.Worksheets(1).name = '表1' '給第一個(gè)工作表設(shè)置名稱
- Application.SheetsInNewWorkbook = 3
- Dim fileInfo As String
- fileInfo = Application.GetOpenFilename('Excel 工作簿(*.xlsx), *.xlsx')
- MsgBox fileInfo
3. 備份(另存為)Excel文件
- Dim wb As Workbook
- Set wb = Application.WorkBooks(1) '原文件名為vba.xlsx
- wb.Activate
- wb.SaveCopyAs wb.path & '\' & 'Bak_' & wb.name '備份文件名為Bak_vba.xlsx
- Dim fileInfo As String
- fileInfo = Application.GetSaveAsFilename('excelFile', 'Excel 工作簿(*.xlsm),*.xlsm')
- If Not fileInfo = 'False' Then
- ActiveWorkbook.SaveAs Filename:=fileInfo
- End If
- MsgBox '文件未保存'
- Else
- Dim win As Window
- Dim winState As Long
- Dim winWidth As Double
- Dim winHeight As Double
- Set win = Application.ActiveWindow
- win.Activate
- With win
- .WindowState = xlMinimized '最小化工作簿,但是Excel程序窗口沒(méi)有最小化
- End With
- With win
- winState = .WindowState
- winWidth = .Width
- winHeight = .Height
- End With
- Debug.Print 'WinState: ' & winState
- Debug.Print 'WinWidth: ' & winWidth
- Debug.Print 'WinHeight: ' & winHeight
- Dim win As Window
- Set win = Application.ActiveWindow
- With win
- .Split = True
- .SplitColumn = 1 '若設(shè)置為0,表示不凍結(jié)列
- .SplitRow = 3
- .FreezePanes = True '如果不設(shè)置FreezePanes將會(huì)在工作表中出現(xiàn)粗分割線
- End With
7. 修改工作簿文件名
- Dim fileName As String
- fileName = 'C:\book.xlsx' '文件不存在會(huì)報(bào)錯(cuò)
- Name fileName As 'C:\book1.xlsx' '工作簿應(yīng)處于關(guān)閉狀態(tài),而且路徑應(yīng)當(dāng)一致
- Debug.Print 'Renamed OK!'
Workbook主要事件:
Workbook事件比起之前的Application事件寫(xiě)起來(lái)方便些。我們直接使用ThisWorkbook對(duì)象的事件(也是一個(gè)Workbook對(duì)象)
如下圖,雙擊ThisWorkbook,在右側(cè)的代碼區(qū)上方直接選擇需要實(shí)現(xiàn)的事件,然后在自動(dòng)生成的事件函數(shù)中編寫(xiě)代碼
1.BeforeClose事件
- Private Sub Workbook_BeforeClose(Cancel As Boolean)
- MsgBox '關(guān)不掉了'
- Cancel = True
- End Sub
該事件在關(guān)閉工作簿前觸發(fā)2.BeforeSave事件
- Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
- If Not SaveAsUI Then
- MsgBox '保存不了了'
- Cancel = True
- End If
- End Sub
3.WindowActive事件
- Private Sub Workbook_WindowActivate(ByVal Wn As Window)
- MsgBox '激活工作簿'
- Wn.width = 100
- End Sub
聯(lián)系客服