Create unique filename by adding incremental number - filenames

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

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

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'

Related

WScript and com ref issue

wscript no longer uses run? and other gets a com reference issue,
the code is for editing current session for downloading the csv file.
every to this point works as it should.
If Dir(cf) = "" Then CreateObject("WScript.Shell").RUN "cmd.exe /s /c echo TEXT&echo.Enter your pin&echo.&echo. & " & f & " --aea --cookie-jar " & cf, vbNormalFocus, True
C = CreateObject("New:0D43FE01-F093-11CF-8940-00A0C9054228").OpenTextFile(cf).ReadAll
If InStr(C, vbTab) = 0 Or InStr(C, vbCrLf) = 0 Then JasperDruif = True: GoTo doitagain
Set t = CreateObject("New:47DFBE54-CF76-11D3-B38F-00105A1F473A")
t.SetVarDate Now
If Right(Split(C, vbTab & "session")(0), 10) / 1 < ((t.getVarDate(False) - 25569) * 86400) Then CreateObject("WScript.Shell").RUN "cmd.exe /s /c echo TEXT.&echo.Enter your pin&echo.&echo. & " & f & " --aea --cookie-jar " & cf, vbNormalFocus, True: C = CreateObject("New:0D43FE01-F093-11CF-8940-00A0C9054228").OpenTextFile(cf).ReadAll
Cookie = "session=" & Split(Split(C, "session" & vbTab)(1), vbCrLf)(0)
any idea how to make this work in vb.net, worked fine in vb6 and even on excel vba.

Trim both newlines and spaces in VBA 7.0

Trim (in VBA for MS-Access 2010) does not remove vbCrLfs, only spaces. In the immediate window, I get
? Len(vbCrLf & "a" & vbCrLf & "b" & vbCrLf)
8
? Len(Trim(vbCrLf & "a" & vbCrLf & "b" & vbCrLf))
8
For spaces however:
? Len(" " & "a" & " " & "b" & " ")
5
? Len(Trim(" " & "a" & " " & "b" & " "))
3
How to make a trim that removes vbCrLFs on the ends only?
If you don't mind removing ALL new lines (and not just edges) you could just do:
myStr = Application.clean(Application.trim(myStr))
For imitating Trim function, you'd need to test each character in your string's edges:
Function TrimNewLines(mtStr As String) As String
Dim pattern As String, c As String
Dim i As Integer: i = 1
pattern = "[" & Chr(10) & Chr(13) & "]"
c = Mid(mtStr, i, 1)
Do While c Like pattern
i = i + 1
c = Mid(mtStr, i, 1)
Loop
mtStr = Mid(mtStr, i, Len(mtStr))
i = Len(mtStr)
c = Mid(mtStr, i, 1)
Do While c Like pattern
i = i - 1
c = Mid(mtStr, i, 1)
Loop
mtStr = Mid(mtStr, 1, i)
TrimNewLines = mtStr
End Function
This seems to have done the trick:
Public Function trimNewlinesAndSpaces(chaine As String) As String
chaine = Trim(chaine)
Do While (left(chaine, 2) = vbCrLf) Or right(chaine, 2) = vbCrLf
If left(chaine, 2) = vbCrLf Then
chaine = right(chaine, Len(chaine) - 2)
End Ifj
If right(chaine, 2) = vbCrLf Then
chaine = left(chaine, Len(chaine) - 2)
End If
chaine = Trim(chaine)
Loop
trimNewlinesAndSpaces = chaine
End Function

vbs script upload only the file name without inside data

