2017-08-13 108 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