2017-08-13 112 views
-2

我想在VB 6.0上找一個小程序來查找數據庫中的記錄,並在基於組合框選擇的文本框中打印它,但是我未能找到一個代碼允許我這樣做。使用組合框搜索並在文本框中篩選結果

請任何幫助。

Dim adoCon 
Dim adoRs 
Dim strSQL As String 


Dim strDB As String 

'Change YourDatabaseName to actual database you have 
strDB = "c:\path\YourDatabaseName.accdb" 



Set adoCon = CreateObject("ADODB.Connection") 
adoCon.Open "Provider = Microsoft.ACE.OLEDB.12.0; " & _ 
"Data Source = " & strDB & ";" & _ 
"Persist Security Info = False;" 

'Change Table1 to your table name in MS Access 
'change the name of combobox and the fieldname in MS Access table 
' 
'''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''' 
' if combo is numeric 
strSQL = "SELECT [fieldNameToReturn] FROM Table1 Where [fieldName] = " + [combo].Value + ";" 

' if combo is text 
'strSQL = "SELECT [fieldNameToReturn] FROM Table1 Where [fieldName] = '" + [combo].Value + "';" 
'''''''''''''''''''''''''''''''''''''''''''''''''' ''''''''''''''''''''''' 

Set adoRs = CreateObject("ADODB.Recordset") 

'Set the cursor type we are using so we can navigate through the recordset 
adoRs.CursorType = 2 

'Set the lock type so that the record is locked by ADO when it is updated 
adoRs.LockType = 3 

'Open the tblComments table using the SQL query held in the strSQL varaiable 
'adoRs.Open strSQL, adoCon 

If Not adoRS.Eof() Then 
[yourTextBox] = adoRs(0) 
End If 
adoRs.Close 
adoCon.Close 
Set adoRs = Nothing 
Set adoCon = Nothing 
+0

我覺得在VB6,我們使用的「&」,而不是「+」字符串連接.... – Khan

+0

VB.NET是不一樣的東西VB6 – Plutonix

+0

也許你應該取消對打開記錄和使用的線路您的對象和控件名稱在何處指示。 – June7

回答

0

下面的「BOF」不是拼寫錯誤。如果記錄集爲空(查詢未返回記錄),BOF將爲true。

adoRs.Open strSQL, adoCon 
If Not adoRS.BOF Then 
    'If not _BOF_ we have records so load the first record 
    adoRs.MoveFirst 

    'If first field is a string then use this 
    [yourTextBox] = adoRs.Fields(0).Value 

    'If first field is numeric then use this 
    [yourTextBox] = CStr(adoRs.Fields(0).Value) 
Else 
    Msgbox "No records returned." 
End If 

如果你處理多個記錄,你仍然會做的MoveFirst,然後循環播放,直到EOF是真實的,處理每個記錄。當沒有更多記錄要處理時,MoveNext將設置EOF = True。

adoRs.Open strSQL, adoCon 
If Not adoRS.BOF Then 
    'If not _BOF_ we have records so load the first record 
    adoRs.MoveFirst 

    Do While Not adoRS.EOF 
     'Process records here 
     '. 
     '. 
     '. 
     adoRS.MoveNext 
    Loop 
Else 
    Msgbox "No records returned." 
End If 
+0

它在adoR上返回一個錯誤「參數錯誤的類型超出了可接受的範圍或者相互衝突」。打開strSQL,adoCon行,請你幫忙。 – Mahmoud

+0

這是VB6,所以你需要定義你的變量類型:Dim adoCon As ADODB.Connection和Dim adoRS as ADODB.Recordset。爲此,您必須通過VB6 Project-> References菜單設置對Microsoft ActiveX數據對象的引用。 – thx1138v2