如何创建序列

时间:2014-10-10 11:31:16

标签: vba ms-access access-vba ms-access-2003

我将文件从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。你能帮我解决这个问题吗? 感谢。

1 个答案:

答案 0 :(得分: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

因此,第一次运行代码时,它将在表中查找Max ID。由于没有条目,它将使用Nz函数并分配0 + 1,因此获得ID为1。然后导出发生在指定的位置。同时输入文件日志,说明已分配ID。因此,下次代码运行时,它将查找文件日志表,因为ID为1是可用的,它不会使用2.所以等等....

这样它就不依赖于文件系统。它有自己的日志,因此即使文件被移动或删除,它仍然能够提供一致/连续的编号。希望这有帮助!