1

这就是我正在尝试做的事情,如果我走错了方向,我深表歉意。我正在尝试遍历存储在表 t_Directory 中的文件路径,如果文件扩展名是“xlsx”,则打开 Excel 文件并使用 Excel 工作表的 FileID 和工作表计数以及工作表名称更新另一个名为 t_SheetInfo 的表。如果有更有效的方法,有人会花一分钟时间检查我到目前为止所做的事情或引导我朝着正确的方向前进吗?我不是 100% 确定我知道自己在做什么。与往常一样,提前感谢您的帮助!!

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
4

1 回答 1

6

Try something on these lines. Step through.

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
于 2012-05-17T15:39:28.183 回答