How do loop through and open *.frm files in VB6? - vb6

In VB6, how can I loop through all the .frm files in a folder and do something to each of them?

MyFile = Dir(CurDir() & "\" & "*.frm")
Do While MyFile <> ""
' do stuff to file
MyFile = Dir
Loop

Related

How to rename an existing file in VB Script? [duplicate]

This question already has answers here:
Rename files without copying in same folder
(2 answers)
Closed 5 years ago.
I am very new to VB Script. I am trying to rename a file through VB Script could any one please help me in this ?
I just tried this but didn't work.
Dim OldFile As String
Dim NewFile As String
OldFile = "C:\apache-tomcat-8.0.44\apache-tomcat-8.0.44\webapps\" & "\" & timeStampDir & "\" & "output_11.docx"
NewFile = "C:\apache-tomcat-8.0.44\apache-tomcat-8.0.44\webapps\" & "\" & timeStampDir & "\" & "output.docx"
Name OldFile As NewFile
Use FileSystemObject and use Name property of a object referring the file you want to rename.
Dim OldFile, FSO, objFile
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
OldFile = "C:\apache-tomcat-8.0.44\apache-tomcat-8.0.44\webapps\" + CStr(timeStampDir) + "\output_11.docx"
Set objFile = FSO.GetFile(OldFile)
objFile.Name = "output.docx"
Keep in mind that you need to correctly escape all of the whitespaces in your oldFile variable, otherwise the file may not be found.
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.MoveFile OldFile, NewFile
Set objFSo = Nothing

Get a list of files in a directory with a specified pattern in filename in VB 6

I have a directory and it contains a number of files,
Some filenames start with say, abc_001.ini, abc_002.ini, abc_003.ini and so on.
There are other files as well in the same folder.
I want to get a list of files which start with abc_ and have a ".ini" extension.
How can I do this in VB 6?
Shamelessly stolen from the documentation at https://msdn.microsoft.com/en-us/library/aa262727(v=vs.60).aspx
MyPath = "c:\wherever\abc_*.ini" ' Set the path.
MyName = Dir(MyPath, vbDirectory) ' Retrieve the first entry.
Do While MyName <> "" ' Start the loop.
' Ignore the current directory and the encompassing directory.
If MyName <> "." And MyName <> ".." Then
Debug.Print MyName
End If
MyName = Dir ' Get next entry.
Loop

Vbs script read txt file with file names then search if taht file exist and move another file

I found this code:
Option Explicit ' .. Just coz.
Const forReading = 1 ' Set our constants for later.
Const forWriting = 2 ' ....
Dim inputFile, outputFile, fso, fileList, logFile, fileSpec ' Dimension our variables
inputFile = "filelist.txt" ' Our input file
outputFile = "missing.txt" ' Our output file
Set fso = CreateObject("Scripting.FileSystemObject") ' Set up fso
Set fileList = fso.OpenTextFile(inputFile, forReading) ' Open our input file for reading
If Not (fso.FileExists(outputFile)) Then fso.CreateTextFile(outputfile) ' Create output file if it doesn't exist
Set logFile = fso.OpenTextFile(outputFile, forWriting) ' Open up our output file for writing later
Do while not fileList.AtEndOfStream ' While we have lines to process do this loop
fileSpec = fileList.ReadLine() ' Read in line of text as variable fileSpec
If Not (fso.FileExists(fileSpec)) Then ' If it doesnt exist ....
logFile.writeline (fileSpec) ' ....Write it out to the output file
End If
Loop
fileList.close ' Clean up
logFile.close
Here is explanation of that code.
I need one more thing. I need move extra files from default directory (they are not write in filelist.txt) into the new directory. I need in default directory only files who are write in filelist.txt. I don't fully understand that code. I was try remake that code but each time failed.
Set problems (union, difference, ...) can be solved with a Dictionary in VBScript.
You have two sets of file names, one from your source file (SetF), one from the files in your default directory (SetD). In your existing loop over SetF, store the the names in a dictionary (DicF). Then add a loop over SetD (DefFolder.Files) and move the files that don't exist in DicF - as in:
>> SetF = Split("A D F G")
>> SetD = Split("B D G H")
>> Set DicF = CreateObject("Scripting.Dictionary")
>> For Each f in SetF
>> DicF(f) = 0
>> Next
>> For Each f In SetD
>> If Not DicF.Exists(f) Then
>> WScript.Echo f
>> End If
>> Next
>>
B
H
(cf. Compare arrays)

Extract all .gz file in folder using VBA Shell command

I have the following VBA code to extract all the files within a given directory.
Sub extractAllFiles()
Dim MyObj As Object, MySource As Object, file As Variant
Dim shellStr As String
file = Dir("C:\Downloads\")
While (file <> "")
If InStr(file, ".gz") > 0 Then
shellStr = "winzip32 -e C:\Downloads\" & file & " C:\Downloads\"
Call Shell(shellStr, vbHide)
End If
file = Dir
Wend
End Sub
When I execute this sub routine I get a Run-Time error 53, "File Not Found" error. When I copy the shellStr... Example: winzip32 -e C:\Downloads\file1.gz C:\Downloads\ and execute it from command prompt, it works perfectly! I get the text file within file1.gz extracted to the downloads directory. However running it from VBA doesn't seem to work.
Can anyone shed some light?
You should try with the full path of the shell command, like this, that worked for me:
Sub extractAllFiles()
Dim MyObj As Object, MySource As Object, file As Variant
Dim shellStr As String
file = Dir("C:\Downloads\")
While (file <> "")
If InStr(1, file, ".gz") > 0 Then
shellStr = "C:\Program Files (x86)\WinZip\winzip32 -e C:\Downloads\" & file & " C:\Downloads\"
Call Shell(shellStr, vbHide)
End If
file = Dir
Wend
End Sub
My winzip is installed as C:\Program Files (x86)\WinZip\winzip32. You should use yours.
Your install path may be:
C:\Program Files\WinZip\winzip32
WinZip path needs to be absolute path:
C:\Program Files\WinZip\winzip32'
Check your WinZip path. That needs to be fine fixed to the full path to your WinZip.
Using the logic from this SO post, try the below code:
Sub ExtractAllFiles()
Dim FileName As String
Dim ShellStr
FileName = Dir("C:\Downloads\*.gz")
Do While Len(FileName) > 0
ShellStr = "winzip32 -e " & FileName & " C:\Downloads"
Call Shell(ShellStr, vbHide)
FileName = Dir
Loop
End Sub
Let us know if this helps.

Trouble compressing large files using vbs

I have jumbled up a vbs script to compress files older than 7 days using 7za's command line utility. While most of the logic works fine, I am able to compress single file into single zip file.
The problem arises when I try to add all matching files to one zip file. Below is the code snippet:
strCommand = "7za.exe -mx=9 a " & ObjectFolder & sysDate & ".zip " & strFileName
strRun = objShell.Run(strCommand, 0, True)
Now as per the 2nd line, setting True would make sure the script will wait till command is finished executing. But the problem is 7za is exiting immediately and going to the next loop, processing the next file and since it tries to create same zip file, I get access denied error.
Can someone please help me to fix this?
I have also tested the scenario in command prompt. What I did was, execute below 2 commands simultaneously in separate prompts:
Prompt 1:
C:\7za.exe -mx=9 a test.zip c:\sample1.pdf
Prompt 2:
C:\7za.exe -mx=9 a test.zip c:\sample2.pdf
Prompt 2 resulted in following error:
Error: test.zip is not supported archive
System error:
The process cannot access the file because it is being used by another process.
This is the same error I am getting in my script and I need help in resolving this. Any pointers will be helpful!
UPDATE:
With the great pointers provided by both John and Ansgar, I was able to resolve this! It turned out to be a bug in my script! In my script, I included a check to see if the file is in use by any other process before processing it for archive. So I was checking this by opening the file for appending using:
Set f = objFSO.OpenTextFile(strFile, ForAppending, True)
But before proceeding to process the same file, I was not CLOSING it in the script, hence the error: The process cannot access the file because it is being used by another process
After I closed the file, all went well!
Thanks Again for all the great support I got here!
As a token of gratitude, I am sharing the whole script for anyone's use. Please note that I am not the original author of this, I gathered it from various sources and tweaked it a little bit to suit my needs.
Archive.vbs
Const ForAppending = 8 ' Constant for file lock check
Dim objFSO, objFolder, objFiles, objShell
Dim file, fileExt, fileName, strCommand, strRun, strFile
Dim SFolder, OFolder, Extension, DaysOld, sDate
'''' SET THESE VARIABLES! ''''
SFolder = "C:\SourceFolder\" 'Folder to look in
OFolder = "C:\OutputFolder\" 'Folder to put archives in
Extension = "pdf" 'Extension of files you want to zip
DaysOld = 1 'Zip files older than this many days
''''''''''''''''''''''''''''''
sDate = DatePart("yyyy",Date) & "-" & Right("0" & DatePart("m",Date), 2) & "-" & Right("0" & DatePart("d",Date), 2)
'Create object for playing with files
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Create shell object for running commands
Set objShell = wscript.createObject("wscript.shell")
'Set folder to look in
Set objFolder = objFSO.GetFolder(SFolder)
'Get files in folder
Set objFiles = objFolder.Files
'Loop through the files
For Each file in objFiles
fileName = Split(file.Name, ".")
fileExt = fileName(UBound(fileName))
'See if it is the type of file we are looking for
If fileExt = Extension Then
'See if the file is older than the days chosen above
If DateDiff("d", file.DateLastModified, Now()) >= DaysOld Then
strFile = file.Path
'See if the file is available or in use
Set f = objFSO.OpenTextFile(strFile, ForAppending, True)
If Err.Number = 70 Then ' i.e. if file is locked
Else
f.close
strFName = objFSO.GetBaseName(file.name)
strCommand = "C:\7za.exe -mx=9 a " & OFolder & sDate & ".zip " & strFile
strRun = objShell.Run(strCommand, 0, True)
'wscript.echo strCommand ' un-comment this to check the file(s) being processed
'file.Delete ' un-comment this to delete the files after compressing.
End If
End If
End If
Next
'Cleanup
Set objFiles = Nothing
Set objFolder = Nothing
Set objFSO = Nothing
Set objShell = Nothing
wscript.Quit
===========================
Thanks
-Noman A.
Not quite what you asked for, but here's a batch script I use for a similar task in case that helps get you past of your immediate issue:
ArchiveScriptLog.Bat
::ensure we're in the right directory, then run the script & log the output
cls
pushd "c:\backup scripts"
ArchiveScript.bat > ArchiveScript.log
popd
ArchiveScript.bat
::Paths (must include the \ on the end). There must be no space between the equals and the value
::UNC paths are acceptable
Set FolderToBackup=F:\EnterpriseArchitect\Energy\
Set BackupPath=F:\EnterpriseArchitect\!ARCHIVE\
Set RemoteBackupPath=\\ukccojdep01wok\h$\Energy\cciobis01edc\
Set SevenZip=C:\Program Files (x86)\7-Zip\
::Get DATE in yyyymmdd format; done in two lines to make it easy to change the date format
FOR /F "TOKENS=2,3,4 DELIMS=/ " %%A IN ('echo %Date%') DO (SET mm=%%A&SET dd=%%B&SET yyyy=%%C)
SET strDate=%yyyy%%mm%%dd%
::Set the Backup File to be the backup path with the current date & .zip on the end
Set BackupFile=%BackupPath%%strDate%.zip
::create a zip containing the contents of folderToBackup
pushd %SevenZip%
7z a "%BackupFile%" "%FolderToBackup%"
popd
::go to the archive directory & copy all files in there to the remote location (this accounts for previous errors if the network were unavailable)
pushd "%BackupPath%"
move *.zip "%RemoteBackupPath%"
popd
::delete off backups in the remote location which are older than 90 days
pushd "%RemoteBackupPath%"
forfiles /D -90 /M *.zip /C "cmd /c del #file"
popd
Your command shouldn't return before 7za has finished its task (and it doesn't in my tests). Try changing your code to the following, so you can see what's going on:
strCommand = "7za.exe -mx=9 a " & ObjectFolder & sysDate & ".zip " & strFileName
strCommand = "%COMSPEC% /k " & strCommand
strRun = objShell.Run(strCommand, 1, True)
It may also be a good idea to quote the filenames:
Function qq(str)
qq = Chr(34) & str & Chr(34)
End Function
strCommand = "7za.exe -mx=9 a " & qq(ObjectFolder & sysDate & ".zip") & " " _
& qq(strFileName)

Resources