0

在我的硬盘驱动器上,我有一个包含许多 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 脚本例程”,因此我想知道我在编写此宏时所采用的方法是否适合我的既定目标,还是应该从头开始重写?

谢谢你的帮助。

4

2 回答 2

4

如果文件类型混合在一起,您可以使用 Dir 函数提高性能,因为您可以过滤文件类型,例如:

根据布雷特的建议进行编辑

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
于 2012-03-04T21:48:24.683 回答
1

以下语句意味着您看不到任何警告:

Application.DisplayAlerts = False

您缺少的警告来自:

book.Close

它询问您是否要保存所做的更改。忽略这个问题,你就是在回答“不”。

建议措施:

  1. 删除Application.DisplayAlerts = False
  2. book.Save除非您想确认每次保存,否则请在关闭前添加。
于 2012-03-04T21:31:33.413 回答