VBA代碼: 1,、在模塊1里,WorkBookUsage過程 Sub WorkBookUsage() Dim wb As Workbook Dim path As String Dim fileName As String Dim ws As Worksheet Dim shtName As String fileName = "C:\我剛剛創(chuàng)建的Excel文件.xlsx"
'檢查目標(biāo)文件是否已打開,打開就關(guān)閉它,。 For Each wb In Workbooks If wb.FullName = fileName Then MsgBox "文件【" & wb.FullName & "】已打開,,接下來關(guān)閉它!" wb.Close savechanges:=False End If Next
'下面新建一個工作簿 MsgBox "下面新建一個工作簿,并在后面插入一張新的工作表" Set wb = Application.Workbooks.Add
'激活工作簿 wb.Activate 'activate 方法
'在工作簿中新建一個工作表 Set ws = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count)) '顯示工作表的名稱 【屬性】 MsgBox "新建的工作簿名稱為:" & Chr(10) _ & " " & wb.Name & Chr(10) & "完整路徑名稱為:" _ & Chr(10) & " " & wb.FullName & Chr(10) _ & "新插入的工作表為:" & Chr(10) & " " & ws.Name
'保存到C盤,,SaveAs方法,屏蔽復(fù)蓋文件提示 Application.DisplayAlerts = False wb.SaveAs fileName Application.DisplayAlerts = True
'顯示保存后的工作簿的名稱 path = wb.FullName MsgBox "保存后:" & Chr(10) & "工作簿的名稱為:" _ & Chr(10) & " " & wb.Name & Chr(10) _ & "工作簿的完整路徑名稱為:" & Chr(10) & " " & path MsgBox "工作簿所在文件夾為:" & Chr(10) & wb.path
'循環(huán)工作簿,,把每個工作表的名稱寫入A1單元格 MsgBox "下面循環(huán)工作簿中的工作表," & Chr(10) _ & "把每個工作表的名稱寫入A1單元格," _ & Chr(10) & "把A1單元格,、工作表標(biāo)簽頁隨機(jī)標(biāo)色" For Each ws In wb.Sheets ws.Activate ws.Cells(1, 1) = ws.Name Randomize Timer r = Int(255 * Rnd) g = Int(255 * Rnd) b = Int(255 * Rnd) ws.Cells(1, 1).Interior.Color = RGB(r, g, b) ws.Tab.Color = RGB(r, g, b) shtName = shtName & ws.Name & "/" Application.Wait Now + TimeSerial(0, 0, 1) Next shtName = Left(shtName, Len(shtName) - 1) MsgBox "所有表名為:" & shtName
'把工作表改名 MsgBox "下面再次循環(huán)工作簿中的工作表," _ & Chr(10) & "把工作表改名,," & Chr(10) _ & "把A1單元格、工作表標(biāo)簽頁隨機(jī)標(biāo)色"
shtName = "" For Each ws In wb.Sheets ws.Activate i = i + 1 ws.Name = "工作表_" & i Randomize Timer r = Int(255 * Rnd) g = Int(255 * Rnd) b = Int(255 * Rnd) ws.Cells(1, 1).Interior.Color = RGB(r, g, b) ws.Tab.Color = RGB(r, g, b) shtName = shtName & ws.Name & "/" Application.Wait Now + TimeSerial(0, 0, 1) Next shtName = Left(shtName, Len(shtName) - 1) MsgBox "改名后所有表名為:" & shtName '保存關(guān)閉工作簿 MsgBox "即將關(guān)閉:" & Chr(10) _ & wb.Name & Chr(10) & "等待2秒后,,將再次打開,。"
wb.Save wb.Close savechanges:=False '等待2秒再打開 Application.Wait Now + TimeSerial(0, 0, 2)
'打開剛才保存的工作簿 MsgBox "即將打開:" & Chr(10) & path Set wb = Workbooks.Open(path) wb.Activate End Sub 代碼解析:僅為演示各種屬性、方法的用法,,基本在代碼注釋里,,MsgBox函數(shù)中寫得比較清楚了,不再多說,。 (1)如果MsgBox中如果文字較長,,需要換行顯示的,我們可以插入換行符 Chr(10),。 (2)隨機(jī)生成RGB函數(shù)中的rgb值,,可以實(shí)現(xiàn)隨機(jī)著色的效果。 (3)為了能看得清楚程序運(yùn)行過程,,我們加入等待時間,。用Application.Wait。2,、在ThisWorkBook里
Private Sub Workbook_BeforeClose(Cancel As Boolean) Me.Save MsgBox "你關(guān)閉了文件:" _ & Chr(10) & Me.Name & Chr(10) & "歡迎下次再來,!" End Sub
Private Sub Workbook_Open() MsgBox "歡迎打開:" & Chr(10) & ThisWorkbook.Name End Sub
代碼解析:工作簿的BeforeClose事件、Open事件,,代碼僅僅是為了演示之用,,沒有什么實(shí)際意義。 喜歡就點(diǎn)個贊,、點(diǎn)在看,、留言評論、分享一下唄,!感謝支持,!
|