从 MS Access 随机化导出的文件名

randomize exported file name from ms access

提问人:Zyarat 提问时间:11/14/2023 最后编辑:June7Zyarat 更新时间:11/14/2023 访问量:55

问:

我有一个随机化文件名的功能。我将其称为 GetNextFileName。

Option Compare Database

Function GetNextFileName(ByVal strFile As String) As String
  Dim strResult As String
  Dim intCount As Integer
  
  strResult = Replace(strFile, "1", "*") 'add wildcard
  strResult = Dir(strResult)
  
  While strResult <> ""
    intCount = intCount + 1
    strResult = Dir()
  Wend
  
  GetNextFileName = Replace(strFile, "1", intCount + 1)
  
End Function

我正在将附件从我的 Access 表导出到需要随机化文件名的文件夹,以避免在保存文件时出现 Access 的重复错误。

Option Compare Database
Option Explicit

Public Sub ExtractAllAttachments(ByVal TableName As String, ByVal AttachmentColumnNane As String)
Dim rsMainRecords As DAO.Recordset2
Dim rsAttachments As DAO.Recordset2

Set rsMainRecords = CurrentDb.OpenRecordset("SELECT " & AttachmentColumnNane & _
                                            " FROM " & TableName & _
                                            " WHERE " & AttachmentColumnNane & ".FileName IS NOT NULL")
                                            
Do Until rsMainRecords.EOF   
  Set rsAttachments = rsMainRecords.Fields(AttachmentColumnNane).value       
  Do Until rsAttachments.EOF      
    Dim outputFileName As String        
    outputFileName = GetNextFileName.GetNextFileName(rsAttachments.Fields("FileName").value)
    outputFileName = "F:\SHARING\Tracking System\file" & "\" & outputFileName        
    rsAttachments.Fields("FileData").SaveToFile outputFileName      
    rsAttachments.MoveNext
  Loop
  rsAttachments.Close        
  rsMainRecords.MoveNext
Loop
    
rsMainRecords.Close
    
Set rsAttachments = Nothing
Set rsMainRecords = Nothing
    
End Sub

我试过了,但文件的名称不是随机的,也没有添加前缀! 有什么建议吗?

VBA 文件名 MS-ACCESS-2016

评论

2赞 user10186832 11/14/2023
无需对文件名进行更改,只需使用时间戳,如下所示 - 将文件名调暗为字符串:sFilename = “U:\Data\rpt” & Format(Now(), “yyyymmddHHMMSS”) & “.txt”
2赞 hennep 11/14/2023
或者使用 FileSystemObject.GetTempName 让窗口创建文件名。(以防您每秒生成超过 1 个文件)
0赞 Andre 11/15/2023
调试 VBA 代码 -- 单步执行函数以查看发生的情况。

答: 暂无答案