0

大家好,我一直在努力寻找解决我的错误的方法,但我在网上找不到类似的例子来解决这个问题。我有一个变量(i)在进入循环时设置为 3,然后进入第一个 if 语句它运行良好,文件被复制并插入到工作表 3 但是一旦它增加到 4 并进入第二个 if 语句我得到一个错误 9

      Set wks4 = wkb.Sheets(i)

这是下面完整代码的一部分,希望你们能帮助我。

Set Excel_App = New EXCEL.Application
Excel_App.Visible = False
Set wkb = EXCEL.Workbooks.Add
Set wks = wkb.Sheets(1) 'want first sheet

With wks
    ......
    'extra code involing input to sheet 1 
End With


    Dim wkb2 As EXCEL.Workbook
    Set wkb2 = EXCEL.Application.Workbooks.Open(strDir & "\DETAILS.xlsx")

        wkb2.ActiveSheet.Cells.Select
        Selection.Copy
        Set wks2 = wkb.Sheets(2)
        With wks2
            .Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        End With
        wkb2.Close

i = 3
      Do While Not rstTypes.EOF

            If rstTypes![TYPE] Like "GROUPED" Then
                    DoCmd.OutputTo acOutputReport, "EXCEL_CBD_CAP_CR", acFormatXLS, strDir & "\SAMEDAY_NEXTDAY_FUTURE.xls", 0
                    Dim wkb3 As EXCEL.Workbook
                    Set wkb3 = EXCEL.Application.Workbooks.Open(strDir & "\SAMEDAY_NEXTDAY_FUTURE.xls")

                    wkb3.ActiveSheet.Cells.Select
                    Selection.Copy
                    Set wks3 = wkb.Sheets(i)
                    With wks3
                        .Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                                :=False, Transpose:=False
                    End With
                    wkb3.Close                   
                    i = i + 1
            End If

            If rstTypes![TYPE] Like "GROUPED2" Then
                DoCmd.OutputTo acOutputReport, "EXCEL_ND/FUT_CAP_CR", acFormatXLS, strDir & "\NEXTDAY_FUTURE.xls", 0
                    Dim wkb4 As EXCEL.Workbook
                    Set wkb4 = EXCEL.Application.Workbooks.Open(strDir & "\NEXTDAY_FUTURE.xls")


                    wkb4.ActiveSheet.Cells.Select
                    Selection.Copy
                    Set wks4 = wkb.Sheets(i)
                    With wks4
                        .Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                                :=False, Transpose:=False
                    End With
                    wkb4.Close
                    Kill (strDir & "\NEXTDAY_FUTURE.xls")

                    i = i + 1
            End If
            rstTypes.MoveNext
 Loop
4

3 回答 3

2

这意味着第 i 个工作表不存在,每次您想与策略性放置的工作表交互时都检查一下:

If i > ThisWorkbook.Worksheets.Count then Exit Do

于 2012-11-01T14:03:33.767 回答
1

您可能没有第四张工作表。根据您的代码,我假设您希望工作表存在,因此您需要在运行时添加工作表。您应该将 wks3 和 wks4 的两个工作表设置包装在如下逻辑中:

if wkb.Sheets.Count < i then
   Set wks3 = wkb.sheets.add
end if

然后后来

if wkb.Sheets.Count < i then
   Set wks4 = wkb.sheets.add
end if
于 2012-11-01T14:06:09.273 回答
0

还请记住,与数组不同,第一张纸将是第一张纸。

于 2012-11-01T14:08:29.600 回答