2

我需要 VBA 代码将选定的电子表格从多个 excel 文件导入到 access 2007 表中。任何人都可以帮忙吗?

这是我到目前为止的代码。

Option Compare Database
Option Explicit

Const strPath As String = "C:\Users\person\Documents\files.xlsx"

Dim strFile As String
Dim strFileList() As String
Dim intFile As Integer

Sub Sample() 
    strFile = Dir(strPath & "*.xls")

strFile = Dir(strPath & "*.xls")
While strFile <> ""
    'adding files to the list
    intFile = intFile + 1
    ReDim Preserve strFileList(1 To intFile)
    strFileList(intFile) = strFile
    strFile = Dir()
If intFile = 0 Then
    MsgBox "No Files Found"
    Exit Sub
End If
'going through the files and linking them to access
For intFile = 1 To UBound(strFileList)
    DoCmd.TransferSpreadsheet acLink, , _
    strFileList(intFile), strPath & strFileList(intFile), True, "A5:J17"
Next
MsgBox UBound(strFileList) & "Files were linked"
End Sub
4

1 回答 1

3

我不明白该代码的所有内容,但我的直觉是它没有按照您的预期进行。

你声明一个常数,strPath.

Const strPath As String = "C:\Users\person\Documents\files.xlsx"

稍后,您将“*.xls”连接到该常量并将其提供给Dir()函数。

Sub Sample() 
    strFile = Dir(strPath & "*.xls")

我认为你应该Debug.Print在那个时候尝试......

Debug.Print strPath & "*.xls"

...因为您提供的字符串Dir()使其等同于以下语句:

strFile = Dir("C:\Users\person\Documents\files.xlsx*.xls")

我怀疑它是否与您要处理的任何 Excel 文件相匹配。

看看下面的代码大纲是否有用。我认为不需要先填充数组,然后循环遍历数组以链接电子表格。我不明白为什么你应该在这里需要一个数组。如果可以,请避免使用它,因为代码会更简单并且会ReDim Preserve影响性​​能。

Sub Sample2()
    Const cstrFolder As String = "C:\Users\person\Documents\"
    Dim strFile As String
    Dim i As Long

    strFile = Dir(cstrFolder & "*.xls")
    If Len(strFile) = 0 Then
        MsgBox "No Files Found"
    Else
        Do While Len(strFile) > 0
            Debug.Print cstrFolder & strFile
            ' insert your code to link to link to it here '
            i = i + 1
            strFile = Dir()
        Loop
        MsgBox i & " Files were linked"
    End If
End Sub
于 2012-12-17T23:21:09.680 回答