这就是我想要做的事情,如果我走向错误的方向,我会道歉。我正在尝试遍历存储在表t_Directory中的文件路径,如果文件扩展名为“xlsx”,则打开Excel文件并使用Excel工作表的FileID和工作表计数以及工作表名称更新另一个名为t_SheetInfo的表。如果有更有效的方法,有人会花点时间检查我到目前为止所得到的东西,或者引导我朝着正确的方向前进吗?我不是百分百肯定我知道自己在做什么。一如既往,提前感谢您的帮助!!
Dim db As DAO.Database
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlWS As Excel.Worksheet
Private Sub CycleThroughWorkSheets()
Dim rs As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim sSQL1 As String
Dim sSQL2 As String
Dim sSQL3 As String
Dim rsFilePath As String
Dim rsWSName As String
Set db = CurrentDB
sSQL1 = "SELECT t_Directory.FileID, t_Directory.FilePath FROM t_Directory " & _
"WHERE (((t_Directory.FileExtension)=""'xlsx'""))"
Set rs = db.OpenRecordset("sSQL1", dbOpenDynaset)
With rs
rs.MoveFirst
Do While Not rs.EOF
rsFilePath = rs.Fields("[FilePath]")
OpenWorkBook (rsFilePath)
Set rs2 = db.OpenRecordset("t_SheetInfo", dbOpenDynaset)
With rs2
rs2.MoveFirst
Do While Not rs2.EOF
rs2.AddNew
rs2.Fields("FileID") = rs.Fields(1)
rs2.Fields("[SheetIndex]") = WorkSheetCount(rsFilePath)
rs2.Fields("[SheetName]") = WorkSheetName(WorkSheetCount)
rs2.Update
Next
Loop
End With
End With
Set rs = Nothing
Set rs2 = Nothing
End Sub
Public Function WorkSheetCount(rsFilePath As String) As Integer
Set xlWB = xlApp.Workbooks.Open(rsFilePath)
WorkSheetCount = xlWB.Sheets.Count(rsFilePath)
Debug.Print "WorkSheetCount : " & WorkSheetCount
End Function
Public Function WorkSheetName(WorkSheetCount As Integer) As String
Set xlWB = xlApp.Workbooks.Open(rsFilePath)
WorkSheetName = Worksheets(WorkSheetCount).Name
Debug.Print "WorkSheetName : " & WorkSheetName
End Function
答案 0 :(得分:6)
尝试这些方面的东西。一步一步。
Dim xlApp As New Excel.Application
Dim xlWB As Excel.Workbook
Dim sh As Object ''Some sheets may be charts
Dim rs As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim sSQL1 As String
Dim sSQL2 As String
Dim sSQL3 As String
Dim rsFilePath As String
Dim rsWSName As String
Set db = CurrentDb
xlApp.Visible = True
sSQL1 = "SELECT t_Directory.FileID, t_Directory.FilePath FROM t_Directory " & _
"WHERE t_Directory.FileExtension='.xlsx'"
Set rs2 = db.OpenRecordset("t_SheetInfo", dbOpenDynaset)
Set rs = db.OpenRecordset(sSQL1, dbOpenDynaset)
Do While Not rs.EOF
rsFilePath = rs.Fields("[FilePath]")
Set xlWB = xlApp.Workbooks.Open(rsFilePath)
For Each sh In xlWB.Sheets
rs2.AddNew
rs2.Fields("FileID") = rs.Fields("FileID")
rs2.Fields("[SheetIndex]") = sh.Index
rs2.Fields("[SheetName]") = sh.Name
rs2.Update
Next
rs.MoveNext
xlWB.Close False
Loop
Set rs = Nothing
Set rs2 = Nothing
xlApp.Quit