2014-10-10 43 views
2

我從MS Access表中導出文件到我的本地,我正在做這個VBA編碼。 我需要爲這樣的方式的文件名創建序列,如何創建序列

File1PN00001 
File1PN00002 
File1PN00003 
... 

... 

我對下面的代碼

Private Sub Command0_Click() 
Dim FileName As String 
Dim intChoice As Integer 
Dim strPath As String 
Dim LSProc As QueryDef 
Dim db As Database 
Set db = CurrentDb() 

Set LSProc = db.CreateQueryDef("") 

'make the file dialog visible to the user 
strFilePath = BrowseFolder("Please Select Path to Export Neutrality Report file to") 

If strFilePath <> "" Then 
Call MsgBox(strFilePath, vbInformation, "Save Path") 
Else 
MsgBox "Please Provide a file path before exporting!", vbCritical + vbOKOnly 
End If 
FileName = strFilePath & "File1PN" & Format(txtBal_Number, "000000") & ".txt" 

    DoCmd.TransferText acExportDelim, , "T1", FileName, False 
End Sub 

這樣做我很困惑如何創建該序列,如何創建序列以及如何在每次運行此代碼時將值增加1。您能否幫我解決這個問題 謝謝。

+0

是否希望將DB中的所有表導出到txt文件? – PaulFrancis 2014-10-10 11:41:09

+0

那麼,你需要找到那個目錄中最後保存的文件的編號。抓取數字部分並在保存時增加1? – 2014-10-10 11:49:32

+0

@PaulFrancis:不,並非所有的表格只有那些需要的表格。這裏T1是輸出的表格 – 2014-10-10 12:01:10

回答

3

如果你有一個日誌系統,你可以得到這個排序。首先,你需要創建一個沒有什麼特別的表格,只是一個簡單的兩列表格。

tbl_FileNameLog 
-------------------------------------------------------------------------- 
FIELD NAME | DATA TYPE |     COMMENTS 
------------+---------------+--------------------------------------------- 
fileID  | Number  | Could use Auto Number, but for future safe. 
      |    |  use Number, so you can edit it. 
      |    |  But make sure it is a Primary Key. 
exportDate | Date/Time | Just a Date field to store the Date. 

現在你可以編輯你的代碼。

Private Sub Command0_Click() 
    Dim strPath As String, FileName As String 
    Dim lngChoice As Long 
    Dim dbObj As Database 

    Set dbObj = CurrentDb() 

    'make the file dialog visible to the user 
    strFilePath = BrowseFolder("Please Select Path to Export Neutrality Report file to") 

    If strFilePath <> "" Then 
     MsgBox "Exporting File to : " & strFilePath, vbInformation, "Save Path" 
    Else 
     MsgBox "Please Provide a file path before exporting!", vbCritical + vbOKOnly 
     Exit Sub 
    End If 

    lngChoice = Nz(DMax("fileID", "tbl_FileNameLog"), 0) + 1 

    FileName = strFilePath & "File1PN" & Format(lngChoice, "000000") & ".txt" 

    DoCmd.TransferText acExportDelim, , "T1", FileName, False 

    dbObj.Execute "INSERT INTO tbl_FileNameLog (fileID, exportDate) VALUES (" & _ 
        lngChoice & ", " & CDbl(Date()) & ")" 

    Set dbObj = Nothing 
End Sub 

所以,第一次運行代碼時,它會查找表中的最大ID。由於沒有條目,它將使用Nz函數並分配一個0 + 1,因此獲得1的ID。然後導出到指定的位置。同時在文件日誌中輸入說明ID已被分配。所以下一次代碼運行時,它會查找文件日誌表,因爲ID爲1可以不使用2.所以等等......

這樣它不依賴於文件系統。它有自己的日誌,所以即使文件被移動或刪除,它仍然能夠提供一致的/連續的編號。希望這可以幫助 !

+0

其工作感謝哥們:)乾杯! – 2014-10-10 14:36:34

+0

很高興你有它排序!祝你好運。 :) – PaulFrancis 2014-10-13 08:30:19