在对话框中选择文件,在文本框中放置路径,以及用于导入为表格的另一个按钮

问题描述 投票:1回答:1

VBA通过单击按钮打开对话框,分别选择文件,将路径放置在多个文本框中,单击另一按钮导入文件

我一直在网上搜索,但是所有代码都可以在一个程序中选择和导入

'Module
Public Sub ImportDocument()
    On Error GoTo ErrProc

    Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    With fd
        .InitialFileName = "Some folder"
        .Title = "Some Title"
        With .Filters
            .Clear
            .Add "TXT documents", "*.txt", 1
        End With
        .ButtonName = " Import Selected "
        .AllowMultiSelect = False

        If .Show = 0 Then GoTo Leave
    End With

    Dim selectedItem As Variant
    For Each selectedItem In fd.SelectedItems
        DoCmd.TransferText acImportDelim, "team_Specs", "team", selectedItem, True, ""
        'DoCmd.TransferText acImportDelim, "Raw Data from Import_ Import Specification", "Raw Data from Import", selectedItem, True, ""
    Next

Leave:
    Set fd = Nothing
    On Error GoTo 0
Exit Sub

ErrProc:
    MsgBox err.Description, vbCritical
    Resume Leave
End Sub

'Form
Private Sub Command2_Click()
Dim status_ As TaskImportEnum
    status_ = ImportDocument

Select Case status_
    Case TaskImportEnum.Success:
        MsgBox "Success!"

    Case TaskImportEnum.Failure:
        MsgBox "Failure..."

    Case Else:
        MsgBox "Aborted..."
End Select
End Sub
access-vba
1个回答
0
投票

您需要将导入子细分为多个任务。

选择文件功能仅返回所选文档的文件路径,然后将该路径插入相关的文本框。

然后,导入按钮将验证TextBox是否具有值,是的,它将导入它。

1。选择文件。


Private Sub ButtonSelect_Click()

    Dim file_ As String
        file_ = SelectDocument()

    'Selection was made?
    If file_ <> vbNullString Then TextBoxFilePath.Value = file_

End Sub

选择文件的功能。


Public Function SelectDocument() As String
    On Error GoTo Trap

    Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    With fd
        .InitialFileName = "Some folder"
        .Title = "Some Title"
        With .Filters
            .Clear
            .Add "TXT documents", "*.txt", 1
        End With
        .ButtonName = " Import Selected "
        .AllowMultiSelect = False
    End With

    'if a selection was made, return the file path
    If fd.Show = -1 Then SelectDocument = fd.SelectedItems(0)

Leave:
    Set fd = Nothing
    On Error GoTo 0
Exit Function

Trap:
    MsgBox Err.Description, vbCritical
    Resume Leave
End Function

2。如果已选择,则导入。


Private Sub ButtonImport_Click()
    With TextBoxFilePath
        If Not IsNull(.Value) Then
            DoCmd.TransferText acImportDelim, "team_Specs", "team", .Value, True, ""
        End If
    End With
End Sub

您需要更改按钮和文本框的名称。

© www.soinside.com 2019 - 2024. All rights reserved.