如何从数据库中填充文本框的值?

时间:2016-11-30 16:03:55

标签: sql vba ms-access textbox access-vba

这是我到目前为止的代码,我尝试查找我的问题的解决方案,但找不到我正在寻找的确切内容。我在Access中这样做。

Dim rs As DAO.Recordset
sSQL = "SELECT Building FROM tblDepartment WHERE Department_ID = 
'" & Me.cboDepartment & "'"
Set rs = CurrentDb.OpenRecordset(sSQL)
Me.txtLocation = rs.Fields(1).Value

我也试过这个:

Dim db As DAO.Database
Set db = CurrentDb()
sSQL = "SELECT Building FROM tblDepartment WHERE " _
& "Department_ID = '" & Me.cboDepartment.Value & "'"
Me.txtLocation.Value = db.Execute(sSQL)

第三次尝试是这样的:

Sub spGetBuilding()
Dim rs As DAO.Recordset
sSQL = "SELECT Building FROM tblDepartment WHERE Department_ID = '" & Me.cboDepartment & "'"
Set rs = CurrentDb.OpenRecordset(sSQL)

If rs.RecordCount > 0 Then
    Me.txtLocation = rs.Fields(0).Value
Else
    Me.txtLocation = 0
End If

Set rs = Nothing
End Sub

但它返回了错误消息"标准表达式中的数据类型不匹配"

我发现导致此错误的原因是因为某些值不包含构建值。我试图设置参数,以便WHERE还包括一个" AND Building IS NOT NULL"消除摆脱空值。但同样的错误仍然存​​在。

2 个答案:

答案 0 :(得分:1)

最肯定的原因是你的组合框架。 如果您使用的是超过1列的组合框,则隐藏具有ID的列,因为您使用查询来填充所述组合框,然后您将基础ID传递给选择查询。

要将组合框中写入的内容实际传递给select子句,请使用它的text属性。

sSQL = "SELECT Building FROM tblDepartment WHERE " _
& "Department_ID = '" & Me.cboDepartment.Text & "'"

答案 1 :(得分:1)

对于这样一个简单的任务, DLookup 要简单得多,如果没有找到建筑物,它会返回Null。

另外,请忽略单引号,因为 Department_ID 很可能是数字:

Me!txtLocation.Value = DLookup("Building", "tblDepartment", "Department_ID = " & Me!cboDepartment.Value & "")