The problem of this script is that it shows an unknown error Message while running the script.
I called the function by echo method in my ftp which is "filezilla".
every thing is working fine as it logs into the server check for the path, open channel for data writing. Still dont know where is the problem
Function FTPUpload(sSite, sUsername, sPassword, sLocalFile, sRemotePath)
'This script is provided under the Creative Commons license located
'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not
'be used for commercial purposes with out the expressed written consent
'of NateRice.com
Const OpenAsDefault = -2
Const FailIfNotExist = 0
Const ForReading = 1
Const ForWriting = 2
Set oFTPScriptFSO = CreateObject("Scripting.FileSystemObject")
Set oFTPScriptShell = CreateObject("WScript.Shell")
sRemotePath = Trim(sRemotePath)
sLocalFile = Trim(sLocalFile)
'----------Path Checks---------
'Here we willcheck the path, if it contains
'spaces then we need to add quotes to ensure
'it parses correctly.
If InStr(sRemotePath, " ") > 0 Then
If Left(sRemotePath, 1) <> """" And Right(sRemotePath, 1) <> """" Then
sRemotePath = """" & sRemotePath & """"
End If
End If
If InStr(sLocalFile, " ") > 0 Then
If Left(sLocalFile, 1) <> """" And Right(sLocalFile, 1) <> """" Then
sLocalFile = """" & sLocalFile & """"
End If
End If
'Check to ensure that a remote path was
'passed. If it's blank then pass a "\"
If Len(sRemotePath) = 0 Then
'Please note that no premptive checking of the
'remote path is done. If it does not exist for some
'reason. Unexpected results may occur.
sRemotePath = "\"
End If
'Check the local path and file to ensure
'that either the a file that exists was
'passed or a wildcard was passed.
If InStr(sLocalFile, "*") Then
If InStr(sLocalFile, " ") Then
FTPUpload = "Error: Wildcard uploads do not work if the path contains a " & _
"space." & vbCRLF
FTPUpload = FTPUpload & "This is a limitation of the Microsoft FTP client."
Exit Function
End If
ElseIf Len(sLocalFile) = 0 Or Not oFTPScriptFSO.FileExists(sLocalFile) Then
'nothing to upload
FTPUpload = "Error: File Not Found."
Exit Function
End If
'--------END Path Checks---------
'build input file for ftp command
sFTPScript = sFTPScript & "USER " & sUsername & vbCRLF
sFTPScript = sFTPScript & sPassword & vbCRLF
sFTPScript = sFTPScript & "cd " & sRemotePath & vbCRLF
sFTPScript = sFTPScript & "binary" & vbCRLF
sFTPScript = sFTPScript & "prompt n" & vbCRLF
sFTPScript = sFTPScript & "put " & sLocalFile & vbCRLF
sFTPScript = sFTPScript & "quit" & vbCRLF & "quit" & vbCRLF & "quit" & vbCRLF
sFTPTemp = oFTPScriptShell.ExpandEnvironmentStrings("%TEMP%")
sFTPTempFile = sFTPTemp & "\" & oFTPScriptFSO.GetTempName
sFTPResults = sFTPTemp & "\" & oFTPScriptFSO.GetTempName
'Write the input file for the ftp command
'to a temporary file.
Set fFTPScript = oFTPScriptFSO.CreateTextFile(sFTPTempFile, True)
fFTPScript.WriteLine(sFTPScript)
fFTPScript.Close
Set fFTPScript = Nothing
oFTPScriptShell.Run "%comspec% /c FTP -n -s:" & sFTPTempFile & " " & sSite & _
" > " & sFTPResults, 0, TRUE
Wscript.Sleep 1000
'Check results of transfer.
Set fFTPResults = oFTPScriptFSO.OpenTextFile(sFTPResults, ForReading, _
FailIfNotExist, OpenAsDefault)
sResults = fFTPResults.ReadAll
fFTPResults.Close
oFTPScriptFSO.DeleteFile(sFTPTempFile)
oFTPScriptFSO.DeleteFile (sFTPResults)
If InStr(sResults, "226 Transfer complete.") > 0 Then
FTPUpload = True
ElseIf InStr(sResults, "File not found") > 0 Then
FTPUpload = "Error: File Not Found"
ElseIf InStr(sResults, "cannot log in.") > 0 Then
FTPUpload = "Error: Login Failed."
Else
FTPUpload = "Error: Unknown."
End If
Set oFTPScriptFSO = Nothing
Set oFTPScriptShell = Nothing
WScript.Echo "Process Completed (" & Now & ")"
End Function

Text templating engine/function in Visual Basic for Applications

