我正在学习适应在VBA中使用的代码以在VB.Net中工作,而且我很难确定如何从查询中获取值并将其存储在字符串中。
我知道查询有效,但是当我尝试将VBA存储在字符串“ Valor”中时,VBA异常,会发生错误,如错误图像中所示。
Sub Main()
Dim VD As New ADODB.Connection
Dim RS As New ADODB.Recordset
Dim Valor As String
VD.ConnectionString = "DSN=XXX;UID=XXX;PWD=XXX;"
VD.Open()
RS = VD.Execute("SELECT Cod_PA FROM Tab_SERVICO WHERE Cod_PA='VIADELMAR'")
If Not (RS.BOF And RS.EOF) Then
Valor = RS.Fields("Cod_PA").Value
Else
Valor = "Não existe!"
End If
RS.Close()
VD.Close()
MsgBox(Valor)
End Sub
答案 0 :(得分:1)
Private Sub Example()
Dim VD As New System.Data.OleDb.OleDbConnection ' ADODB.Connection
Dim CMD As New System.Data.OleDb.OleDbCommand ' ADODB.Recordset
Dim Valor As String
VD.ConnectionString = "DSN=XXX;UID=XXX;PWD=XXX;"
VD.Open()
CMD.Connection = VD
CMD.CommandText = "SELECT Cod_PA FROM Tab_SERVICO WHERE Cod_PA='VIADELMAR'"
''Two (or more) possible choices for getting data:
''Option 1
''If you Then just want 1 col / 1 row, you can simply .ExecuteScalar()
Valor = CMD.ExecuteScalar 'Simple. Sometimes too simple.
''Option 2 - If your query will return multiple columns and rows then
'' you need to get data with a DataAdapter and store it
'' in a DataSet or DataTable. Example: (uncomment below)
'Dim DT As New DataTable
'Dim DA As New System.Data.OleDb.OleDbDataAdapter(CMD)
'DA.Fill(DT)
'If (DT.Rows.Count > 0) Then
' Valor = DT.Rows(0)("Cod_PA")
'Else
' Valor = "Não existe!"
'End If
''clean up. Just like: Set VD = Nothing
'DA.Dispose()
CMD.Dispose()
VD.Close()
VD.Dispose()
MsgBox(Valor)
End Sub