它已经钻入我的头,以避免错误,并提供良好的用户体验,最好避免使用.Select,.Activate,ActiveSheet,ActiveCell,等.
记住这一点,有没有办法在不使用上述其中一个的情况.ExportAsFixedFormat下Sheets在工作簿的子集上使用该方法?到目前为止,我能够做到这一点的唯一方法是:
For Each; 但是,这导致单独的PDF文件,这是不好的.使用类似于宏录制器生成的代码,使用.Select和ActiveSheet:
Sheets(Array("Sheet1", "Chart1", "Sheet2", "Chart2")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"exported file.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, openafterpublish:= True
Run Code Online (Sandbox Code Playgroud)也许不可能不使用ActiveSheet,但我能不能以.Select某种方式使用?
我试过这个:
Sheets(Array("Sheet1", "Chart1", "Sheet2","Chart2")).ExportAsFixedFormatType:= _
xlTypePDF, Filename:= "exported file.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, openafterpublish:= _
True
Run Code Online (Sandbox Code Playgroud)
这会产生:
错误438:对象不支持此属性或方法
Com*_*ern 24
讨厌疏通一个老问题,但我不愿意看到有人在这个问题上磕磕绊绊地诉诸于其他答案中的代码体操.该ExportAsFixedFormat方法仅导出可见的工作表和图表.这更清洁,更安全,更容易:
Sub Sample()
ToggleVisible False
ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
"exported file.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=True
ToggleVisible True
End Sub
Private Sub ToggleVisible(state As Boolean)
Dim ws As Object
For Each ws In ThisWorkbook.Sheets
Select Case ws.Name
Case "Sheet1", "Chart1", "Sheet2", "Chart2"
Case Else
ws.Visible = state
End Select
Next ws
End Sub
Run Code Online (Sandbox Code Playgroud)
Sid*_*out 14
它钻进了我的脑海(通过很多......
我知道你是什么MEAN ;)
这是一种不使用的方法 .Select/.Activate/ActiveSheet
逻辑:
代码:
Sub Sample()
Dim ws As Object
On Error GoTo Whoa '<~~ Required as we will work with events
'~~> Required so that deleted sheets/charts don't give you Ref# errors
Application.Calculation = xlCalculationManual
For Each ws In ThisWorkbook.Sheets
Select Case ws.Name
Case "Sheet1", "Chart1", "Sheet2", "Chart2"
Case Else
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End Select
Next ws
'~~> Use ThisWorkbook instead of ActiveSheet
ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"exported file.pdf", Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, openafterpublish:=True
LetsContinue:
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = True
'~~> VERY IMPORTANT! This ensures that you get your deleted sheets back.
ThisWorkbook.Close SaveChanges:=False
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
Run Code Online (Sandbox Code Playgroud)