MS Access VBA数据类型功能不匹配

时间:2014-10-20 15:40:17

标签: ms-access access-vba

我有一个数据库,其中包含水井的位置和与这些水井相关的大量特性。所有表都与WELL_ID(井的名称)链接,这是"短文本"从我所知道的数据类型。在数据库中存在现有的查询,我试图从中获取数据(我不想弄乱表格,以防我犯错并搞砸了。)

我创建了一个表单,用户输入东向和北向的UTM坐标,以及搜索半径,然后点击"搜索"按钮。在单击搜索时,该过程创建[qryUTM_NAD83]的记录集,然后计算每个孔的径向距离,如果它在指定的搜索半径内,则使用INSERT INTO将其存储在新的[Search_Results]表中。

现在,一旦将井确定为满足搜索条件,就会存储WELL_ID,并将其传递给搜索不同查询[qryFormation]的记录集的函数。该查询具有一对多关系,其中存在每个地质层的记录,每个具有相同的WELL_ID(即,每个井具有多个层但是所有这些层具有相同的WELL_ID)。我需要将这些层连接成一个字符串,将它们传递回搜索功能并将其添加到[Search_Results]表中。但是,我在SQL语句中遇到数据类型不匹配错误。

这是我的代码: (我已经省略了一些代码部分,以便让所有代码保持简短)

Private Sub SearchButton_Click()

Dim WellID As String, mySQL As String, NewLitho As String

'Creating new recordsets from [qryUTM_NAD83] table
Dim rs1 As DAO.Recordset
'[ZONE] is just user specified, helps me narrow the search a little
Set rs1 = CurrentDb.OpenRecordset("SELECT [qryUTM_NAD83].* " & _
                                  "FROM [qryUTM_NAD83] " & _
                                  "WHERE [ZONE] = " & frmZone, dbOpenDynaset)
'Moving through the recordset
rs1.MoveFirst
Do While Not rs1.EOF
    'calculated radius, r , for this well (omitted)
    If r < SearchRadius Then
        WellID = Val(rs1.Fields("WELL_ID").Value)
        NewLitho = LithoTransform(WellID)
        mySQL = "INSERT INTO [Search_Results] " & _
                "([WELL_ID], [Easting], [Northing], [Radius], [Lithology]) " & _
                "VALUES (" & WellID & ", " & x & ", " & y & ", " & r & ", " & NewLitho & ")"
        CurrentDb.Execute mySQL
        rs1.MoveNext
    End If
Loop
End Sub

功能: (错误发生在&#34;设置rs2 ...&#34; - 数据类型不匹配)

Public Function LithoTransform(CurrentID As String) As String

'CurrentID is the well which was identified as being within the search radius
Dim rs2 As DAO.Recordset
Dim mySQL2 As String

'SQL statement and new recordset of the well we are looking at in the search
Debug.Print CurrentID
mySQL2 = "SELECT [qryFormation].* " & _
         "FROM [qryFormation] " & _
         "WHERE [WELL_ID] = " & CurrentID
Set rs2 = CurrentDb.OpenRecordset(mySQL2, dbOpenDynaset)

'Move through recordset rs2 and concatenating into new string
'Bunch of code here

'Close recordset set it to 'nothing'

End Function

1 个答案:

答案 0 :(得分:1)

由于WELL_ID是文字类型,因此当您在CurrentID子句中包含WHERE时,请在mySQL2 = "SELECT [qryFormation].* " & _ "FROM [qryFormation] " & _ "WHERE [WELL_ID] = '" & CurrentID & "'" 的值附近加上引号。所以最快的解决办法可能是......

Dim db As DAO.Database
Dim qdf AS DAO.QueryDef
Dim rs2 As DAO.Recordset
Dim mySQL2 As String

mySQL2 = "SELECT [qryFormation].* " & _
         "FROM [qryFormation] " & _
         "WHERE [WELL_ID] = [which_id]"
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, mySQL2)
qdf.Parameters("which_id") = CurrentID
Set rs2 = qdf.OpenRecordset

但是,您可以改为切换参数查询,从而避免引号出现问题。这是一个未经测试的例子......

{{1}}

如果我犯了错误,请使用Access帮助系统检查该代码中的函数,语法等。由于您是Access的新手,因此您可以更好地使用其帮助系统。