這應該工作。 請記住輸入訪問文件的路徑。
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
ü確實需要更好的措辭。這不是很清楚你需要什麼。 – Kelaref
@Kelaref感謝您查看此內容,我需要在訪問中搜索一個表中的記錄並將結果輸出到excel中。如果用戶將文本輸入爲「貨幣市場」,則宏應在一個表數據的兩個特定列中查看「貨幣市場」的任何地方的記錄集的輸出。 – Manish