2016-01-21 64 views
1

在vbscript中執行用於將字符串解析爲內聯指令。但是,我不能用它來打破對於循環。以下將無法正常工作:vbscript執行:退出外部對於

For i = 1 To 10 
    msgbox i 
    Execute("Exit For") 
Next 

有人知道它的任何解決方法嗎?或者任何方式退出子/退出功能的工作?我試過ExecuteGlobal,但它也引發「無效退出指令」錯誤。

我在整個我的代碼中用它作爲「導入」的一種形式,並且重新實現另一種導入形式會很費時,所以我正在尋找一種方法在考慮更改之前使其工作該項目。

編輯:多個示例

總之,我試圖做一個半抽象方法的部分覆蓋,但不能使用退出對於對抗對於外的執行塊。

Dim names_array 'this array will be populated in another Sub 

'this method will loop though all elements of an array and insert some items into a database... 
'but the method does not know (how to)/(if it will really) insert into the database! 
'all it knows is: it has to loop though the array... and, if needed, finish earlier 
'the insertion part will have to be described before running, like a 'partial override' of an abstract method 
'that is because I know how part of the method must be, but the details will be diferent for each database 
'I don't want to override every method entirely! 
Sub insert_into_database 
    For i = 0 To UBound(names_array) 
     name = names_array(i) 
     Execute(core_op) 'here comes the core operation, it is what I override! 
    Next 
End Sub 

'for some databases, core_op will be simple: 
core_op = "objRecordSet.Open ""INSERT INTO videos (title, date_time) VALUES ('"" & name & ""', Now)"", objConnection" 

'for others, it may be complex: 
core_op =   "If name=""18+ only"" Then" 
core_op = core_op + " MsgBox ""You tried to insert nasty things. System will now halt.""" 
core_op = core_op + " Exit For" 
core_op = core_op + "Else" 
core_op = core_op + " objRecordSet.Open ""INSERT INTO videos (title, date_time) VALUES ('"" & name & ""', Now)"", objConnection" 
core_op = core_op + "End If" 
'the string won't be loaded this way, it will come from an external file 
'there are other methods that operate like this, but not all of them need Exit For 

這更接近我的項目。現實是:覆蓋的代碼將來自外部文件,並將存儲在字典中。

對不起,如果它看起來一團糟,那就是我試圖讓vbscript更像java一樣關於可重用性的方法。

+0

你想做什麼? 'Exit For'可以自己運行,但是如果你在代碼塊中運行它,它會在第一次迭代時退出For循環。 – RLH

+0

這是我想要做的一個例子。在這個例子中是無用的。在我的真實世界項目中,我將發送一些內聯代碼在每個For循環中運行。代碼將有一些指令,但在某些情況下,我想在達到最後一個元素之前完成它。但有時候,不是。我無法破解那是在執行之外。 –

+0

請發佈一個你需要運行的代碼的真實例子。 – RLH

回答

0

Exit語句是複合語句(循環,例程)的一部分,必須在其上下文中「編譯」。所以沒有解決方法,你必須重新設計你的導入策略。也許你應該公佈你目前的做法。

更新WRT評論(該方法的局部覆蓋):

使用GetRef,並通過「函數指針」,或投資於一些類和對象發送到外圍函數。

+0

我害怕這種可能性。我正在導入一些代碼嵌套在for中,就像部分覆蓋方法一樣。我想保留方法的封閉部分。我可以在那裏放置一個Sub/Function,但是Execute給了我更多的可能性......直到我試圖打破外部循環的那天。 –

+0

是的,GetRef解決了一些方法,但我仍然無法從裏面退出。而且我不能在不執行的情況下合併來自不同文件的源代碼。 –

+0

對不起,當我說「合併來自不同文件的源代碼」時,我的意思是「將源文件分發到另一個文件的不同部分」 –