【问题标题】:Access add filename while importing multiple TXT to last column using VBA使用 VBA 将多个 TXT 导入最后一列时访问添加文件名
【发布时间】:2020-07-13 13:47:38
【问题描述】:

我目前有一个使用访问规范导入文件夹中所有文件的宏。我想在 Access 表的末尾添加一列,其中包含每个导入的 .txt 文件的文件名。到目前为止,这是我的代码。如何完成?

Sub cmdImport_Click()
    Dim strPath As String
    Dim strFile As String
    Dim strTable As String
    Dim strSpecification As String
    Dim intImportType As AcTextTransferType
    Dim blnHasFieldNames As Boolean

    strTable = "Reconstrucción"
    strSpecification = "Reconstruir"
    blnHasFieldNames = False
    intImportType = acImportDelim

    ' Permite al usuario elegir una carpeta
    With Application.FileDialog(4)
        If .Show Then
            strPath = .SelectedItems(1)
        Else
            MsgBox "No seleccionó una carpeta", vbExclamation
            Exit Sub
        End If
    End With
    If Right(strPath, 1) <> "\" Then
        strPath = strPath & "\"
    End If

    DoCmd.OpenForm "frmMessage"
    Forms!frmMessage.Repaint

    ' Loop a través de los archivos de texto
    strFile = Dir(strPath & "*.txt")
    Do While strFile <> ""
        ' Importa los archivos de texto de la carpeta
        DoCmd.TransferText _
            TransferType:=acImportFixed, _
            SpecificationName:=strSpecification, _
            TableName:=strTable, _
            FileName:=strPath & strFile, _
            HasFieldNames:=blnHasFieldNames
        strFile = Dir
    Loop

    DoCmd.Close acForm, "frmMessage"
End Sub

【问题讨论】:

    标签: vba ms-access


    【解决方案1】:

    只需在“Reconstrucción”表中创建一个名为 FileName 的字段,并将下面的代码添加为循环的最后一行:

    docmd.runsql "UPDATE " & strTable & " SET FileName = '" & strFile & "' WHERE strFile ISNULL;"
    

    【讨论】:

    • 操作查询应使用CurrentDb().Execute 运行。然后,您不必打开/关闭警告。
    • 您确定要在每个循环中添加 same 列吗?
    • Kostas K. 对于我从问题中理解的内容,是的,必须添加相同的列名,因为每个文件都有不同的表名。我错过了什么吗?
    • 只有一张桌子,strTable
    猜你喜欢
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多