|
zez 发表于 2008-10-13 09:49
Public Sub 查询全部字段前面若干条记录() Dim mydata As String, mytable As String, S ...
Public Sub 利用Like运算符进行模糊查询()
Dim mydata As String, mytable As String, SQL As String
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim i As Integer
Dim f, t As String
f = ActiveWorkbook.Sheets("查殉").Range("D4").Value
t = ActiveWorkbook.Sheets("查殉").Range("D8").Value '清除工作表的部分数据
Rows("15:124").Select
Selection.ClearContents
'指定数据库和数据表
mydata = ThisWorkbook.Path & "\db2.mdb" '指定数据库
mytable = "sheet1" '指定数据表
'建立与数据库的连接
Set cnn = New ADODB.Connection
With cnn
.Provider = "microsoft.jet.oledb.4.0"
.Open mydata
End With
'查询数据表
SQL = "select * from " & mytable & " where f like 't %'"
Set rs = New ADODB.Recordset
rs.Open SQL, cnn, adOpenKeyset, adLockOptimistic
'也可以使用下面的语句
' Set rs = cnn.Execute(SQL)
'复制字段名
For i = 1 To rs.Fields.Count
Cells(15, i) = rs.Fields(i - 1).Name
Next i
'设置字段名字体为加粗并居中对齐
With Range(Cells(1, 1), Cells(1, rs.Fields.Count))
.Font.Bold = True
.HorizontalAlignment = xlCenter
End With
'复制全部数据
Range("A16").CopyFromRecordset rs
'设置工作表格式
ActiveSheet.Cells.Font.Size = 10
ActiveSheet.Columns.AutoFit
'关闭记录集及数据库连接,并释放变量
rs.Close
cnn.Close
Set rs = Nothing
Set cnn = Nothing
End Sub
请老师帮看看,,我加了两条代码,运行不了,应怎样改?? |
|