第二次迭代时出错:应用程序定义或对象定义的错误

时间:2018-03-21 17:36:38

标签: excel vba excel-vba loops iteration

今年,我继承了Office 2010 Win 7中大约十几个accdb应用程序的支持,这些应用程序经常操作外部excel文件。

我一直得到同样的错误情况。它在我的vba中用于excel命令, 但只在循环的第一次迭代之后。它第一次通过时总能正常工作。似乎与我如何识别对象有关。我已经阅读了多篇关于使用对象和特定错误的最佳实践的文章,但没有任何内容已经转化为解决方案。有人ELI5我做错了吗?

在下面的示例中,它在Range("A1").Select命令的第二次迭代中提前抛出错误。

代码:

Sub runCleanAndImportUnpre()

Dim strFolder As String
Dim strTableDest As String

strTableDest = "Unpresented_EOD_Import"
strFolder = "C:\Users\lclambe\Projects\Inputs\test2"

Call CleanAndImportUnpresentedInAGivenFolder(strTableDest, strFolder)

End Sub


Function CleanAndImportUnpresentedInAGivenFolder(strTable As String, strFolder As String)

' Function that opens files in a folder, cleans them up and saves them.

Dim myfile
Dim mypath
Dim strPathFileName As String
Dim i As Integer
'Call ClearData(strTable)

'if it needs a backslash on the end, add one
If Right(strFolder, 1) <> "\" Then
   strFolder = strFolder & "\"
End If

mypath = strFolder
ChDir (strFolder)
myfile = Dir(mypath)
ChDir (mypath)
myfile = Dir("")
i = 1

Do While myfile <> ""

                'Format the excel report
                 strPathFileName = mypath & myfile

                'use for unpresented
                   Call formatExcelUnPresentedForImport(strPathFileName)

            i = i + 1

        myfile = Dir()
Loop
End Function



Function formatExcelUnPresentedForImport(filePath As String)

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Note:
' Called from CleanAndImportUnpresentedInAGivenFolder when
' importing Unpresented reports
'
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

On Error GoTo formatExcelUnPresentedForImport_Error

Dim strFilePath As String
Dim strReportType As String
Dim i As Integer
Dim iTotal_Row
Dim Lastrow As Long
Dim iCol As Integer

Dim appExcel As excel.Application
Dim wkb As excel.Workbook
Dim sht As Worksheet
Dim rng As Range


strReportType = reportType
strFilePath = filePath

Set appExcel = New excel.Application
 appExcel.Visible = False

           'Define the worksheet
            Set wkb = appExcel.Workbooks.Open(strFilePath, ReadOnly:=False)

          'Turn off error msg: "minor loss of fidelity" if you are sure no data will be lost
            wkb.CheckCompatibility = False

            'Expand Column to avoid scientific notation
            appExcel.Columns("A:A").EntireColumn.AutoFit

           'Find last row

           'FAILS HERE ON SECOND ITERATION OF LOOP:
            Range("A1").Select
            ActiveCell("A1").Select
            Selection.End(xlDown).Select

            'Delete the last 3 rows of totals
            ActiveCell.offset(-2, 0).Select
            Selection.EntireRow.Delete
            Selection.EntireRow.Delete
            Selection.EntireRow.Delete

           'Add a TRIM of Cash Amount Field2 at column L
            Range("L2").Select
            ActiveCell.FormulaR1C1 = "=TRIM(RC[-9])"
            Range("L2").Select

            'Copy it to rest of cells to bottom
            Selection.Copy
            Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
            Selection.AutoFill Destination:=Range("L2:L" & Lastrow), Type:=xlFillDefault
            Range("L2:L" & Lastrow).Select

            'Delete original unformatted unpresented
            Selection.Copy
            ActiveSheet.Paste
            Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
            :=False, Transpose:=False

            'Delete all the rows except Unpresented
            Range("B:B,C:C,D:D,E:E,F:F,G:G,H:H,I:I,J:J,K:K").Select
            Range("K1").Activate
            Selection.Delete Shift:=xlToLeft

            'Add a Header
            Range("B1").Select
            ActiveCell.FormulaR1C1 = "Unpresented"

        wkb.Save
        wkb.Close
        appExcel.Quit
        Set wkb = Nothing
        Set appExcel = Nothing

 On Error GoTo 0
 Exit Function

  formatExcelUnPresentedForImport_Error:
        Set wkb = Nothing
        Set appExcel = Nothing

strMessage = "Error " & err.Number & " (" & err.Description & ") in procedure formatExcelUnPresentedForImport of Module modExternalExcelClean."
strMessage = strMessage & " Application will stop processing now." & vbNewLine
strMessage = strMessage & "Please note or copy this error message and contact application developer for assistance."
MsgBox strMessage, vbCritical + vbOKOnly, "Error"
End
End Function

1 个答案:

答案 0 :(得分:0)

猜测您第二次没有迭代Excel文件,因此会抛出错误。要以ELI5样式调试它,请更改您的代码:

Do While myfile <> ""
    MsgBox myFile
    'Format the excel report
    strPathFileName = mypath & myfile
    'use for unpresented
    Call formatExcelUnPresentedForImport(strPathFileName)
    i = i + 1
    myfile = Dir()
Loop

并且每次都要注意MsgBox。它是否显示出您认为应该展示的内容?