2

選択したスプレッドシートを複数の Excel ファイルから Access 2007 テーブルにインポートするには、VBA コードが必要です。誰でも助けることができますか?

これは私がこれまでに持っているコードです。

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 に答える