(Q) I need to export about 50 files from my database every night. The files have a
fixed name, for example, tmp00010.Dat, tmp00011.Dat etc. I know how to generate each
export file with loops in code. But I don't know how to generate such a sequential and
unique file name given an export directory.
(A) Paste the following function in a new module and use the Function fUniqueFile to
generate a unique sequential filename. The function checks for existance of each file
before returning the unique name back.
Function fUniqueFile(strDir As String, intMaxFiles As Integer, _
strPadChar As String, strFileInitName As _
String, Optional strFileExt) As String
Dim strtmpFile As String
Dim strTmp As Variant
Dim i As Integer
Dim boolNextI As Boolean
On Error GoTo funiqueFile_Error
For i = 1 To intMaxFiles
boolNextI = False
If Not IsMissing(strFileExt) Then
strTmp = Dir(strDir & "\*." & strFileExt)
strtmpFile = strFileInitName & Lpad(CStr(i), strPadChar, 5) _
& "." & strFileExt
Else
strTmp = Dir(strDir & "\*.*")
strtmpFile = strFileInitName & Lpad(CStr(i), strPadChar, 5)
End If
Do While strTmp <> ""
If strTmp = strtmpFile Then
boolNextI = False
Exit Do
Else
boolNextI = True
End If
strTmp = Dir
Loop
If boolNextI Then
Exit For
End If
Next i
fUniqueFile = strtmpFile
fUniqueFile_Success:
Exit Function
funiqueFile_Error:
fUniqueFile = vbNullString
Resume fUniqueFile_Success
End Function
Function Lpad(MyValue$, MyPadCharacter$, MyPaddedLength%)
Dim PadLength As Integer
Dim X As Integer
PadLength = MyPaddedLength - Len(MyValue)
Dim PadString As String
For X = 1 To PadLength
PadString = PadString & MyPadCharacter
Next
Lpad = PadString + MyValue
End Function
|