2013-12-16 93 views
1

我有一個使用Excel和具有調用幾個程序一句話VBA:字VBA,最終子失敗

private sub testsub1 
    'some process 

     call testsub2 (a, b, c,...) 

end sub 

private sub testsub2 (byref a as long, byref b as long, byref c as long,...) 
    'some process 

     call testsub3 (a, b, c,...) 

end sub 

private sub testsub3 (byref a as long, byref b as long, byref c as long,...) 
    'some process 

    'calls testub2 if a is less than some value. 
     if a < somevalue then 
     call testsub2 (a, b, c,...) 
     end if 

     documents("doc1").close 'closes a document 
     wb.close 'closes a workbook 
     exc.quit 'closes excel 

     set wb = nothing 
     set exc = nothing 

     msgbox "Analysis complete" 

end sub 

問題:從testsub3調用testsub2後,我無法結束testsub3子。在MsgBox之後,它跳到testsub3中的一些代碼(文檔(「doc1」)。close)---錯誤:錯誤的文件名------>文檔已被關閉。

但是我能夠結束,如果它沒有調用testsub2。

想法?

感謝

注意:由於代碼太長,我不使用循環(錯誤:程序太大)。因此,多個程序/子。

+0

循環不會在這裏工作。代碼太長而無法放入一個循環 - 導致錯誤:過程太大。這就是我創建多個潛艇的原因。 – user2468695

回答

0

嘗試這樣做的工作,沒有錯誤

private sub testsub3 (byref a as long, byref b as long, byref c as long,...) 
    'some process 

    'calls testub2 if a is less than some value. 
     if a < somevalue then 
     call testsub2 (a, b, c,...) 

     else 

     documents("doc1").close 'closes a document 
     wb.close 'closes a workbook 
     exc.quit 'closes excel 

     set wb = nothing 
     set exc = nothing 

     msgbox "Analysis complete" 

    end if 

end sub 
+0

如果testsub2調用testsub3(就像在你的第一個例子中那樣),我認爲你不應該從testsub3調用testsub2(a,b,c,...)。我希望你的解決方案會在'a

0

也許你可以嘗試這樣的:

Private analysisComplete As Boolean 

Private Sub testsub1() 
    'some process 

     analysisComplete = False 

     Call testsub2(a, b, c,...) 

End Sub 

Private Sub testsub2(ByRef a As Long, ByRef b As Long, ByRef c As Long,...) 
    'some process 

     Call testsub3(a, b, c) 

End Sub 

Private Sub testsub3(ByRef a As Long, ByRef b As Long, ByRef c As Long,...) 
    'some process 

    'calls testub2 if a is less than some value. 
     If a < someValue Then 
     Call testsub2(a, b, c) 
     End If 

     If Not analysisComplete Then 

     Documents("doc1").Close 'closes a document 
     wb.Close 'closes a workbook 
     exc.Quit 'closes excel 

     Set wb = Nothing 
     Set exc = Nothing 

     MsgBox "Analysis complete" 

     analysisComplete = True 

    End If 

End Sub 

所以它執行testsub3的最後部分只有一次。

+0

這似乎可能會導致他目前遇到的相同問題,除非所有數據都是順序的。 – engineersmnky

+0

我假設有時他退出循環,然後運行的第一個testsub3(堆棧頂部)將關閉文檔,然後下一個(在堆棧中較低)將不會嘗試再次關閉該文檔。 – brWHigino

+0

正確,但他正在做的東西與文件,因此關閉它會拋出一些錯誤,沿着'不能做什麼,當......關閉'的線' – engineersmnky