A common usage of VBA at my company is generation of source code based on information entered in Excel tables. Given VBA's native string manipulation, the code that does this is tedious to write and not very readable.
A simple example (these get more complex) is:
Print #fileIdentifier, SSpace(9) & "update_" & print_string & "[" & CStr(j) & "] <= 1'b0;"
Print #fileIdentifier, SSpace(9) & print_string & "_ack_meta" & "[" & CStr(j) & "] <= 1'b0;"
Print #fileIdentifier, SSpace(9) & print_string & "_ack_sync" & "[" & CStr(j) & "] <= 1'b0;"
I am looking for a solution in VBA that would allow me to specify this using a "text template", so define a text that would look something like this
update_#name#[#bit#] <= 1'b0;
#name#_ack_meta[#bit#] <= 1'b0;
#name#_ack_sync[#bit#] <= 1'b0;
and have a function/method call, passing the values of #name# and #bit#, replace all instances of #name# and #bit# with corresponding values.
Basic insertion function:
Function insert(template As String, ParamArray inserts() As Variant) As String
Dim i As Long
For i = 0 To UBound(inserts)
template = Replace$(template, "%" & i + 1 & "%", inserts(i))
Next
'// some special cases perhaps
template = Replace$(template, "%SSPACE%", SSpace(9))
template = Replace$(template, "\r\n", VbCrLf)
insert = template
End Function
For
?insert("Foo %1% Bar %2% Qux %3% (%1%)", "A", "B", "C")
Foo A Bar B Qux C (A)
Map (add a reference to Microsoft Scripting Runtime):
Dim col As New Scripting.Dictionary
col("name") = "bob"
col("age") = 35
MsgBox insert2("Hello %name% you are %age%", col)
...
Function insert2(template As String, map As Scripting.Dictionary) As String
Dim name
For Each name In map.Keys()
template = Replace$(template, "%" & name & "%", map(name))
Next
insert2 = template
End Function
Alex K., thank you for the solution.
Here is how I expanded it (please feel free to let me know if there is a better way of doing this)
Function FillTemplateGeneric(template As Variant, map As Scripting.Dictionary) As String
Dim name
Dim out_text As String
' Handle multiple ways of receiving the template string
If VarType(template) = vbString Then
out_text = template
ElseIf VarType(template) = vbArray Then
out_text = Join(template, vbCrLf)
ElseIf TypeName(template) = "String()" Then
out_text = Join(template, vbCrLf)
ElseIf TypeName(template) = "Variant()" And TypeName(template(LBound(template, 1))) = "String" Then
out_text = Join(template, vbCrLf)
Else
MsgBox "Unknown Var Type passed to FillTemplateGeneric as first argument:" & vbCrLf & TypeName(template)
Err.Raise vbObjectError + 513, "FillTemplateGeneric", "Unknown Var Type passed to FillTemplateGeneric as first argument:" & vbCrLf & TypeName(template)
End If
For Each name In map.Keys()
out_text = Replace$(out_text, "%" & name & "%", map(name))
Next
FillTemplateGeneric = out_text
End Function
This allows for it to accept calls in multiple formats:
' Common dictionary for expansion
Dim col As New Scripting.Dictionary
col("name") = print_string
' Using inline text for template
MsgBox FillTemplateGeneric("test text with %name% name - just string", col)
' Using a multi-line string
Dim template As String
templ_text = " update_%name% <= 1'b0; // 1 - manual multi-line string" & _
vbCrLf & " %name%_ack_meta <= 1'b0; // " & _
vbCrLf & " %name%_ack_sync <= 1'b0; // "
MsgBox FillTemplateGeneric(templ_text, col)
' Using an array of strings
Dim ttext(1 To 3) As String
ttext(1) = " update_%name% <= 1'b0; // 2 - manual array of strings"
ttext(2) = " %name%_ack_meta <= 1'b0; // "
ttext(3) = " %name%_ack_sync <= 1'b0; // "
MsgBox FillTemplateGeneric(ttext, col)
' Using an inline array of strings
MsgBox FillTemplateGeneric(Array( _
" update_%name% <= 1'b0; // 3 - immediate array of strings", _
" %name%_ack_meta <= 1'b0; // ", _
" %name%_ack_sync <= 1'b0; // " _
), col)

comparing dataset through vb.net

dasaset (ds) contain value like this comapring two dataset and write the phone number from dataset to notepad which is not equal to dataset1.but am getting the result in notepad like the phone numbers which are equal to both dataset
dataset
-------
91 9942321400
91 9865015695
91 9677031515
91 9994828285
91 9688104229
dataset1 values
----------------
91 9942321400
91 9865015695
91 9677031515
expected result in notepad
--------------------------
91 9994828285
91 9688104229
my code
-------
Dim i As Integer = 0
Dim toggle As Boolean = False
Do While (i <= ds1.Tables(0).Rows.Count - 1)
Dim phone As String = ds1.Tables(0).Rows(i).Item(1).ToString
Dim j As Integer = 0
Do While (j <= Ds.Tables(0).Rows.Count - 1)
Dim dumphone As String = Ds.Tables(0).Rows(j).Item(4).ToString
If dumphone <> phone Then toggle = True 'This will set your flag to add the output.
j = (j + 1)
Loop
'After we're done checking if there's a match, we decided to add it to the output.
If toggle = True Then
TextBox1.AppendText(a.ToString & "|" & b.ToString & "|" & c.ToString & "|" & d.ToString & "|" & phone.ToString & "|" & e1.ToString & "|" & f.ToString & "|" & g.ToString & "|" & h.ToString & "|" & i1.ToString & "|" & j1.ToString & "|" & k.ToString & "|" & l.ToString & "|" & m.ToString & "|" & n1.ToString & "|" & o.ToString & "|" & p.ToString & "|" & q.ToString & "|" & r.ToString & "|" & s.ToString & "|" & t.ToString & "|" & u.ToString & "|" & v.ToString & "|" & w.ToString & "|" & x.ToString)
sw.WriteLine(TextBox1.Text)
TextBox1.Text = ""
toggle = False 'Reset the flag for the next value
End If
i = (i + 1) 'Move to the next value to check against.
Loop
but am getting the output in note pad like this
------------------------------------------------
91 9942321400
91 9865015695
91 9677031515
I tried this way and I got the result you were looking for...
For i As Integer = 0 To dataset.Tables(0).Rows.Count - 1
Dim found As Boolean = False
For j As Integer = 0 To dataset1.Tables(0).Rows.Count - 1
If dataset.Tables(0).Rows(i)(0).ToString = dataset1.Tables(0).Rows(j) (0).ToString Then
found = True
End If
Next
If found = False Then
'here you are getting the right result in each loop
'in this example i'm showing the result in a textbox
'just change the instruction and write them in your note pad or wherever you want to
MsgBox(dataset.Tables(0).Rows(i)(0).ToString)
End If
Next