|
再次改下,标题问题已经解决了。- Const adUseClient = 3
- Const adModeShareDenyWrite = 8
- Const adModeReadWrite = 3
- Const adModeRead = 1
- Dim AdoConn As Object, AdoRst As Object
- Sub 提取数据()
- Dim sht As Worksheet
- Dim strSql As String
- Dim strCode As String
- Dim lLastRow As Long
- Dim arrTitle()
- Dim i As Long
-
- strCode = Application.InputBox("请输入要查找的代码字段值" & vbCrLf & vbCrLf & "请注意大小写", Type:=2)
- If strCode = "False" Then
- MsgBox "没有输入查询字段或没有确定,结束"
- Exit Sub
- End If
- For Each sht In Worksheets
- With sht
- If .Name <> "提取数据" Then
- lLastRow = .Cells(Rows.Count, 1).End(xlUp).Row
- strSql = strSql & "select * from [" & sht.Name & "$A1:O" & lLastRow & "] where 代码='" & strCode & "' union all "
- End If
- End With
- Next
- If Len(strSql) = 0 Then Exit Sub
- strSql = Left(strSql, Len(strSql) - 11)
- If ADOQuery(ThisWorkbook.FullName, strSql) Then
- With Worksheets("提取数据")
- Application.ScreenUpdating = False
- .UsedRange.ClearContents
- ReDim arrTitle(1 To AdoRst.Fields.Count)
-
- For i = 1 To UBound(arrTitle)
- arrTitle(i) = AdoRst.Fields(i - 1).Name
- Next
-
- .Range("a1").Resize(, UBound(arrTitle)).Value = arrTitle
- If AdoRst.RecordCount > 0 Then
- .Range("a2").CopyFromRecordset AdoRst
- MsgBox "查询完毕" & vbCrLf & vbCrLf & "一共查询到 " & AdoRst.RecordCount & " 条记录", vbInformation + vbOKOnly
- Else
- MsgBox "没有查询到符合条件的数据" & vbCrLf & "请检查代码字段"
- End If
-
- Application.ScreenUpdating = True
- End With
- End If
- End Sub
- Function ADOQuery(strFullname As String, Optional strSql As String, Optional blnHasHeader As Boolean = True) As Boolean
- Dim StrConn$
- Set AdoConn = CreateObject("ADODB.Connection")
- StrConn = "Provider= Microsoft.Jet.OLEDB.4.0;" & _
- "Data Source='" & strFullname & "';Extended Properties='Excel 8.0;HDR=" & blnHasHeader & ";imex=1';"
-
- On Error GoTo ErrorHandler
- With AdoConn
- .CommandTimeout = 5
- .ConnectionTimeout = 5
- .CursorLocation = adUseClient
- .Mode = adModeRead
- .ConnectionString = StrConn
- .Open
- End With
- Set AdoRst = AdoConn.Execute(strSql)
- ADOQuery = True
- Exit Function
- ErrorHandler:
- MsgBox Err.Number & vbCrLf & Err.Description
- Set AdoRst = Nothing
- Set AdoConn = Nothing
- End Function
复制代码 |
|