Search for Excel Files in a Column Range using FSO - excel

In the code below what I am trying to achieve is that the code searches for the files that are entered in column range F in the given path which is "D:\Checksheets\". I am still learning the FSO and would greatly appreciate any help.
Sub Test()
Dim FSO As Object
Dim FSO_Folder As Object
Dim FSO_file As Object
Dim path As String
Dim sheetref As String
Dim nextform As String
Dim row As Integer
Dim col As Integer
row = 8
col = 6
sheetref = Sheets("Sheet1").Cells(row, col)
'nextform = sheetref
path = "D:\Checksheets\"
Do Until Sheets("Sheet1").Cells(row, col) = "END"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FSO_Folder = FSO.GetFolder(path)
For Each FSO_file In FSO_Folder.Files
If FSO_file.Name = sheetref Then
MsgBox "done" & path
Else
End If
row = row + 1
Next
Loop
End Sub

The FSO has a built in FileExists method:
...
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim sht As Worksheet, cell As Range
Set sht = Sheets("Sheet1")
Do
Set cell = sht.Cells(row, col)
If cell.Value = "END" Then Exit Do
If FSO.FileExists(path & cell.Value) Then
MsgBox "done " & cell.Value
End If
row = row + 1
Loop
You can remove the FSO code entirely and replace the FileExists call with the built-in Dir$ function:
If Len(Dir$(path & cell.Value)) Then

Thanks to Alex I was able to get the code working. In case someone has similar issue, below is the code:
Sub test()
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim sht As Worksheet, cell As Range
Dim row As Integer
Dim col As Integer
Dim path As String
path = "D:\Checksheets\"
row = 1
col = 6
Set sht = Sheets("Sheet1")
Do
Set cell = sht.Cells(row, col)
If cell.Value = "END" Then Exit Do
If cell.Value <> "" Then ' checks for any empty cells
FSO.FileExists (path)
MsgBox "file exists"
Else
End If
row = row + 1
Loop
End Sub

Related

Why is my match row function not being entered?

I have a userform that is pulling in data from a worksheet into the userform fields. I have a function that matches the row of that employee if the employee number in userform is found in column F.
It used to work but now it doesn't even enter the function to determine if that employee exists in the data.
Private Sub CommandButton2_Click()
On Error Resume Next
Dim wb As Workbook: Set wb = Workbooks.Open("J:\HRIS Team\Analytics\Headcount Tracking File.xlsx")
Dim ws As Worksheet: Set ws = wb.Worksheets("Sheet1")
Dim lString As String, lArray() As String
lString = cmbEmployee.Value
lArray = Split(lString, " - ")
Dim recRow As Range
If optEmployeeName.Value = True And optEmployeeID.Value <> True Then
Set recRow = MatchRow(ws.Range("A1").CurrentRegion, _
lArray(1))
Else
Set recRow = MatchRow(ws.Range("A1").CurrentRegion, _
lArray(0))
End If
If recRow Is Nothing Then MsgBox "Employee not found"
With recRow.EntireRow
Me.cmbFunction.Value = .Cells(1).Value
Me.cmbHRBP.Value = .Cells(3).Value
Me.cmbRequestType.Value = .Cells(4).Value
Me.cmbMovementType.Value = .Cells(7).Value
Me.txtEffectiveDate.Value = .Cells(8).Value
Function MatchRow(tablerange As Range, lArray) As Range
Dim rw As Range
Dim lString_2 As String, lArray_2() As String
lString_2 = cmbEmployee.Value
lArray_2 = Split(lString_2, " - ")
For Each rw In tablerange.Rows
If optEmployeeName.Value = True Then
If CStr(rw.Cells(6).Value) = Trim(lArray_2(1)) Then
Set MatchRow = rw
Exit Function
End If
ElseIf optEmployeeID.Value = True Then
If CStr(rw.Cells(6).Value) = Trim(lArray_2(0)) Then
Set MatchRow = rw
Exit Function
End If
End If
Next rw
End Function
I hover over to make sure it's getting the employee ID correctly from the lArray, and its there. I can't figure out the reasoning behind why it wouldn't even attempt to enter the matchrow function. Any ideas?

Workbook.Open can not find the file

