2014-03-05 82 views
0

我有訪問數據庫和幾個查詢那裏。VBA:將參數傳遞到訪問查詢中

最近我添加了一個帶有兩個單選按鈕(值爲1和2)的選項組到我的表單。

我試圖實現的是:當第一個單選按鈕被檢查時,查詢應該只返回國家的數據;當第二個被檢查時,查詢應該只返回城市的數據。

我創造了一些代碼:

Private Sub Command54_Click() 

Dim dtps As String 

If Frame45.Value = 1 Then 
    dtps = "101,103,1104,1105" 
Else 
    dtps = "105,125,127,129,131,133,145,147,149,151,153,171,173,175,177,179,181,1105,1125,1127,1129,1131,1133,1141,1145,1147,1149,1151,1153,104,124,126,128,130,132,144,146,148,150,152,170,172,172,176,178,180,1104,1124,1126,1128,1130,1132,1144,1146,1146,1148,1150,1152" 
End If 


DoCmd.OpenQuery "test1", acViewNormal, acEdit 

End Sub 

眼下查詢 「測試1」 很簡單:

"Select * from MyTable" 

而且我的想法是將其改爲:

"Select * from MyTable Where CountryCodeID IN (@dtps)" 

不任何人都知道如何做到這一點?


我也試過是使用功能:

我的查詢代碼:

Select * from MyTable Where CountryCodeID IN (getcountrycode()) 

功能代碼:

Private Sub Command54_Click() 

'MsgBox Frame45.Value 

DoCmd.OpenQuery "test1", acViewNormal, acEdit 

End Sub 

Public Function getcountrycode() 

Dim dtps As String 

If Frame45.Value = 1 Then 
    dtps = "101,103,1104,1105" 
Else 
    dtps = "101,103,105,125,127,129,131,133,145,147,149,151,153,171,173,175,177,179,181,1105,1125,1127,1129,1131,1133,1141,1145,1147,1149,1151,1153,104,124,126,128,130,132,144,146,148,150,152,170,172,172,176,178,180,1104,1124,1126,1128,1130,1132,1144,1146,1146,1148,1150,1152" 
End If 

getcountrycode = dtps 

End Function 

它會返回錯誤:「未定義功能「 getcountrycode'in expression

回答

0

它可能會更容易簡單地構建查詢:

sSQL = "SELECT * FROM MyTable Where CountryCodeID IN (" & dtps & ")" 

If Not IsNull(DLookup(_ 
    "Test1", "MSysObjects", "[Name]='Test1' AND Type= 5")) Then 
    ''Query exists, overwrite the sql permanently 
    CurrentDb.QueryDefs("Test1").SQL = sSQL 
Else 
    ''Note that you cannot have a query with the same name as a table, 
    ''so you might need to check that, too. 
    CurrentDb.CreateQueryDef "Test1", sSQL 
End If 

DoCmd.OpenQuery "test1", acViewNormal, acEdit 

而不是簡單地打開一個查詢,我強烈建議您綁定的查詢方式。