[VBA-Word03]VBA批量调整word页边距.txt
Sub Batch()
    Dim fp As String
    Dim fn As String
    Dim d As Document
    Dim m() As String
    Dim tm As Single, bm As Single, lm As Single, rm As Single
    Dim fd As FileDialog
    Dim tbl As Table
    
    Set fd = Application.FileDialog(msoFileDialogFolderPicker)
    fd.Title = "请选择文件夹"
    fd.AllowMultiSelect = False
    If fd.Show <> -1 Then
        MsgBox "未选择文件夹!"
        Exit Sub
    End If
    fp = fd.SelectedItems(1)
    
    m = Split(InputBox("请输入上下左右边距(以厘米为单位,以逗号分隔,最大值9):"), ",")
    If UBound(m) <> 3 Then
        MsgBox "边距输入格式错误!"
        Exit Sub
    End If
    tm = CSng(m(0)): bm = CSng(m(1)): lm = CSng(m(2)): rm = CSng(m(3))
    
    If fp = "" Or Dir(fp, vbDirectory) = "" Then
        MsgBox "无效的文件夹路径!"
        Exit Sub
    End If
    
    fn = Dir(fp & "\*.doc*")
    Do While fn <> ""
        Set d = Documents.Open(FileName:=fp & "\" & fn)
        
        With d.PageSetup
            .TopMargin = tm * Application.CentimetersToPoints(1)
            .BottomMargin = bm * Application.CentimetersToPoints(1)
            .LeftMargin = lm * Application.CentimetersToPoints(1)
            .RightMargin = rm * Application.CentimetersToPoints(1)
        End With
        
        For Each tbl In d.Tables
            tbl.Rows.Alignment = wdAlignRowCenter
            tbl.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
            tbl.Cell(1, 1).Select
            With tbl.Range.Cells
                .VerticalAlignment = wdCellAlignVerticalCenter
            End With
        Next tbl
        
        d.Save
        d.Close
        fn = Dir
    Loop
    
    MsgBox "页边距调整完成!", , "逗号技巧"
End Sub
返回视频教程