EXCEL 中多条件查询VBA代码解释

Private Sub CommandButton1_Click()
Application.ScreenUpdating = False '关闭屏幕刷新
Dim cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strsql As String
cnn.Open "provider=microsoft.jet.oledb.4.0;extended properties='excel 8.0;hdr=no';data source=" & ActiveWorkbook.FullName

strsql = "select f1,f2,f3,f4 from [数据表$] Where f1=" & Range("g2") & "and f2=" & Range("h2") & "and f3=" & Range("i2") & ""
rs.Open strsql, cnn, adOpenKeyset, adLockReadOnly

Range("a5:e65536").Clear
Range("b5").CopyFromRecordset rs '将 ADO 或 DAO Recordset
Range("A5").Resize([B5].End(4).Row - 4, 1).FormulaR1C1 = "=ROW()-4"

With Range("A4").Resize([B5].End(4).Row - 3, 5)
.Borders.ColorIndex = 5
.Borders(11).Weight = xlThin
.Borders(12).LineStyle = xlContinuous
For i = 7 To 10
.Borders(i).Weight = xlMedium
Next i
End With

rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
Application.ScreenUpdating = True
End Sub
请将每一行的代码解析写在后面

Application.ScreenUpdating = False '关闭屏幕刷新
'建立ADO组件和数据连接
Dim cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset
'定义查询语句
Dim strsql As String
'打开数据库连接,并设置数据源为本工作簿。注意,这是2003版本滴。
cnn.Open "provider=microsoft.jet.oledb.4.0;extended properties='excel 8.0;hdr=no';data source=" & ActiveWorkbook.FullName
‘设置数据源为数据表,并选择字段1~字段4。必须满足条件:字段1的值为G2,字段2的为H2,字段3为I2的值。
strsql = "select f1,f2,f3,f4 from [数据表$] Where f1=" & Range("g2") & "and f2=" & Range("h2") & "and f3=" & Range("i2") & ""
'以只读方式打开ADO记录集。
rs.Open strsql, cnn, adOpenKeyset, adLockReadOnly
’清空A:E列数据
Range("a5:e65536").Clear
'在B5开始粘贴符合条件的记录集。
Range("b5").CopyFromRecordset rs '将 ADO 或 DAO Recordset
‘A5输入公式:=row()-4,以获取编号。
Range("A5").Resize([B5].End(4).Row - 4, 1).FormulaR1C1 = "=ROW()-4"
’设置A列格式。
With Range("A4").Resize([B5].End(4).Row - 3, 5)
'边框颜色
.Borders.ColorIndex = 5
'边框粗细(细线)
.Borders(11).Weight = xlThin
'边框样式(连续细线)
.Borders(12).LineStyle = xlContinuous
For i = 7 To 10
'设置第七个到第十个边框为粗线。
.Borders(i).Weight = xlMedium
Next i
End With
‘关闭记录集
rs.Close
'清空记录集以释放内存
Set rs = Nothing
'关闭数据连接
cnn.Close
'清空数据连接以释放内存
Set cnn = Nothing
’更新屏幕
Application.ScreenUpdating = True
'结束语句
End Sub
温馨提示:答案为网友推荐,仅供参考
相似回答