问题描述
我正在尝试将文件夹中的许多Excel文件转换为PDF。我创建了一个宏,将Excel文件转换为PDF并格式化首页。
我试图让它为每一页设置格式,但是我没有运气。
我已经为每个循环尝试了很多,但是似乎不起作用。
单元格E4和E3是主宏工作簿第一页中文件的位置。
有什么建议吗?
<script>
$(document).ready(function() {
$('#button1').click(function() {
$input = $('#input1').val();
$.ajax({
type: 'POST',url: '.PHP',data: {
'doing_somthing1.PHP': $input
},dataType: 'json',success: function(result) {
$('.results-container').html(result[0]);
},});
});
});
</script>
解决方法
首先,您需要更改Print_Settings()
的签名,以便它接受工作簿对象而不是文件对象...
Sub Print_Settings(wb As Workbook,ePaperSize As XlPaperSize)
然后,您可以使用For Each/Next
循环遍历每个工作表...
For Each ws In wb.Worksheets
'etc
'
'
Next ws
所以Print_Settings()
如下...
Sub Print_Settings(wb As Workbook,ePaperSize As XlPaperSize)
Dim ws As Worksheet
'On Error Resume Next
Application.PrintCommunication = False
For Each ws In wb.Worksheets
With ws.PageSetup
.LeftMargin = Application.InchesToPoints(0)
.RightMargin = Application.InchesToPoints(0)
.TopMargin = Application.InchesToPoints(0)
.BottomMargin = Application.InchesToPoints(0)
.HeaderMargin = Application.InchesToPoints(0)
.FooterMargin = Application.InchesToPoints(0)
.Orientation = xlLandscape
.PaperSize = ePaperSize
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
Next ws
Application.PrintCommunication = True
End Sub
然后您可以调用以下过程...
Call Print_Settings(wb,xlPaperLetter)
其他注意事项
-
您可以删除对
Print_Settings()
的第二次调用,因为这似乎是多余的。 -
您应该为Workbook对象的Close方法提供适当的参数。否则,系统会提示您是否要保存工作簿。
-
您的计数器变量
n
应该在For Each/Next
循环之前初始化,然后在循环内递增。
请尝试以下操作...
n = 0 'initialize counter
For Each f In fo.Files
n = n + 1 'increment counter
Application.StatusBar = "Processing..." & n & "/" & fo.Files.Count
Set wb = Workbooks.Open(f.Path)
Call Print_Settings(wb,xlPaperLetter)
wb.ExportAsFixedFormat xlTypePDF,sh.Range("E4").Value & Application.PathSeparator & VBA.Replace(f.Name,".xlsx",".pdf"),quality:=xlQualityStandard,IncludeDocProperties:=True,IgnorePrintAreas:=True
wb.Close SaveChanges:=False 'change as desired
Next