2017-01-23 130 views
0

我已经构建了一个表单,用户可以选择一个或多个文件并将它们导入到一个表中。当用户选择文件或多个文件时,一旦导入完成,我想要在每一行上添加文件名,当然,这与正确的文件相关。使用文本文件将文件名添加到列导入

我能够设置查询手动添加文件名,但我怎么能够以更自动化的方式做到这一点。例如,如果用户选择一个文件,我如何编码SQL查询来自动检测文件名并添加它?如果用户选择多个文件,那么查询如何为每行写入正确的文件名?

这里是我的表单代码:

Option Compare Database 

'Private Sub Command0_Click() 
Private Sub cmdFileDialog_Click() 

'Requires reference to Microsoft Office 12.0 Object Library. 

    Dim fDialog As Office.FileDialog 
    Dim varFile As Variant 

    'Clear listbox contents. 
    'Me.FileList.RowSource = "" 

    'Set up the File Dialog. 
    Set fDialog = Application.FileDialog(msoFileDialogFilePicker) 
    With fDialog 
     'Allow user to make multiple selections in dialog box. 
     .AllowMultiSelect = True 

     'Set the title of the dialog box. 
     .Title = "Please select one or more files" 
    .InitialFileName = "C:\Users\ABCCCCC\Desktop\January CMS reports for CCCCC" 

     'Clear out the current filters, and add our own. 

     .Filters.Clear 
     '.Filters.Add "Access Databases", "*.MDB; *.ACCDB" 
     .Filters.Add "Access Projects", "*.txt" 
     '.Filters.Add "All Files", "*.*" 

     'Show the dialog box. If the .Show method returns True, the 
     'user picked at least one file. If the .Show method returns 
     'False, the user clicked Cancel. 
     If .Show = True Then 
     'Loop through each file selected and add it to the list box. 
     For Each varFile In .SelectedItems 
      ' Me.FileList.AddItem varFile 
     Call InsertCMS_Reports_2ndSave(varFile) 
     Next 
     Else 
     MsgBox "You clicked Cancel in the file dialog box." 
     End If 
    End With 
End Sub 

模块代码:

Function InsertCMS_Reports_2ndSave(FileName As Variant) 
    'DoCmd.DeleteObject CopyOfCOMPRPT_CE, "CMS_Reports_2ndSave" 
    DoCmd.TransferText acImportFixed, "CMS_Reports_Import", _ 
    "CMS_Reports_Import", "C:\Users\ABCCCCC\Desktop\January CMS reports for CCCCC\FileName" 
    CurrentDb.Execute "UPDATE CopyOfCOMPRPT_CE SET FileName = 'HLTH_COMPRPT_1701011028174_h0062.txt' WHERE FileName is NULL", dbFailOnError 
End Function 

回答

0

只要你提供的是已经工作的代码,那么这应该为你工作。

​​

如果你有问题,这是最有可能是语法问题与SQL字符串和引号将是最有可能是罪魁祸首。如果遇到问题,请在代码中添加一条调试语句,以便查看生成的SQL语句。例如:

Function InsertCMS_Reports_2ndSave(FileName As Variant) 

    Dim strSQL as String 

    'DoCmd.DeleteObject CopyOfCOMPRPT_CE, "CMS_Reports_2ndSave" 
    DoCmd.TransferText acImportFixed, "CMS_Reports_Import", _ 
    "CMS_Reports_Import", "C:\Users\ABCCCCC\Desktop\January CMS reports for CCCCC\FileName" 

    strSQL = "UPDATE CopyOfCOMPRPT_CE SET FileName = '" & FileName & "' WHERE FileName is NULL", dbFailOnError" 
    debug.print strSQL 

    CurrentDb.Execute strSQL, dbFailOnError 
End Function 
相关问题