Generic Search Function
กระทู้เก่าบอร์ด อ.สุภาพ ไชยา

 249   1
URL.หัวข้อ / URL
Generic Search Function

ถามไว้ที่ http://www.utteraccess.com/forums/showflat.php?Cat=&Board=access_2000&Number=154135&page=0&view=collapsed&sb=5&o=7&fpart=1&vc=1&PHPSESSID= 
 
เขาต้องการที่จะเขียนฟังก์ชันในการค้นหาข้อมูลรายการที่ต้องการ ในฟีลด์ใดๆ ของตารางเป้าหมาย 
 
ผมเลยลองทำฟังก์ชันทั้งของ DAO และ ADO ดังนี้ 
 
Function IfExists(strItem As String, strTable As String, strField As String) As Boolean 
Dim dbs As DAO.Database, rst As DAO.Recordset, strSQL As String 
Set dbs = CurrentDb 
strSQL = "Select " & strField & " From " & strTable & " Where " & strField & "='" & strItem & "'" 
Set rst = dbs.OpenRecordset(strSQL) 
If Not rst.EOF Then 
    IfExists = True 
Else 
    IfExists = False 
End If 
rst.Close 
dbs.Close 
Set rst = Nothing 
Set dbs = Nothing 
End Function 
 
 
Function IfExists2(strItem As String, strTable As String, strField As String) As Boolean 
Dim dbs As DAO.Database, rst As DAO.Recordset, strSQL As String 
Set dbs = CurrentDb 
strSQL = "SELECT Count(*) " _ 
    & "FROM " & strTable _ 
    & " HAVING " & strField & "='" & strItem & "'" 
 
Set rst = dbs.OpenRecordset(strSQL) 
If rst(0) >= 1 Then 
    IfExists2 = True 
Else 
    IfExists2 = False 
End If 
rst.Close 
dbs.Close 
Set rst = Nothing 
Set dbs = Nothing 
End Function 
 
Function IfExists3(strItem As String, strTable As String, strField As String) As Boolean 
    Dim cnn As New ADODB.Connection 
    Dim rst   As New ADODB.Recordset 
     
    ' Open the connection 
    Set cnn = CurrentProject.Connection 
     
    ' Open the forward-only, read-only recordset 
    rst.Open "Select Count(*) From " & strTable & _ 
         " Where " & strField & "= '" & strItem & "'", cnn, _ 
          adOpenForwardOnly, adLockReadOnly 
    If rst(0) >= 1 Then 
        IfExists3 = True 
    Else 
        IfExists3 = False 
    End If 
    rst.Close 
    cnn.Close 
    Set rst = Nothing 
    Set cnn = Nothing 
 
End Function 
 
การนำไปใช้ 
 
? IfExists3("กส-380001","AllFarmers","รหัสเกษตรกร") 
 
ถ้ามีข้อมูลนี้อยู่ จะได้ค่า True แต่ถ้าไม่มีจะได้ค่า False 
 
ลองปรับไปใช้ดูครับ  *** Edited by Supap Chaiya *** 17/5/2546 15:14:01

1 Reply in this Topic. Dispaly 1 pages and you are on page number 1

1 @R02919
ขอเป็น file ตัวอย่างได้มัยค่ะ
@ ประกาศใช้งานเว็บบอร์ดใหม่ => บอร์ดเรียนรู้ Access สำหรับคนไทย
แล้วจะใส่ลิ้งอ้างอิงมาที่โพสต์เก่านี้หรือไม่ก็ตามสะดวกครับ
Time: 0.0489s