使用vbscript将Excel中的每个工作表设置为Pagesetup

时间:2016-08-30 23:07:36

标签: excel vbscript


我有一个VBscript将文件夹(c:\ folder)中的所有xls文件转换为pdf文件。所有列也设置为适合一页,并具有方向横向。该脚本适用于Sheet1,但如果xls文件有超过1张,它只会将Pagesetup设置设置为“活动”工作表,而不是全部。

如何将我的Pagesetup设置应用于文件夹中所有xls文件中的所有工作表?

Set xlObj = CreateObject("Excel.Application")
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder("c:\folder")
For Each file In f.Files
set xlWB = xlObj.Workbooks.Open(file)
With xlWB.ActiveSheet.PageSetup
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = False
End With    
thisFileName =Left(xlWB.FullName , InStrRev(xlWB.FullName , ".") - 1)
xlWB.Sheets.Select
xlWB.ActiveSheet.ExportAsFixedFormat 0, thisFileName & ".pdf", 0, 1, 0,,,0
xlWB.close False
Next
xlObj.quit

2 个答案:

答案 0 :(得分:2)

您不清楚如何处理导出其他工作表? 作为单独的文件,还是全部在同一个PDF中?

Set xlObj = CreateObject("Excel.Application")
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder("c:\folder")
For Each file In f.Files
    set xlWB = xlObj.Workbooks.Open(file)
    for each sht in xlWB.Worksheets
        With sht.PageSetup
            .Zoom = False
            .FitToPagesWide = 1
            .FitToPagesTall = False
        End With 
        'can't use the same filename for all sheets !
        thisFileName = Left(xlWB.FullName , InStrRev(xlWB.FullName , ".") - 1)
        sht.ExportAsFixedFormat 0, thisFileName & ".pdf", 0, 1, 0,,,0
    next sht
    xlWB.close False
Next
xlObj.quit

答案 1 :(得分:0)

我通过删除sht中的next sht来解决问题
以下代码工作:

    Set xlObj = CreateObject("Excel.Application")
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder("c:\folder")
For Each file In f.Files
    set xlWB = xlObj.Workbooks.Open(file)
    for each sht in xlWB.Worksheets
        With sht.PageSetup 
            .Orientation = 2
            .Zoom = False
            .FitToPagesWide = 1
            .FitToPagesTall = False
        End With 
thisFileName =Left(xlWB.FullName , InStrRev(xlWB.FullName , ".") - 1)
 xlWB.Sheets.Select
xlWB.ActiveSheet.ExportAsFixedFormat 0, thisFileName & ".pdf", 0, 1, 0,,,0
next 
xlWB.close False
Next
xlObj.quit