[英]Loop through all worksheets in all Excel workbooks in a folder to change the font, font size, and alignment of text in all cells
在我的硬盤驅動器上,我有一個包含許多Excel工作簿的文件夾。 我想循環瀏覽此文件夾中每個Excel工作簿中的所有工作表,以更改字體,字體大小和所有單元格中文本的對齊方式。
根據我自己對VBA的有限了解,以及通過閱讀此處的其他相關問題,我將自己存儲在Personal.xls中的宏匯總在一起。
到目前為止,它似乎遍歷了工作簿,但並未格式化其中的任何文本。
Sub Format_Workbooks()
'This macro requires that a reference to Microsoft Scripting Routine
'be selected under Tools\References in order for it to work.
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim fso As New FileSystemObject
Dim source As Scripting.Folder
Dim wbFile As Scripting.File
Dim book As Excel.Workbook
Dim sheet As Excel.Worksheet
Set source = fso.GetFolder("C:\Documents and Settings\The Thing\My Documents\Excel Workbooks")
For Each wbFile In source.Files
If fso.GetExtensionName(wbFile.Name) = "xls" Then
Set book = Workbooks.Open(wbFile.Path)
For Each sheet In book.Sheets
With sheet
.Cells.Font.Name = "Whatever font I want to use"
.Cells.Font.Size = 10
.Cells.HorizontalAlignment = xlLeft
End With
Next
book.Close
End If
Next
End Sub
為了使宏按預期工作,我需要進行哪些更改?
另外,由於我在想知道編寫宏的方法是否符合我的既定目標之前還是從未使用過“ Microsoft腳本例程”,因此應該重新編寫它嗎?
謝謝你的幫助。
如果混合使用文件類型,則可以使用Dir函數提高性能,因為可以過濾文件類型,例如:
根據Brett的建議進行編輯
Sub FormatFiles()
Const fPath As String = "D:\My Documents\"
Dim sh As Worksheet
Dim sName As String
With Application
.Calculation = xlCalculationManual
.EnableEvents = False
.ScreenUpdating = False
End With
sName = Dir(fPath & "*.xls*")
Do Until sName = ""
With GetObject(fPath & sName)
For Each sh In .Worksheets
With sh
.Cells.HorizontalAlignment = xlLeft
.Cells.Font.Name = "Tahoma"
.Cells.Font.Size = 10
End With
Next sh
.Close True
End With
sName = Dir
Loop
With Application
.Calculation = xlAutomatic
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
以下語句表示您沒有看到任何警告:
Application.DisplayAlerts = False
您缺少的警告來自:
book.Close
詢問您是否要保存所做的更改。 通過忽略此問題,您正在回答“否”。
建議措施:
Application.DisplayAlerts = False
book.Save
除非您要確認每次保存,否則請在關閉之前保存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.