I am running the following code. The code is for finding some particular values in all the Excel sheets in a folder.
It gives me the error
"Sorry, we couldn't find the file. Is it possible it was moved, renamed or deleted?"
when it executes
Set wbSlave = Workbooks.Open(filename:=myfilname)
Please help.
Sub find_cells()
Dim i, j As Integer
Dim cell_content As String
Dim total_values As Long
Dim cell_location As Range
Dim cell_address As String
Dim sht As Worksheet
Dim myfilname As String
Dim fldrpath As String
Dim wbMaster As Workbook
Dim wbSlave As Workbook
Dim currentfilename As String
Set wbMaster = ThisWorkbook
j = 3
total_values = Application.WorksheetFunction.CountA(wbMaster.Sheets("Engine").Range("A:A"))
fldrpath = "C:\test\"
myfilname = Dir(fldrpath & "*.xls*")
Application.ScreenUpdating = False
Do While myfilname <> ""
'myfilname = Dir()
Set wbSlave = Workbooks.Open(filename:=myfilname)
For Each sht In wbSlave.Sheets
For i = 2 To total_values
cell_content = wbMaster.Sheets("Engine").Range("A" & i).Value
With sht.UsedRange
Set cell_location = .Find(cell_content, LookIn:=xlValues, MatchCase:=False, SearchFormat:=False)
If Not cell_location Is Nothing Then
cell_address = cell_location.Address
Do
wbMaster.Sheets("Sheet1").Columns(j).Value = cell_location.EntireColumn.Value
j = j + 1
Set cell_location = .FindNext(cell_location)
Loop While Not cell_location Is Nothing And cell_location.Address <> cell_address
End If
End With
Set cell_location = Nothing
If i = total_values Then Exit For
Next i
Next
myfilname = Dir()
Loop
End Sub
The Dir function returns only the matching filename - no path. Then if you try to open it and you are currently not in a correct folder, you get this error.
Set a watch to the variable myfilname or just add Debug.Print myfilname and you see it right away.
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/dir-function

How to Find specific text word using Excel vba

I need to find a specific word from an Excel file. I want to search row by row, and if the word is found, skip 2 rows down and copy the next 20 rows and loop to the next word.
Sub Example4()
Dim FilePath As Workbook
Dim wsheet As Worksheet
Dim i, lcount, lcount2 As Integer
Dim cell, rgFound As Range
Dim Found As Range, LastRow As Long
Set FilePath = Workbooks.Open("D:\SLC.txt")
Dim rowVal As Integer
rowVal = 1
For lcount = 1 To FilePath.Sheets("SLC").Range("A1048576").End(xlUp).Row
Set rgFound = Range("A1:A1048576").Find("TXN. NO TXN SEQ", ThisWorkbook.Sheets(), Cells(rowVal, 1))
FilePath.Cells(wsheet.Range(rowVal).End(xlDown).Row + 3).xlCopy
wbook2.Worksheets(1).Range("A1").PasteSpecial xlPasteValuesAndNumberFormats
wbook2.SaveAs ("D:\SLC_Copied.xlsx")
wbook2.Close
rowVal = rgFound1.Row
Debug.Print lcount
Next lcount
End Sub
As Siddharth Rout suggested, use Find and FindNext.
Try to choose variable names appropriate to their type, calling a workbook object FilePath is confusing to others trying to understand your script.
Option Explicit
Sub Example4()
Const TEXT = "TXN. NO TXN SEQ"
Const TEXT_FILENAME = "D:\SLC.txt"
Const OUT_FILENAME = "D:\SLC_Copied.xlsx"
Dim wbText As Workbook, wbOut As Workbook, rngOut As Range
Dim wsText As Worksheet, wsOut As Worksheet, count As Integer
Dim rngSearch As Range, rngFound As Range, rowFirstFind As Long
' open text file no link update, read only
Set wbText = Workbooks.Open(TEXT_FILENAME, False, True)
Set wsText = wbText.Sheets(1)
' search
Set rngSearch = wsText.Columns("A:A")
Set rngFound = rngSearch.Find(what:=TEXT, LookIn:=xlValues, LookAt:=xlPart)
If rngFound Is Nothing Then
wbText.Close
MsgBox "No lines match [" & TEXT & "]", vbCritical, "Exiting Sub"
Exit Sub
Else
' create new workbook for results
Set wbOut = Workbooks.Add
Set wsOut = wbOut.Sheets(1)
Set rngOut = wsOut.Range("A1")
rowFirstFind = rngFound.Row
Do
'Debug.Print rngFound.Row
rngFound.Offset(3, 0).Resize(20, 1).Copy rngOut
Set rngOut = rngOut.Offset(20, 0)
Set rngFound = rngSearch.FindNext(rngFound)
count = count + 1
Loop Until rngFound.Row = rowFirstFind
End If
wbText.Close False
wbOut.SaveAs OUT_FILENAME
MsgBox count & " blocks copied to " & wbOut.Name, vbInformation, "Finished"
wbOut.Close
End Sub

