从 excel 搜索 Access 数据库
Searching Access database from excel
我正在尝试编写一个代码,该代码将在 Acess 文件中搜索列中的特定值和 return 该行中的特定值。到目前为止,我只是在使用变量而不是特定值时无法正常工作。
首先,我将要搜索的值设置为单元格 A1 中的变量 var,然后我尝试在我的访问文件的“电压”列中搜索它,当我使用 var 时,出现错误“没有为一个或多个必需参数提供值。"
Option Explicit
Sub getDataFromAccess()
'Cell search value
Dim var As Integer
var = Range("A1").value
Dim DBFullName As String
Dim Connect As String, Source As String
Dim Connection As ADODB.Connection
Dim Recordset As ADODB.Recordset
Dim Col As Integer
'Cells.Clear
'Database path info
DBFullName = "C:\Users\jmike\Desktop\excel
database - Copy\Database.accdb"
'Open the connection
Set Connection = New ADODB.Connection
Connect = "Provider=Microsoft.ACE.OLEDB.12.0;"
Connect = Connect & "Data Source=" & DBFullName & ";"
Connection.Open ConnectionString:=Connect
'Create RecordSet
Set Recordset = New ADODB.Recordset
With Recordset
'Filter Data
Source = "SELECT * FROM Orders Where[Voltage]=var"
.Open Source:=Source, ActiveConnection:=Connection
'Write field names
For Col = 0 To Recordset.Fields.Count - 1
Range("A2").Offset(0, Col).value = Recordset.Fields(Col).Name
Next
'Write recordset
Range("A2").Offset(1, 0).CopyFromRecordset Recordset
End With
ActiveSheet.Columns.AutoFit
Set Recordset = Nothing
Connection.Close
Set Connection = Nothing
End Sub
Source = "SELECT * FROM Orders Where [Voltage]=" & var
您想在变量 var
中搜索 值 ,而不是变量名称。
我正在尝试编写一个代码,该代码将在 Acess 文件中搜索列中的特定值和 return 该行中的特定值。到目前为止,我只是在使用变量而不是特定值时无法正常工作。
首先,我将要搜索的值设置为单元格 A1 中的变量 var,然后我尝试在我的访问文件的“电压”列中搜索它,当我使用 var 时,出现错误“没有为一个或多个必需参数提供值。"
Option Explicit
Sub getDataFromAccess()
'Cell search value
Dim var As Integer
var = Range("A1").value
Dim DBFullName As String
Dim Connect As String, Source As String
Dim Connection As ADODB.Connection
Dim Recordset As ADODB.Recordset
Dim Col As Integer
'Cells.Clear
'Database path info
DBFullName = "C:\Users\jmike\Desktop\excel
database - Copy\Database.accdb"
'Open the connection
Set Connection = New ADODB.Connection
Connect = "Provider=Microsoft.ACE.OLEDB.12.0;"
Connect = Connect & "Data Source=" & DBFullName & ";"
Connection.Open ConnectionString:=Connect
'Create RecordSet
Set Recordset = New ADODB.Recordset
With Recordset
'Filter Data
Source = "SELECT * FROM Orders Where[Voltage]=var"
.Open Source:=Source, ActiveConnection:=Connection
'Write field names
For Col = 0 To Recordset.Fields.Count - 1
Range("A2").Offset(0, Col).value = Recordset.Fields(Col).Name
Next
'Write recordset
Range("A2").Offset(1, 0).CopyFromRecordset Recordset
End With
ActiveSheet.Columns.AutoFit
Set Recordset = Nothing
Connection.Close
Set Connection = Nothing
End Sub
Source = "SELECT * FROM Orders Where [Voltage]=" & var
您想在变量 var
中搜索 值 ,而不是变量名称。