如何使用VBA将文件名插入访问表

时间:2018-04-23 21:44:34

标签: vba ms-access access-vba

我想要一些帮助...... 我有一个来自访问的子,我在某个文件夹中读取了.gif扩展名的所有文件,并想知道如何继续插入访问表中读取的所有名称,我在下面编写了代码,但它不是工作......你能帮助我吗?

Sub realAllFiles ()

Dim varFile As Variant
Dim CustomerFolder As String
Dim fDialog As FileDialog, result As Integer
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)

With fDialog

.AllowMultiSelect = True
.Title = "Upload | Selecione a pasta de imagens capturadas..."
.Filters.Clear
.Filters.Add "All files", "*.gif*"
.InitialFileName = "H:\Gestao de Dados Processamento\FAP\Baixa de Pendencia DUT\Novo Fluxo"

If .Show = True Then
      For Each varFile In .SelectedItems
         CustomerFile = varFile
      Next
      Else: Exit Sub
   End If
End With

DoCmd.TransferText acImportDelim, , "MyTable", CustomerFile, False

End Sub

1 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点。

第一种方法是设置一个导入查询,将文件名作为参数传递。

查询的SQL:

PARAMETERS [prmFileName] Text (255);
INSERT INTO T ( FieldName )  '<- Change to the actual table and field names
SELECT [prmFileName] As _FileName;

然后在循环内调用查询:

Sub realAllFiles()

    Dim varFile As Variant
    Dim CustomerFolder As String
    Dim fDialog As FileDialog, result As Integer
    Set fDialog = Application.FileDialog(msoFileDialogFilePicker)

    With fDialog
        .AllowMultiSelect = True
        .Title = "Upload | Selecione a pasta de imagens capturadas..."
        .Filters.Clear
        .Filters.Add "All files", "*.gif*"
        .InitialFileName = "H:\Gestao de Dados Processamento\FAP\Baixa de Pendencia DUT\Novo Fluxo"
    End With

    If fDialog.Show = True Then
        For Each varFile In fDialog.SelectedItems
            With CurrentDb().QueryDefs("ImportQueryName") '<- change to the above query's name
                .Parameters("[prmFileName]").Value = varFile
                .Execute dbFailOnError
            End With
        Next
    End If
End Sub

第二种方法是通过记录集:

Sub realAllFiles()

    Dim varFile As Variant
    Dim CustomerFolder As String
    Dim fDialog As FileDialog, result As Integer
    Dim rs As DAO.Recordset

    Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
    Set rs = CurrentDb().OpenRecordset("TableName") '<- change to the actual table name

    With fDialog
        .AllowMultiSelect = True
        .Title = "Upload | Selecione a pasta de imagens capturadas..."
        .Filters.Clear
        .Filters.Add "All files", "*.gif*"
        .InitialFileName = "H:\Gestao de Dados Processamento\FAP\Baixa de Pendencia DUT\Novo Fluxo"
    End With

    If fDialog.Show = True Then
       For Each varFile In fDialog.SelectedItems
          rs.AddNew
          rs("Fieldname").Value = varFile '<- change to the actual field name
          rs.Update
       Next
    End If

    If Not rs Is Nothing Then rs.Close
End Sub