VBS to find file with date and to change that date to the previous day - date

New here and VERY new to VBS so please easy.
I have a set of files that are sent via FTP to a folder on a server, the naming structure of these files are:
waw_29_2013-09-09_act_v001.csv
waw_29_2013-09-09_amf_v001.csv
waw_29_2013-09-09_inc_v001.csv
waw_29_2013-09-09_nbs_v001.csv
waw_29_2013-09-09_trn_v001.csv
waw_29_2013-09-09_val_v001.csv
waw_29_2013-09-09_wth_v001.csv
What I am trying to achieve is for a script to scan the folder that contains these files, and change the name to the previous day but keep the structure of the naming convention.
I have tried this on a file in my c:\ drive (I am very new so please excuse my lack of understanding)
**Dim file1, file2
file1 = "C:\fake_%date%.txt"
file2 = "C:\waw_" & year(date) & -month(date) & -Day(Date) & "_act_v001.csv"
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(file1) = true then
If fso.FileExists(file2) = true then
fso.DeleteFile(file2)
End if
fso.MoveFile file1, file2
'else
' msgbox "File does not exist"
End If
Set FSO = Nothing**
The is on a file (as a test) called c:\fake_2013-09-09.txt and it is trying to scan the c:\ drive for that file (regardless of the date) and then rename this file to "waw_29_2013-09-09_act_v001.csv"
.
I also need the same script to run separately but to change the date back 3 days for weekends too.
Any help would be hugely appreciated.
Take care
Mike
Hello again
I have gotten a little further:
I have now amended the script to look as follows:
Dim file1, file2
file1 = "C:\winter\waw_29_2013-09-10_act_v001.csv"
file2 = "C:\winter\waw_29_" & -Year(Date) & Right("0" & Month(Date),2) & Right
("0" & -Day(Date),2) & "_act_v001.csv"
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(file1) = true then
If fso.FileExists(file2) = true then
fso.DeleteFile(file2)
End if
fso.MoveFile file1, file2
'else
' msgbox "File does not exist"
End If
Set FSO = Nothing
Now I have 2 questions about the script as I think it is 90% there:
The line in File1, how can I get this to search for the file but to only search on the and _act field?
Under File2, I can get the system to now produce a date for the file (the wrong date but I am getting there) but the format is 20130909 and not 2013-09-09 as I need. How do I add in the "-" between dates as it fails if I leave the "& Right("0")" in to create the leading "0" but if I take that out, it will put the "-" in but no leading )!!!
My last question is I have found the DateAdd command that allows me to search the file and then change the date to the previous date.....my problem is I don't know where to put that in the code.
Guys if you can help, I would be really grateful.
Mike
WOW thank you so much, really helped a lot and solved the second part of my issue.
Do you know how to search a folder for a set parameter so I can search a folder named "waw_29_2013-09-09_act_v001.csv" but to exclude the date section from the search?
Again thank you so much, I learnt a lot from that part of the script
Mike

For building a date string of the form YYYY-MM-DD you need to concatenate the date portions and the interleaving hyphens:
d = Date
Year(d) & "-" & Right("0" & Month(d), 2) & "-" & Right("0" & Day(d), 2)
For building a date string of 3 days ago you do the same, but subtract 3 days from the current date first:
d = Date - 3
Year(d) & "-" & Right("0" & Month(d), 2) & "-" & Right("0" & Day(d), 2)

Related

MS Access - Report to PDF - Data fields not populating in controls on PDF

