Search a folder for keyword - vba

I'm looking to search a folder for a keyword term 'fuel', to pull information from returned files into a 'data' sheet.
For instance, I have a folder week numbers (1 - 52 cross the year so in the new year this will contain one folder but will build as the year goes on).
I search this folder for all .doc files contains the word 'fuel'.
You can do this via a Windows search by typing "fuel" in the search function in the top corner and it will display all filenames and all files that contains the word 'fuel'.
I have this for searching for a file that has 'fuel' in its name, but not inside it.
Sub LoopThroughFiles()
Dim MyObj As Object, MySource As Object, file As Variant
file = Dir("c:\testfolder\")
While (file <> "")
If InStr(file, "fuel") > 0 Then
MsgBox "found " & file
Exit Sub
End If
file = Dir
Wend
End Sub

It isn't particularly pretty, but think something like this should work:
Sub loopThroughFiles()
Dim file As String
file = FindFiles("C:\TestFolder", "fuel")
If (file <> "") Then MsgBox file
End Sub
Function FindFiles(ByVal path As String, ByVal target As String) As String
' Run The Sheell Command And Get Output
Dim files As String
Dim lines
files = CreateObject("Wscript.Shell").Exec("FIND """ & target & """ """ & path & "\*.*""").StdOut.ReadAll
lines = Split(files, vbCrLf)
' Look for matching files
Dim curFile As String
Dim line
For Each line In lines
If (Left(line, 11) = "---------- ") Then
curFile = Mid(line, 12)
End If
If (line = target) Then
FindFiles = curFile
Exit Function
End If
Next
FindFiles = ""
End Function
Uses the FIND command line and then reads the output (hence needing to use Wscript.Shell) and returns first match, or empty string if no file is found
Following #BLUEPIXY's command FINDSTR /M the function can be replaced by:
Function FindFiles(ByVal path As String, ByVal target As String) As String
' Run The Shell Command And Get Output
Dim files As String
files = CreateObject("Wscript.Shell").Exec("FINDSTR /M """ & target & """ """ & path & "\*.*""").StdOut.ReadAll
FindFiles = ""
If (files <> "") Then
Dim idx As Integer
idx = InStr(files, vbCrLf)
FindFiles = Left(files, idx - 1)
End If
End Function

Related

VBA: Code for creating subfolders and folders not working

I got this code from an online source and cant figure out what I have to change, for it to work, the folders are not being created in the desired location and I am unaware of where they are be created if any where?
Within the excel I have 3 command buttons, one to save the file to a specified location, one to email it to a collegue and lastly the command button which I am having issue with. Ill include images below.
And is it possible to cause a chain reaction between the codes, that once one is completed then the other will begin, as I can get them to work as they are on there own atm.
enter image description here
Mkdir can only create a single directory. You are trying to make two by supplying "9999 William Cox ltd\BRAKEL".
Make "9999 William Cox ltd" first, then make its child directories.
Here is some code that will generate all of the sub directories via a loop:
Add these functions to your code module:
Private Function makeDir(parentDir As String, childDir As String) As String
'Checks if supplied directory name exists in current path, if not then create.
childDir = parentDir & _
IIf(Left(childDir, 1) = "\", "", "\") & _
childDir & _
IIf(Right(childDir, 1) = "\", "", "\")
On Error Resume Next
MkDir childDir
On Error GoTo 0
makeDir = childDir
End Function
Public Sub makePath(parentDir As String, childPath As String)
Dim i As Integer
Dim subDirs As Variant
Dim newdir As String
Dim fPath As String
fPath = parentDir
subDirs = Split(childPath, "\")
For i = 0 To UBound(subDirs)
newdir = subDirs(i)
fPath = makeDir(fPath, newdir)
Next i
End Sub
Then replace this:
MkDir ("T:\Estimating\William Cox Project Enquiries 2018\" & fPath)
If Err.Number <> 0 Then
Err.Clear
End If
With this:
makePath "T:\Estimating\William Cox Project Enquiries 2018\", fpath
You should also remove On Error Resume Next so that you can catch any other errors - Another of which might be in your path (per the screenshot) which has "T:\Estimating" twice at the beginning.

Rename File on Different Drive Using VBA

I have a list of file names in a worksheet. I want to read a name, find the actual file, rename it and move on to the next name.
The 1st part, retrieving the name from the worksheet and modifying it to the new name is not a problem. The problem is assigning the new name to the file.
The Name function does not work because the files are on a different drive. I also tried Scripting.FileSystemObject.
The code runs but no change is made.
Here is the code I used...
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set f = fso.GetFile(fOldName)
If Not Err = 53 Then 'File not found
'Rename file
f.Name = fNewName
End If
Did I make a code mistake I'm not seeing? Should I be using/doing something else?
Finding info on VBA and/or VB6 is getting pretty rare these days.
BTW. This is for Excel 2016.
Tks
If there was no misunderstanding...
FSO... it's bad in any case. It's just a bugsful API wrapper, written with a left chicken paw.
There are pure VB & API for more sophisticated cases.
No external libs & objects:
Public Sub sp_PrjFilMov()
Dim i As Byte
Dim sNam$, sExt$, sPthSrc$, sPthTgt$, sDir$
sPthSrc = "V:\"
sPthTgt = "R:\"
sNam = "Empty_"
sExt = ".dmy" ' dummy
For i = 1 To 5 ' create set of files for test
Call sx_CrtFil(i, sPthSrc, sNam, sExt)
Next
sDir = Dir(sPthSrc & "*" & sExt, vbNormal) ' lookup for our files ..
Do
'Debug.Print sDir
Select Case LenB(sDir)
Case 0
Exit Do ' *** EXIT DO
Case Else
Call sx_MovFil(sPthSrc, sDir, sPthTgt) ' .. & move them to another disk
sDir = Dir
End Select
Loop
Stop
End Sub
Private Sub sx_CrtFil(pNmb As Byte, pPth$, pNam$, pExt$)
Dim iFilNmb%
Dim sFilNam$
sFilNam = pPth & pNam & CStr(pNmb) & pExt
iFilNmb = FreeFile
Open sFilNam For Output As #iFilNmb
Close #iFilNmb
End Sub
Private Sub sx_MovFil(pPnmSrc$, pFnm$, pPthTgt$)
Dim sSrcPne$
sSrcPne = pPnmSrc & pFnm
'Debug.Print "Move " & sSrcPne & " --> " & pPthTgt
Call FileCopy(sSrcPne, pPthTgt & pFnm)
Call Kill(sSrcPne)
End Sub
'

Searching a File in Directory

I would like to search a file in user-defined directory. My file structure like that xxx__description__myFileName__YYMMDD.txt there'll be multiple versions of this file so I want to list all files in directory which includes myFileName in their filename. Also I don't know is it the efficient way to list files with such type of code.
I tried to use this code but it gives me an error:
Run-time error '445': Object doesn't support this action
Sub findFiles()
Dim i As Integer
Dim myFile As String
myFileName = "ABC123"
With Application.FileSearch
.NewSearch
.LookIn = "C:\myTestDirectory"
.fileName = "*myFileName*.xlsx"
.SearchSubFolders = True
If .Execute() > 0 Then
For i = 1 To .FoundFiles.Count
Debug.Print .FoundFiles(i)
Next i
End If
End With
End Sub

Winzip not executing with gap in file path

I've used the code from Extract all .gz file in folder using VBA Shell command, to extract .gz files.The problem is that if there is a gap in the filepath, code doesn't work, if there is no gap, it works, as illustrated below:
Notice in first example, there is no '_' but a gap ' ', between 'K' and 'L', therefore file path has gaps,
whereas example that works, there is an '_', and the whole filepath has no gaps
'Example that doesn't work:
Sub extractAllFiles()
Dim MyObj As Object, MySource As Object, File As Variant
Dim shellStr As String
File = Dir("Z:\A_B_C\D_E_F\G_H_I\J_K L\_M_N_O\P_Q_R\*.gz")
While (File <> "")
If InStr(1, File, ".gz") > 0 Then
shellStr = "C:\Program Files\WinZip\winzip32 -e Z:\A_B_C\D_E_F\G_H_I\J_K L\_M_N_O\P_Q_R\" & File & " Z:\A_B_C\D_E_F\G_H_I\J_K L\_M_N_O\P_Q_R\"
Call Shell(shellStr, vbHide)
End If
File = Dir
Wend
End Sub
'Example that works:
Sub extractAllFiles()
Dim MyObj As Object, MySource As Object, File As Variant
Dim shellStr As String
File = Dir("Z:\A_B_C\D_E_F\G_H_I\J_K_L\_M_N_O\P_Q_R\*.gz")
While (File <> "")
If InStr(1, File, ".gz") > 0 Then
shellStr = "C:\Program Files\WinZip\winzip32 -e Z:\A_B_C\D_E_F\G_H_I\J_K_L\_M_N_O\P_Q_R\" & File & " Z:\A_B_C\D_E_F\G_H_I\J_K_L\_M_N_O\P_Q_R\"
Call Shell(shellStr, vbHide)
End If
File = Dir
Wend
End Sub
I want the first example to work, but why doesn't it?
There are no errors. The code runs, opens winzip, but it's empty, no file is unzipped!
Many thanks.
Try putting quotation marks around the paths in your shell string:
shellStr = "C:\Program Files\WinZip\winzip32 -e ""Z:\A_B_C\D_E_F\G_H_I\J_K L\_M_N_O\P_Q_R\" & File & """ ""Z:\A_B_C\D_E_F\G_H_I\J_K L\_M_N_O\P_Q_R\"""
In case you didn't already know, two double quotes ("") evaluates to a single double quote inside the string. Compare to languages like C where the backslash would be used to escape the quotation mark (\").

How to get the browse file path in text box using VBA?

How to get the browse file name into text box ? if get the file path, how to split the file name?
I tried application.GetOpenFilename("Text Files(*.txt),*.txt")
Please advise to display into the text box and how to split the exact file name only to read the text file?
Don't waste your time reinventing the wheel: the FileSystemObject will do this for you.
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Sheet1.TextBox1.Text = FSO.GetFilename("C:\mydir\myfile.dat")
The textbox now contains the text myfile.dat.
The Dir function will give you the file name as long as it's a file that exists - and yours will be if you use GetOpenFilename.
Sub GetFileName()
Dim sFullName As String
Dim sFileName As String
sFullName = Application.GetOpenFilename("*.txt,*.txt")
sFileName = Dir(sFullName)
Debug.Print sFullName, sFileName
End Sub
Here is a VBA routine to return the file name stripped of its path. Its easily modified to return the path instead, or both.
'====================================================================================
' Returns the file name without a path via file open dialog box
'====================================================================================
' Prompts user to select a file. Which ever file is selected, the function returns
' the filename stripped of the path.
Function GetAFileName() As String
Dim someFileName As Variant
Dim folderName As String
Dim i As Integer
Const STRING_NOT_FOUND As Integer = 0
'select a file using a dialog and get the full name with path included
someFileName = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If someFileName <> False Then
'strip off the folder path
folderName = vbNullString
i = 1
While STRING_NOT_FOUND < i
i = InStr(1, someFileName, "\", vbTextCompare) 'returns position of the first backslash "\"
If i <> STRING_NOT_FOUND Then
folderName = folderName & Left(someFileName, i)
someFileName = Right(someFileName, Len(someFileName) - i)
Else 'no backslash was found... we are done
GetAFileName = someFileName
End If
Wend
Else
GetAFileName = vbNullString
End If
End Function
Easiest way is to simply read from the final "\";
tbx.text = mid$(someFileName, 1 + InStrRev(someFileName, "\"), Len(someFileName))
Button1 click
OpenFileDialog1.ShowDialog()
Me.TextBox1.Text = OpenFileDialog1.FileName
End Sub
Textbox1 change
Dim File As System.IO.FileInfo
File = My.Computer.FileSystem.GetFileInfo(TextBox1.Text)
Dim Path As String = File.DirectoryName
TextBox2.Text = Path
Dim fileName As String = File.Name
TextBox3.Text = fileName
End Sub