我認爲這應該很簡單,但我找不到正確的方式來做到這一點。我有幾個我想解決的情況的例子,所以我會描述兩者。我認爲他們可能可以用相同的解決方案來處理,但如果沒有,請告訴我。我試圖遍歷一個值列表,併爲每個值運行一個SQL查詢。在一種情況下,這些值是文本,而在另一種情況下,它們是非順序整數。MS Access VBA循環列表
編輯添加:我應該說,值的列表是動態的,它來自在組合框中選擇的ID值列表。現在,這些被存儲爲我的變量名爲item_in_my_text_list和item_in_my_ID_list下面的逗號分隔列表。
事情是這樣的:
item_in_my_text_list = "User-defined, mean, upper-bound"
For Each item_in_my_text_list(i)
'run a query where i is part of the condition
'I want to run the same query first the user-defined metric, then for the mean, then for the upper-bound
'SQL should be "select metric, age, value into scenario where metric = 'user-defined'"
SQL= "Select metric, age, value into scenario WHERE metric = [i]
DoCmd.SetWarnings False
DoCmd.RunSQL SQL
DoCmd.SetWarnings True
SQL = ""
rs.MoveNext
Loop
另一種情況涉及ID值的非連續的數字清單:
item_in_my_ID_list = "7, 9, 15, 88"
For Each item_in_my_ID_list(i)
'run a query where i is part of the condition
'I want to run the same query first for 7, then for 9, then 15, and so on
SQL= "Update thistable set x = y where ID = " & [i]
DoCmd.SetWarnings False
DoCmd.RunSQL SQL
DoCmd.SetWarnings True
SQL = ""
rs.MoveNext
Loop
什麼是建立循環正確的語法?當我嘗試使用Split時,它好像給了我列表中項目的數量,所以當我嘗試將[i]用作查詢條件的一部分時,我得到1,2,3(取決於列表中的項目數量),而不是「用戶定義的」或正確的ID值。
編輯添加我的解決方案。 @mehow的建議讓我知道我需要做什麼。
Set db = CurrentDb
'Delete records for algorithms that aren't selected
Dim DeleteSQL As String
DeleteSQL = "Delete from Scenario WHERE ID not in (" & Me.ListSelect & ")"
db.Execute DeleteSQL, dbFailOnError
DeleteSQL = ""
'for each of the IDs selected, copy the whole scenario
Dim i As Long
For i = 0 To UBound(Split(Me.ListSelect, ","))
'find the records from the scenario table, and copy them for the "upper bound"
SQL = "insert into scenario (a, b, c)"
SQL = SQL & " SELECT a, b, c
SQL = SQL & " FROM Scenario "
SQL = SQL & " WHERE Scenario.Id= " & Trim(Split(Me.ListSelect, ",")(i))
db.Execute SQL, dbFailOnError
SQL = ""
'reset user-defined values for both mean and upper bound
Dim allMetrics As String
allMetrics = "Central tendency, Upper bounding"
Dim thisMetric As Long
For thisMetric = 0 To UBound(Split(allMetrics, ","))
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT Parameter FROM AllParameters WHERE Id= " & Trim(Split(Me.ListSelect, ",")(i)))
Dim DefaultSQL As String
If Not (rs.EOF And rs.BOF) Then
Do Until rs.EOF = True
DefaultSQL = "UPDATE defaults LEFT JOIN scenario ON defaults.Age = Scenario.Age SET Scenario." & rs("Parameter") & " = [defaults].[Value] "
DefaultSQL = DefaultSQL & " WHERE defaults.ID =" & Trim(Split(Me.ListSelect, ",")(i))
DefaultSQL = DefaultSQL & " And defaults.metric = '" & Trim(Split(allMetrics, ",")(thisMetric)) & "'"
db.Execute DefaultSQL, dbFailOnError
DefaultSQL = ""
rs.MoveNext
Loop
End If
rs.Close
Set rs = Nothing
Next
Next
請不要使用SetWarnings和RunSQL,看到http://stackoverflow.com/questions/11213892/whats-the- docmd-setwarnings-and-currentdb-execution/11213943#11213943 – Fionnuala
@Remou,謝謝你的聯繫。我很高興有更好的方法。 – kvibbertj