I am trying to generate a pdf file, based on the contents of an Access Form or a Report (either is fine for me but understand it should be done via a report).
I can generate/populate the form itself, and the report itself, but when I create the pdf with this code, the fields in the pdf are blank. The controls are all there, like seen in my form, but the fields that should have data don't get copied over.
This works as-is for me, and makes a pdf that looks just like my report, except the data from the report does not carry over to the saved pdf
Private Sub pdfBtn_Click()
Dim fileName As String, fldrPath As String, filePath As String
Dim answer As Integer
fileName = "File_Test1" 'filename for PDF file*
fldrPath = "C:\Users\myname\Desktop" 'folder path where pdf file will be saved *
filePath = fldrPath & "\" & fileName & ".pdf"
'check if file already exists
If FileExist(filePath) Then
answer = MsgBox(prompt:="PDF file already exists: " & vbNewLine & filePath & vbNewLine & vbNewLine & _
"Would you like to replace existing file?", buttons:=vbYesNo, Title:="Existing PDF File")
If answer = vbNo Then Exit Sub
End If
On Error GoTo invalidFolderPath
DoCmd.OutputTo acOutputReport, "Report2", acFormatPDF, filePath
MsgBox prompt:="PDF File exported to: " & vbNewLine & filePath, buttons:=vbInformation, Title:="Report Exported as PDF"
Exit Sub
invalidFolderPath:
MsgBox prompt:="Error: Invalid folder path. Please update code.", buttons:=vbCritical
End Sub
Function FileExist(FileFullPath As String) As Boolean
Dim value As Boolean
value = False
If Dir(FileFullPath) <> "" Then
value = True
End If
FileExist = value
End Function
I've spent a few hours searching, so I'd be upset if it is something overly simple and available. But is anyone able to point me in the right direction with this?
It looks like I had some logic wrong. Yes the code provided does work, thanks again #June7. I was over complicating things by trying to generate the pdf off the form itself, versus off a report. I ended up making the button pop up the report instead of another form, and the data does now flow as expected.
Silly, like I said :(

Comparing creation dates of files in VBScript

This may be very obvious to someone out there but I'm having a lot of trouble trying to solve a bug in VBScript. Within the script, I am running through a bunch of .zip files in a directory and processing ones whose creation date is within a specified range.
For instance, if the user enters two arguments 9/3/2014 and 9/5/2014, I only want to process zip files within that date range.
Here is the if statement I am using:
If Mid(file.NAME,len(file.NAME)-3,4) = ".zip" AND
FormatDateTime(file.DateCreated, 2) >= Wscript.Arguments(1) AND
FormatDateTime(file.DateCreated, 2) <= Wscript.Arguments(2) then
I am using the FormatDateTime function to remove the times from the file creation date. That way I should just be left with a short date (mm/dd/yyyy).
The problem I am having is that I am processing dates outside of the given range. For example if the given range is 9/3/2014 to 9/5/2014 then I also end up processing 9/30/2014 for some reason. Can anyone help solve this?
Both the return value of FormatDateTime() and the items of .Argments are Strings. A string comparison of (stringyfied) numbers will give inconvenient results:
>> WScript.Echo CStr(5 < 30)
>> WScript.Echo CStr("5" < "30")
>>
True
False
Use CDate() to convert the .Arguments to Dates and DateDiff() to compare them against the .DateCreated.
Found the source of my problem. FormatDateTime returns a string. Furthermore, the arguments I was being passed were strings also. This means I was actually doing a string comparison instead of a date comparison. The if statement should be:
If Mid(file.NAME,len(file.NAME)-3,4) = ".zip" AND
CDate(FormatDateTime(file.DateCreated, 2)) >= CDate(Wscript.Arguments(1)) AND
CDate(FormatDateTime(file.DateCreated, 2)) <= CDate(Wscript.Arguments(2)) then

How to convert multiple visio file (.vsd) to png

I have a lot of Visio files, and want to programatically convert them all to png format.
I have found a couple of solutions, but can't get any of them to work.
How can .vsd files be batch-converted to .png easily through commandline or a similar means?
Use the built in Visual Basic
something like this: fix up the paths parts yourself.
Sub a()
Dim docs As New Collection
' add the paths of your documents here, use more script if you want wildcard etc
docs.Add ("C:\Users\[username]\Desktop\New folder (4)\drawing2.vsd")
docs.Add ("C:\Users\[username]\Desktop\New folder (4)\drawing3.vsd")
For Each d In docs
Dim doc As Document
Set doc = Documents.Add(d)
Dim p As Page
For Each p In doc.Pages
Dim n As String
' change this for the output path and format of your choice
n = "C:\Users\[username]\Desktop\New folder (4)\" & doc.Name & " " & p.Index & ".png"
p.Export (n)
Next
Next
End sub

Unicode named Folder shows ? in wscript prompt

I am facing problems with Unicode named folders. When I drag the folder to the script, it doesn't show the path of the folder properly.
Simple VBScript (this is just a portion of it):
Dim Wshso : Set Wshso = WScript.CreateObject("WScript.Shell")
Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject")
If WScript.Arguments.Count = 1 Then
If FSO.FileExists(Wscript.Arguments.Item(0)) = true and FSO.FolderExists(Wscript.Arguments.Item(0)) = false Then
Alert "You dragged a file, not a folder! My god." & vbcrlf & "Script will terminate immediately", 0, "Alert: User is stupid", 48
WScript.Quit
Else
targetDir = WScript.Arguments.Item(0)
Wshso.Popup targetDir
End If
Else
targetDir = Wshso.SpecialFolders("Desktop")
Alert "Note: No folder to traverse detected, default set to:" & vbcrlf & Wshso.SpecialFolders("Desktop"), 0, "Alert", 48
End If
If it is a normal path without Unicode characters, it's fine. But in this case:
Directory: 4minute (포미닛) - Hit Your Heart
Then it will show something like 4minute (?) - Hit Your Heart
And if I do a FolderExists it can't find the dragged folder.
Is there any workaround to support Unicode named Folders?
Thanks!
I'll edit if this is not clear enough
This does seem to be a problem peculiar to the Windows Script Host's DropHandler shell extension. Whereas:
test.vbs "C:\포미닛.txt"
C:\WINDOWS\System32\WScript.exe "test.vbs" "C:\포미닛.txt"
both work when typed from the console (even if the console can't render the Hangul so it looks like ?), a drag and drop operation that should result in the same command goes through a Unicode->ANSI->Unicode translation that loses all characters that aren't in the current ANSI code page. (So 포미닛 will work on a default Korean Windows install but not Western.)
I'm not aware of a proper way to fix the problem. You could perhaps work around it by changing the DropHandler for .vbs files in the registry:
HKEY_CLASSES_ROOT\VBSFile\ShellEx\DropHandler\(Default)
from the WSH DropHandler ({60254CA5-953B-11CF-8C96-00AA00B8708C}) to {86C86720-42A0-1069-A2E8-08002B30309D}, the one used for .exe, .bat and similar, which doesn't suffer from this issue. You would also probably have to change the file association for .vbs to put quotes around the filename argument too, since the EXE DropHandler doesn't, to avoid problems with spaces in filenames.
Since this affects argument-passing for all VBS files it would be a perilous fix to deploy on any machine but your own. If you needed to do that, maybe you could try creating a new file extension with the appropriate DropTarget rather than changing VBSFile itself? Or maybe forgo drop-onto-script behaviour and provide a file Open dialog or manual drop field instead.
For anyone landing here from Google...
Bobince's tip lead me to work around this problem by wrapping my vbscript file (myscript.vbs) in a dos batch file (mybatch.bat).
The tip was:
"Seem to be a problem peculiar to the Windows Script Host's
DropHandler shell extension whereas.... the one used for .exe, .bat and
similar... doesn't suffer from this issue."
mybatch.bat contains:
:Loop
IF "%1"=="" GOTO Continue
set allfiles=%allfiles% "%1"
SHIFT
GOTO Loop
:Continue
"myscript.vbs" %allfiles%
You may also find this code from my myscript.vbs to be helpful
For Each strFullFileName In Wscript.Arguments
' do stuff
Next
Based on DG's answer, if you just want to accept one file as drop target then you can write a batch file (if you have it named as "x.bat" place VBScript with filename "x.bat.vbs" at same folder) that just contains:
#"%0.vbs" %1
the # means to not output the row on the display (I found it to show garbage text even if you use chcp 1250 as first command)
don't use double-quotes around %1, it won't work if your VBScript uses logic like the following (code I was using below was from http://jeffkinzer.blogspot.com/2012/06/vbscript-to-convert-excel-to-csv.html). Tested it and it works fine with spaces in the file and folder names:
Dim strExcelFileName
strExcelFileName = WScript.Arguments.Item(0) 'file name to parse
' get path where script is running
strScript = WScript.ScriptFullName
Dim fso
Set fso = CreateObject ("Scripting.FileSystemObject")
strScriptPath = fso.GetAbsolutePathName(strScript & "\..")
Set fso = Nothing
' If the Input file is NOT qualified with a path, default the current path
LPosition = InStrRev(strExcelFileName, "\")
if LPosition = 0 Then 'no folder path
strExcelFileName = strScriptPath & "\" & strExcelFileName
strScriptPath = strScriptPath & "\"
else 'there is a folder path, use it for the output folder path also
strScriptPath = Mid(strExcelFileName, 1, LPosition)
End If
' msgbox LPosition & " - " & strExcelFileName & " - " & strScriptPath
Modify WSH DropHandler ({60254CA5-953B-11CF-8C96-00AA00B8708C}) to {86C86720-42A0-1069-A2E8-08002B30309D} and add this function to convert short path to long:
Function Short2Long(shortFullPath)
dim fs
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(shortFullPath)
Set app = CreateObject("Shell.Application")
Short2Long = app.NameSpace(f.ParentFolder.Path).ParseName(f.Name).Path
end function

Tool to merge MS Word files

I have huge number of Word files I need to merge (join) into one file, and will be time consuming to use the Word merger (one by one). Have you experienced any tool that can handle this job?
Sub MergeAllDocuments(AllDocumentsPath as String, MasterDocumentPath as String)
Dim MasterDocument As Document
Set MasterDocument = Documents.Open(FileName:=MasterDocumentPath)
TheDocumentPath = Dir(AllDocumentsPath , vbNormal)
While TheDocumentPath <> ""
' Append the next doc to the end of the master doc. (The
' special "\EndOfDoc" bookmark is always available!)
MasterDocument.Bookmarks("\EndOfDoc").Range.InsertFile TheDocumentPath
TheDocumentPath = Dir
Wend
MasterDocument.Save
End Sub
MergeAllDocuments "C:\MySeparateDocuments\*.doc", "C:\MasterDocument.doc"
I have one question - why do you want do do such a thing (with a "huge number" of documents, at least)?
I came across a post by Graham Skan a while back. It might get you started:
Sub InsertFiles()
Dim strFileName As String
Dim rng As Range
Dim Doc As Document
Const strPath = "C:\Documents and Settings\Graham Skan\My Documents\Allwork\" 'adjust as necessary '"
Set Doc = Documents.Add
strFileName = Dir$(strPath & "\*.doc")
Do
Set rng = Doc.Bookmarks("\EndOfDoc").Range
If rng.End > 0 Then 'section break not necessary before first document.'
rng.InsertBreak wdSectionBreakNextPage
rng.Collapse wdCollapseEnd
End If
rng.InsertFile strPath & "\" & strFileName
strFileName = Dir$()
Loop Until strFileName = ""
End Sub
Have you tried using the Word COM api? You can automate lots of things - maybe you can automate a merge.
Do you really need to do an actual merge, or do you want to join the files together. The two things are quite different.
Merging is used when you have two versions of an original file with (potentially conflicting) changes. I can't really see how you would have a "huge number" of files that you needed to merge all together. This would be an absolute nightmare of conflicts. Do you mean to merge sets of them into individual files?
Joining would be when you want to concatenate them one after the other. This would be a lot easier to do. This is quite possible using the COM api.