Access 2010:导入使用FileDialog选择的Excel文件

时间:2017-01-11 10:25:15

标签: excel forms vba import access

我是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方法,但它没有用,我甚至不知道放在哪里。我很抱歉,因为我提到了VBA非常新的

1 个答案:

答案 0 :(得分:0)

你走了!!

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