我有一个连接到excel的Access数据库。我需要使用Excel中的记录集中的搜索条件查找记录
MyTable
,其中包含数据超过10列Worksheets("Sheet1").Cells(1, 1)
我需要的是,macro必须循环遍历column7和column 10中的任何匹配字符串,并将三列(column1,column7和column 10)中的相应记录集复制到Worksheets(“ALL”)。Cells(3, 1)......细胞(3,3)等
第7列和第10列中的数据在一个记录单元格中将包含500多个字符文本。搜索字符串可能出现在多个记录单元格中;因此输出将在多个记录集中找到。
我们还有instr函数和SQL查询的其他选项吗?
strSQL = "SELECT Qn_No, Categories, Page_Text FROM MyTable WHERE Categories = '" & str1 & "' or “&Page_Text &"
非常感谢任何帮助。我提前感谢。
答案 0 :(得分:0)
这应该有效。 请记住输入访问文件的路径。
Sub test()
Dim p As String 'path of access file
Dim dbConn As Object, dbData As Object
Dim ws As Worksheet 'worksheet where results will be pasted
Dim s As String 'text searched
Dim sql As String 'select statement
Dim cs As String 'connection string
Dim v As Variant 'stores query result
s = Worksheets("Sheet1").Cells(1, 1)
Set ws = Worksheets("ALL")
sql = "SELECT Qn_No, Categories, Page_Text " & _
"FROM MyTable " & _
"WHERE Categories = '" & s & "' OR " & _
"Page_Text = '" & s & "'"
'################################
cs = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & p & ";Persist Security Info=False;"
Set dbConn = CreateObject("ADODB.Connection")
Set dbData = CreateObject("ADODB.Recordset")
dbConn.ConnectionString = cs
dbConn.Open
With dbData
.ActiveConnection = dbConn
.Source = sql
.LockType = 1
.CursorType = 2
.Open
End With
'Connection to access ready
'###############################
On Error GoTo NoRecords 'no records
v = dbData.GetRows
On Error GoTo 0
'v is zero based array, an records are transposed
'Handle it as you wish
ws.Cells(1, 1).Resize(UBound(v, 1) + 1, UBound(v, 2) + 1).Value = v
GoTo Quitter
'######################
NoRecords:
MsgBox ("No Records Found")
Quitter:
dbData.Close
Set dbData = Nothing
dbConn.Close
Set dbConn = Nothing
End Sub