为什么在此MyCell范围错误上出现类型不匹配?

时间:2018-08-20 18:12:37

标签: excel vba excel-vba

我在此行上不断收到运行时错误:

                        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
                                Filename:=MgrPath & "2018 Mid-Year Comp Statement - " & SM.Range("C5").Value & ".pdf", _
                                Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
                                OpenAfterPublish:=False

Sub Statement_Autoprint()

        Dim MCST As Workbook: Set MCST = ActiveWorkbook
        Dim User As String: User = Environ$("Username")
        Dim SavePath As String: SavePath = "M:\comp_statements\"
        Dim CS As Worksheet: Set CS = MCST.Sheets("Control Sheet")

        Dim MgrPath As String, MyCell As Range, Printed As Integer, i As Integer, SM As Worksheet
        Printed = 0


    Call Disable

For i = 2 To CS.Range("B" & CS.Rows.Count).End(xlUp).Row
    If CS.Range("A" & i) <> "" & CS.Range("B" & i) <> "" Then
        Set SM = MCST.Sheets(CStr(CS.Range("A" & i)))
        SM.Calculate
        SM.Range("P1") = Format(CS.Range("B" & i), "000000000")

            For Each MyCell In SM.Range("N2:N70")
                If MyCell = "HIDE" Then
                    MyCell.EntireRow.Hidden = True
                ElseIf MyCell <> "HIDE" Then
                    MyCell.EntireRow.Hidden = False
                End If
            Next MyCell

        If Not Application.CalculationState = xlDone Then
            DoEvents
        End If

                MgrPath = "M:\Pittsburgh\GRP4\HR_PCorpComp\2018 Midyear\Reporting\Parsley\comp_statements\" & SM.Range("K5") & "\"


                If Dir(MgrPath, vbDirectory) <> "" Then
                    MkDir MgrPath
                End If

                        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
                                    Filename:=MgrPath & "2018 Mid-Year Comp Statement - " & SM.Range("C5").Value & ".pdf", _
                                    Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
                                    OpenAfterPublish:=False

                    Printed = Printed + 1
                End If
            Next i

            CS.Activate

            Call Re_Enable


End Sub

我没有使用该名称存在的文件/以该名称打开的文件,我不知道是什么原因阻止了此文件的保存。其他所有代码都按预期运行,只是无法循环到下一位员工,因为该错误导致保存被取消。

1 个答案:

答案 0 :(得分:2)

尝试一下

For Each mycell In SM.Range("N2:N70")
    If IsError(mycell) Then
        Debug.Print mycell.Address
    Else
        mycell.EntireRow.Hidden = (mycell = "HIDE")
    End If
Next mycell
  1. 使用IsError
  2. 处理错误
  3. 转到上面的代码所指向的单元格,并检查是否存在公式错误。

如果单元格有公式错误,通常会得到该错误。