0

我正在 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:\Share\Manufacturing\Propeller\Finalized" & "\*.*", 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:\Share\Manufacturing\Propeller\Finalized\[" & strListOfFiles(Index) & "]Order Input'!B15"
        MyRS.Update
    Next
End Sub

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

4

1 回答 1

0

当然可以,因为您还没有打开工作簿。您需要包含对 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 对象库。

于 2012-10-06T00:06:43.107 回答