Private Sub Command0_Click()
' On Error Resume Next
Dim i As Long
Dim rec As ADODB.Recordset, rst As ADODB.Recordset
Dim thePath '目的文件夹
Dim fso As New FileSystemObject, fldr As Folder '引用microsoft scripting runtime
Dim xlApp As Object, xlBook As Object, j As Integer
Set rec = New ADODB.Recordset
rec.Open "select 省份,医院 from demo group by 省份,医院 order by 省份,医院", CurrentProject.Connection, adOpenStatic, adLockReadOnly
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Dim A, B As Long
For i = 1 To rec.RecordCount
If Dir(CurrentProject.Path & "\导出", vbDirectory) = "" Then '如果目的目录不存在,就创建文件夹
Set fldr = fso.CreateFolder(CurrentProject.Path & "\导出")
End If
If Dir(CurrentProject.Path & "\导出\" & Trim(rec.Fields(0)), vbDirectory) = "" Then '如果目的目录不存在,就创建文件夹
Set fldr = fso.CreateFolder(CurrentProject.Path & "\导出\" & Trim(rec.Fields(0)))
End If
Set rst = New ADODB.Recordset
rst.Open "select * from demo where 省份='" & rec.Fields(0) & "' and 医院='" & rec.Fields(1) & "'", CurrentProject.Connection, adOpenStatic, adLockReadOnly
If rst.RecordCount > 0 Then
Set xlBook = xlApp.Workbooks.Add
For j = 1 To rst.Fields.Count
xlBook.Sheets(1).Cells(1, j) = rst.Fields(j - 1).Name
Next j
'xlBook.Sheets(1).Range("A2").CopyFromRecordset rst,OLE或长文本字段会有错误
For A = 1 To rst.RecordCount
For j = 1 To rst.Fields.Count
xlBook.Sheets(1).Cells(A + 1, j) = rst.Fields(j - 1)
Next j
Next A
xlBook.SaveAs CurrentProject.Path & "\导出\" & Trim(rec.Fields(0)) & "\" & rec.Fields(1) & ".xls"
xlBook.Close
Set xlBook = Nothing
End If
rec.MoveNext
Next i
MsgBox "导出完毕!"
Shell "explorer /e,/select," & CurrentProject.Path & "\导出", 1
End Sub