有人可以告诉我我做错了什么,我对VBA很新,并且有以下代码。我想打开几个excel文件并保存" Cash"选项卡作为特定文件夹的pdf。我遇到的问题是它试图将文件夹保存到"测试"文件夹而不是"单元格(r,3)"因此,在保存第一个PDF文件后,我收到错误,因为它们具有相同的名称。任何帮助将不胜感激!
Sub Cash_PDF_()
r = 2
Do While Cells(r, 5) <> ""
Workbooks.Open FileName:="H:\Investment\Fund Folders\" & Cells(r, 3) & "\" & Cells(r, 5), _
ReadOnly:=True, UpdateLinks:=0
Sheets("Cash").Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:="C:\Users\Desktop\Test\" & Cells(r, 3) & "\Cash.pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
ActiveWindow.Close SaveChanges:=False
r = r + 1
Loop
End Sub
答案 0 :(得分:2)
Cells
,不合格时,是指活动表。您更改了活动工作表,因此它不是指您想要的内容。
Sub Cash_PDF_()
Dim ws As Worksheet
Dim wb As Workbook
Dim r As Long
Set ws = ActiveSheet
r = 2
Do While ws.Cells(r, 5) <> ""
Set wb = Workbooks.Open(FileName:="H:\Investment\Fund Folders\" & ws.Cells(r, 3) & "\" & ws.Cells(r, 5), _
ReadOnly:=True, UpdateLinks:=0)
wb.Sheets("Cash").ExportAsFixedFormat _
Type:=xlTypePDF, _
FileName:="C:\Users\Desktop\Test\" & ws.Cells(r, 3) & "\Cash.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
wb.Close SaveChanges:=False
r = r + 1
Loop
End Sub