How to adapt this to work with another worksheet?

How do I adapt this to work with another worksheet rather than the worksheet I have visible.
If (IsEmpty(Cells(RowNum, ColumnNum).Value)) Then
GoTo nextloop:
End If
I have moved parenthesis, tried including workbook name but I think I'm just not getting the syntax. I'm not very good with excel.
What I'm trying to achieve. Take all contents of a column, push the data into a bat file. Script will be launched from a button on another worksheet.
UPDATED Full Code: (Tried Ryan's answer, was getting error. Fixed it but then the script did nothing.)
Sub Send2Bat()
Dim ColumnNum: ColumnNum = 26 ' Column Z - I have the I J and K Columns concatenated there.
Dim RowNum: RowNum = 0
Dim objFSO, objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("C:\Test\Convert.bat") 'Output Path
aFile = "C:\Test\Convert.bat"
Dim OutputString: OutputString = ""
Dim LastRow: LastRow = Application.ActiveSheet.Cells(Application.ActiveSheet.Rows.Count, ColumnNum).End(xlUp).Row
Do
nextloop:
RowNum = RowNum + 1
If (IsEmpty(Cells(RowNum, ColumnNum).Value)) Then
GoTo nextloop:
End If
OutputString = OutputString & Replace(Cells(RowNum, ColumnNum).Value, Chr(10), vbNewLine) & vbNewLine
Loop Until RowNum = LastRow
objFile.Write (OutputString)
Set objFile = Nothing
Set objFSO = Nothing
End Sub
I made an excel workbook and put some data in column z for Sheet 1 and Sheet 2.
And I tweaked your code to read as follows:
Sub Send2Bat()
Dim ColumnNum: ColumnNum = 26 ' Column Z - I have the I J and K Columns concatenated there.
Dim RowNum: RowNum = 0
Dim objFSO, objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("C:\Test\Convert.bat") 'Output Path
aFile = "C:\Test\Convert.bat"
Dim OutputString: OutputString = ""
Dim targetSheet As Worksheet
Set targetSheet = Application.Worksheets("Sheet1")
Dim LastRow: LastRow = targetSheet.Cells(targetSheet.Rows.Count, ColumnNum).End(xlUp).Row
Do
RowNum = RowNum + 1
If Not (IsEmpty(targetSheet.Cells(RowNum, ColumnNum).Value)) Then
OutputString = OutputString & Replace(targetSheet.Cells(RowNum, ColumnNum).Value, Chr(10), vbNewLine) & vbNewLine
End If
Loop Until RowNum = LastRow
objFile.Write (OutputString)
Set objFile = Nothing
Set objFSO = Nothing
End Sub
And it produced the following file:
So then I updated the targetSheet name to "Sheet2"
Set targetSheet = Application.Worksheets("Sheet2")
and executed again. The file updated to this:
So, the code is good at least in its basic form. Do you have anything else updating the sheets or moving things around while this is happening?

Selecting the first column (A), not the first in a selection (VBA-Excel)

I've been trying to do this for a while but I'm stumped. I'm trying to loop through a selection so that I can take some information and put and save on a text file. It works, except that when the selection does NOT start in Column A, some data is not brought into the text file (it takes Columns(1) as the first column in the selection). Here's the code:
Sub SaveInfoTxtFile()
Dim oCell As Range
Dim myRange As Range
Dim fso As Object
Dim oFile As Object
Dim LastRow As Long
Dim wholeselect As String
Dim year As String
Dim make As String
Dim model As String
Set myRange = Selection
LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
wholeselect = CStr(myRange.Row) & ":" & CStr(LastRow)
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.CreateTextFile("C:\SSE\test.txt")
Rows(wholeselect).Select
For Each oCell In myRange
year = oCell.Columns(1).Text
make = oCell.Columns(2).Text
model = oCell.Columns(3).Text
oFile.WriteLine year & " " & make & " " & model
oFile.WriteLine
Next oCell
oFile.WriteLine "Name: Blah"
oFile.WriteLine "Company: Blah2"
oFile.Close
Set fso = Nothing
Set oFile = Nothing
End Sub
Suggestions?
Here are 2 ways to solve this:
year = oCell.EntireRow.Columns(1).Text
IMHO it would be better to set the range over which you loop so that the entire row is incorporated. Doing it within the loop is less efficient.
set myRange = rows(wholeselect).EntireRow
For Each oCell In myRange
...

Resources