2

I'm trying to increment file names if a previously numbered one exists.

For example, it should check if "Example.csv" exists. If so, the new file should be called "Example2.csv", then "Example3.csv", "Example4.csv" and so on. Here's my code so far:

$fileNum = 2
; The $month variable is defined earler in the script but I'll define another var for this example
$month = "January"
If FileExists("Emissions Log - " & $month & ".csv") Then
    If FileExists("Emissions Log - " & $month & $fileNum & ".csv") Then
        $fileNum += 1
        $file = FileOpen("Emissions Log - " & $month & $fileNum & ".csv", 1)
    Else
        $file = FileOpen("Emissions Log - " & $month & $fileNum & ".csv", 1)
    EndIf
Else
    $file = FileOpen("Emissions Log - " & $month & ".csv", 1)
EndIf
user4157124
  • 2,809
  • 13
  • 27
  • 42
Timothy Bomer
  • 504
  • 5
  • 21

2 Answers2

2

In order to do that, you must loop the filenames.

$month = "January"

For $i = 0 To 1000 ;max file versions is set to 1000

    If $i = 0 Then
        $num = ''
    Else
        $num = $i
    EndIf

    If Not FileExists("Emissions Log - " & $month & $num & ".csv") then
        $file = FileOpen("Emissions Log - " & $month & $num & ".csv", 1)
        ExitLoop
    EndIf
Next
Milos
  • 2,927
  • 1
  • 15
  • 27
1

I'm trying to increment file names if a previously numbered one exists.

While FileExists() StringReplace(). Example:

Func _FilenameUnique(Const $sFilenameRequested, Const $sDelimiter = '-', Const $iCountStart = 2)
    Local $iError          = 0, _
          $iCount          = $iCountStart - 1
    Local $sFilenameUnique = $sFilenameRequested

    While FileExists($sFilenameUnique) And Not $iError

        $iCount         += 1
        $sFilenameUnique = StringReplace($sFilenameRequested, '.', $sDelimiter & $iCount & '.', -1)
        $iError          = @error

    WEnd

    Return SetError($iError, $iCount, $sFilenameUnique)
EndFunc

$sFilename = _FilenameUnique('C:\path\file.csv', '') functions as requested. Include current time alternatively:

$sFilename = 'C:\path\file_' & @YEAR & @MON & @YDAY & @HOUR & @MIN & @SEC & '.csv'
user4157124
  • 2,809
  • 13
  • 27
  • 42