我正在学习VBA作为加速我工作中某些过程的手段。我必须将房屋清单发送到以excel格式生成的PDF格式的房产。我有以下代码可以很好地工作,但只要隐藏其中一个工作表,我就会收到一条错误消息。当物业从旅行变为旅行时,我必须经常隐藏床单。
我希望将工作表从第4张到PDF表格和#34; Post"。每当我在其中隐藏一张表时,我收到以下错误消息"运行时错误' 5':无效的过程调用或参数"
以下是代码:
Sub SaveAllPDF()
Dim I As Integer
Dim Fname As String
Dim TabCount As Long
TabCount = Sheets("Post").Index
' Begin the loop.
For I = 4 To TabCount
Sheets(I).Activate
With ActiveSheet
Fname = .Range("C15") & " " & .Range(" B1")
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
"C:\Users\brandon.ford\Desktop\Operation Automated\" & Fname,
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
Next I
End Sub
任何人都有任何想法如何解决这个问题,因此对于I = 4到TabCount'忽略任何隐藏的标签?任何帮助都会受到很多赞赏,我一直试图解决这个问题很长一段时间并且没有太多的VBA知识。
答案 0 :(得分:3)
使用当前循环,最好通过在尝试导出之前检查WorkSheet是否可见来避免这种情况。 Visible属性包含此信息。如果工作表可见,则该值应为xlSheetVisible。
以下是支票的完整代码:
Sub SaveAllPDF()
Dim I As Integer
Dim Fname As String
Dim TabCount As Long
TabCount = Sheets("Post").Index
' Begin the loop.
For I = 4 To TabCount
Sheets(I).Activate
With ActiveSheet
If .Visible = xlSheetVisible Then
Fname = .Range("C15") & " " & .Range(" B1")
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
"C:\Users\brandon.ford\Desktop\Operation Automated\" & Fname,
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
End With
Next I
End Sub
答案 1 :(得分:2)
Sheets.Visible
有3个州:xlSheetVisible, xlSheetHidden, xlSheetVeryHidden
xlSheetVeryHidden用于无法通过Excel显示的隐藏工作表,它甚至不在您的列表中。
因此,通过测试,您将避免隐藏的工作表,它会顺利进行!
试试这个:
Sub SaveAllPDF()
Dim I As Integer
Dim Fname As String
Dim TabCount As Long
TabCount = Sheets("Post").Index
' Begin the loop.
For I = 4 To TabCount
If Sheets(I).Visible <> xlSheetVisible Then
Else
With Sheets(I)
Fname = .Range("C15") & " " & .Range(" B1")
.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\brandon.ford\Desktop\Operation Automated\" & Fname, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
End If
Next I
End Sub