|
jjj2123456? 发表于 2015-2-9 18:30
工作表和数据库的表命名一致,赵老师我想做一个循环查询到各个工作表,可以实现吗。
其他的数据库表字段 ...
添加一个有3个页面的多页控件,每个页面代表一个数据表:- Dim cnn As ADODB.Connection '模块级变量
- Dim rs As ADODB.Recordset
- Dim myTable As String
- Dim arr As Variant
- Private Sub CommandButton2_Click() '退出
- Unload Me
- End Sub
- Private Sub MultiPage1_Change()
- Sheets(MultiPage1.Pages(MultiPage1.Value).Caption).Activate
- End Sub
- Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) '关闭窗体时断开连接,释放内存
- On Error Resume Next
- rs.Close
- cnn.Close
- Set rs = Nothing
- Set cnn = Nothing
- End Sub
- Private Sub UserForm_Initialize() '开启窗体设置18个ComboBox
- Dim i As Integer
- Dim j As Integer
- Dim SQL As String
- arr = Array("ID号", "编号", "单号", "年", "月", "日")
- myTable = ActiveSheet.Name
- Set cnn = New ADODB.Connection
- cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & ThisWorkbook.Path & "\jiageguanli.mdb" '连接数据库
- With MultiPage1 '添加一个多页控件
- .Value = ActiveSheet.Index - 1
- For j = 0 To 2
- For i = 1 To 6
- SQL = "SELECT DISTINCT " & arr(i - 1) & " FROM " & .Pages(j).Caption
- Set rs = cnn.Execute(SQL)
- Me.Controls("ComboBox" & j * 6 + i).Column = rs.GetRows
- Next
- Next
- End With
- End Sub
- Private Sub CommandButton1_Click() '确定
- Dim s As String
- Dim i As Integer
- Dim j As Integer
- Dim SQL As String
- j = MultiPage1.Value
- If Len(Me.Controls("ComboBox" & j * 6 + 1).Value) Then s = s & " and " & arr(0) & "=" & Me.Controls("ComboBox" & j * 6 + 1).Value
- For i = 2 To 6
- If Len(Me.Controls("ComboBox" & j * 6 + i).Value) Then s = s & " and " & arr(i - 1) & "='" & Me.Controls("ComboBox" & j * 6 + i).Value & "'"
- Next
- SQL = "SELECT * FROM " & MultiPage1.Pages(j).Caption
- If Len(s) Then SQL = SQL & " WHERE " & Mid(s, 6)
- Set rs = cnn.Execute(SQL)
- If Not rs.EOF Then
- With Sheets(MultiPage1.Pages(j).Caption)
- .UsedRange.Offset(1).ClearContents
- .[a2].CopyFromRecordset rs
- End With
- Else
- MsgBox "没有查到"
- End If
- End Sub
复制代码 |
评分
-
1
查看全部评分
-
|