从 Excel 填充访问记录



我正在 Access 2010 中创建一个表单,该表单将为特定文件夹中的每个 Excel 文件创建一条记录,并使用来自各个单元格的信息填充字段。 该宏使用 Excel 工作簿的所有文件名(各种字母数字序列)填充数组,然后遍历这些文件并为每个 Excel 工作表创建新记录。

Private Sub PopulateArray_Click()
    Dim strListOfFiles() As String
    Dim intCount As Integer
    intCount = 0
    Dim sFile As String
    sFile = Dir$("P:ShareManufacturingPropellerFinalized" & "*.*", vbDirectory Or vbHidden Or vbSystem Or vbReadOnly Or vbArchive)
    Do Until sFile = vbNullString
        If sFile <> "." Then ' relative path meaning this directory
            If sFile <> ".." Then ' relative path meaning parent directory
                ReDim Preserve strListOfFiles(0 To (intCount + 1)) As String
                strListOfFiles(intCount) = sFile
                intCount = intCount + 1
            End If
        End If
        sFile = Dir$()
    Loop
    Dim MyDB As DAO.Database
    Dim MyRS As DAO.Recordset
    Set MyDB = CurrentDb()
    Set MyRS = MyDB.OpenRecordset("Record", dbOpenDynaset)
    For Index = 0 To UBound(strListOfFiles)
        MyRS.AddNew
        MyRS![SerialNumber] = "'P:ShareManufacturingPropellerFinalized[" & strListOfFiles(Index) & "]Order Input'!B15"
        MyRS.Update
    Next
End Sub

我已经完成了大部分工作,但最后一步让我卡住了。 问题出在"MyRS![序列号]"位。 目前,它所做的只是打印单元格的(正确的)文件路径,而不是单元格本身的值。

当然可以,因为您尚未打开工作簿。您需要包含对 MS Excel 对象库的引用(最新版本是我的计算机上使用 MSO 2007 的 11.0)。

然后,您可以使用Excel"命名空间"来访问 Excel 对象,如下所示:

Dim xlApp as Excel.Application
Dim xlWb as Excel.Workbook
Dim cell as Excel.Range
With xlApp
    .Visible = true
    Set xlWb = .Workbooks.Open(...)
End With
// And so on...

编辑:要包含引用,您需要键入 Alt+F11 进入 VBA 编辑器,然后在Tools转到References并检查该 Excel 对象库。

最新更新