访问2010:导入Excel文件,该文件使用文件对话框选择



我是Access 和 VBA 的新手。我创建了一个表单,可以在其中通过 fileDialog 选择一个文件。

这里是 fileDialog 的代码:

Public Function DateiAuswaehlen()
Dim objFiledialog As FileDialog
Set objFiledialog = _
    Application.FileDialog(msoFileDialogOpen)
With objFiledialog
    .AllowMultiSelect = False
    If .Show = True Then
        DateiAuswaehlen = .SelectedItems(1)


    End If
End With
Set objFiledialog = Nothing
End Function

如何将选定的 Excel 文件导入访问表?我找到了DoCmd.TransferSpreadsheet方法,但它没有奏效,tbh我什至不知道把它放在哪里。我很抱歉,因为我提到我对 VBA 很陌生

你去吧!!

Sub btn_GetFileName_Click()
'************************************************************************
'Lets get the file name
    Debug.Print "Getting File Name"
    'Declare a variable as a FileDialog object.
    Dim fd As FileDialog
    'Set the starting look location
    Dim strComPath As String
    strComPath = "C:"
    Dim strFilePath As String
    'Create a FileDialog object as a File Picker dialog box.
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    'Declare a variable to contain the path
    'of each selected item. Even though the path is a String,
    'the variable must be a Variant because For Each...Next
    'routines only work with Variants and Objects.
    Dim vrtSelectedItem As Variant
    'Use a With...End With block to reference the FileDialog object.
    With fd
        .InitialFileName = strComPath
        .AllowMultiSelect = False
        .Filters.Clear
        'Add filter to only show excel files.
        .Filters.Add "Excel files", "*.xlsm", 1
        'Use the Show method to display the File Picker dialog box and return the user's action.
        'The user pressed the action button.
        If .Show = -1 Then
                strFilePath = .SelectedItems(1)
            'Step through each string in the FileDialogSelectedItems collection.
            'For Each vrtSelectedItem In .SelectedItems
                'vrtSelectedItem is a String that contains the path of each selected item.
                'You can use any file I/O functions that you want to work with this path.
                'This example simply displays the path in a message box.
             '   strFilePath: " & vrtSelectedItem
            'Next vrtSelectedItem
        Else
            'The user pressed Cancel.
            DoCmd.Hourglass (False)
            MsgBox "You must select a file to import before proceeding", vbOKOnly + vbExclamation, "No file Selected, exiting"
            Set fd = Nothing
            Exit Sub
        End If
    End With

    tblFileName = strFilePath
    DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, "tblTest", tblFileName, True
    Set fd = Nothing
End Sub

最新更新