im trying to get file name with csv extension , but when i try to debug.print it always print the .csv file and the .txt file
im search the file in the folder and subfolder
heres the code
Sub LoopAllSubFolders(ByVal folderPath As String)
Dim fileName As String
Dim fullFilePath As String
Dim numFolders As Long
Dim folders() As String
Dim i As Long
If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
fileName = Dir(folderPath & "*.*", vbDirectory)
While Len(fileName) <> 0
If Left(fileName, 1) <> "." Then
fullFilePath = folderPath & fileName
If (GetAttr(fullFilePath) And vbDirectory And Not (fullFilePath Like "*csv*")) = vbDirectory Then
ReDim Preserve folders(0 To numFolders) As String
folders(numFolders) = fullFilePath
numFolders = numFolders + 1
Else
'Insert the actions to be performed on each file
'This example will print the full file path to the immediate window
Debug.Print folderPath & fileName
End If
End If
fileName = Dir()
Wend
For i = 0 To numFolders - 1
LoopAllSubFolders folders(i)
Next i
End Sub
The code i get from website and i add not like "*csv*"
perhaps someone can correcting the code,
thankyou
You can use Dir(folderPath & "*.csv") to find all csv files in folderPath.
If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
fileName = Dir(folderPath & "*.csv")
While Len(fileName) <> 0
If Left(fileName, 1) <> "." Then
fullFilePath = folderPath & fileName
ReDim Preserve folders(0 To numFolders) As String
folders(numFolders) = fullFilePath
numFolders = numFolders + 1
End If
fileName = Dir()
Wend
new edition: use FileSystemObject
Use FileSystemObject to get names of subfolders then get all csv files in each subfolder
Dim fso as object, mainFolder as object, subFolder as object, file
set fso = createobject("Scripting.FileSystemObject")
if fso.FolderExists("folderPath") Then
set mainFolder = fso.getfolder("folderPath")
else
exit sub
end if
for each subFolder in mainFolder.subfolders
for each file in subFolder.Files
if file.name like "*.csv" then
ReDim Preserve folders(0 To numFolders) As String
folders(numFolders) = file
numFolders = numFolders + 1
end if
next file
next subFolder
My suggestion:
fullFilePath = folderPath & fileName
If (GetAttr(fullFilePath) And vbDirectory) = vbDirectory Then
ReDim Preserve folders(0 To numFolders) As String
folders(numFolders) = fullFilePath
numFolders = numFolders + 1
Else
If Right(fileName, 4) = ".csv" Then 'new line
'Insert the actions to be performed on each file
'This example will print the full file path to the immediate window
Debug.Print folderPath & fileName
End If
Related
I am trying to rename my folder files. However, every time I try to run the below script, I see an error:
can’t find project or library on Sub and set FSO
How can I fix it?
Sub renameFiles()
'
' renamefiles Macro
'
Dim folderpath As String
Dim file_name As String
Dim target_folder As String
Dim trim_file_name As String
Set fso = CreateObject("Scripting.FileSystemObject")
folderpath = ThisWorkbook.Sheets("File Converter").Range("C7").Value & "\"
newFileName = Range("").Value
fileCount = 0
filePath = Dir$(folderpath & "*.*")
Do While filePath <> ""
fileCount = fileCount + 1
fileNames = fileNames & filePath & "," & newFileName & CStr(fileCount) & "." &
fso.GetExtensionName(filePath) & ","
filePath = Dir$
Loop
Dim renameFiles() As String
renameFiles = Split(fileNames, ",")
For fileCount = 0 To UBound(renameFiles) - 2 Step 2
Name folderpath & renameFiles(fileCount) As folderpath & renameFiles(fileCount + 1)
Next
End Sub
Good Morning,
I have some code that is doing the basis of what I want, BUT I just need to take it one step further for it to work perfectly. Currently I'm pulling every file in the folders and subfolders which is proper, but now I need to select only files that have a particular version label: "v5.3.xlsx" so I can open them, make adjustments and close. I've tried every version of a wild card search I can think of but I'm not terribly well versed in VBA so I was hoping someone could kick this over the finish line for me. Any help is very much appreciated!
Sub loopAllSubFolderSelectStartDirectory()
'Another Macro must call LoopAllSubFolders Macro to start to procedure
Call LoopAllSubFolders("C:\Users\smith\Desktop\Excel Test File\Client\")
End Sub
'List all files in sub folders
Sub LoopAllSubFolders(ByVal folderPath As String)
Dim fileName As String
Dim myFile As String
Dim fullFilePath As String
Dim numFolders As Long
Dim folders() As String
Dim i As Long
Application.ScreenUpdating = False
If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
fileName = Dir(folderPath & ".", vbDirectory)
While Len(fileName) <> 0
If Left(fileName, 1) <> "." Then
fullFilePath = folderPath & fileName
If (GetAttr(fullFilePath) And vbDirectory) = vbDirectory Then
ReDim Preserve folders(0 To numFolders) As String
folders(numFolders) = fullFilePath
numFolders = numFolders + 1
Else
'Insert the actions to be performed on each file
'This example will print the full file path to the immediate window
Debug.Print fullFilePath
End If
End If
fileName = Dir()
Wend
For i = 0 To numFolders - 1
LoopAllSubFolders folders(i)
Next i
Application.ScreenUpdating = True
End Sub
I have the following module to check the number of files contained in a folder and display a messagebox with the with the number of files:
Sub CheckFiles(strDir As String, strType As String)
Dim file As Variant, i As Integer
strDir = ThisWorkbook.Path & "\Source\"
If Right(strDir, 1) <> "\" Then strDir = strDir & "\"
file = Dir(strDir & strType)
While (file <> "")
i = i + 1
file = Dir
Wend
MsgBox i
End Sub
Files to look for (in separate module):
Call CheckFiles("", "File1*.xlsx")
Call CheckFiles("", "File2*.xlsx")
What I want to do is to only display messagebox if the number of files for File1 is not excaly 3 and the number of files for File2 is not excaly 2. This is what I'm having trouble doing? How can this be acheived?
Add the ChckNum as Third Parameter in the Subject and pass it in the Call Statement
Try:
Sub CheckFiles(strDir As String, strType As String, chknum As Integer)
Dim file As Variant, i As Integer
strDir = ThisWorkbook.path & "\Source\"
If Right(strDir, 1) <> "\" Then strDir = strDir & "\"
file = Dir(strDir & strType)
While (file <> "")
i = i + 1
file = Dir
Wend
If i <> chknum Then MsgBox i
End Sub
And
Call CheckFiles("", "File1*.xlsx", 3)
Call CheckFiles("", "File2*.xlsx", 2)
I need to rename 300+ files of various extensions in 1 folder. I have a list of file names without extension in column B, and final names in column A of my Excel worksheet. My code works, but renames files in wrong order. Filenames contain dots, like
А1.14.12.2016
Here is the code:
Option Explicit
Sub test2()
Dim x As String
Dim fName As String
Dim oldPath As String
Dim newPath As String
Dim i As Long
oldPath = "\\Plu20\dfs01\USMiKAR\docs\"
newPath = oldPath & "New\"
On Error Resume Next
x = GetAttr(newPath) And 0
If Err.Number <> 0 Then MkDir newPath
fName = Dir(oldPath & "*.*")
With ActiveSheet
Do While Len(fName) > 0
i = i + 1
FileCopy oldPath & fName, newPath & .Cells(i, 1) & Mid$(fName, InStrRev(fName, "."))
'.Cells(i, 2) = oldPath & fName 'ïðîâåðêà
'Kill oldPath & fName 'óäàëåíèå ñòàðûõ
fName = Dir
Loop
End With
End Sub
Untested, but you can do something like this:
Sub test2()
Dim x As String
Dim fName As String
Dim oldPath As String
Dim newPath As String
Dim i As Long
Dim fso As Object, f As Range
Set fso = CreateObject("scripting.filesystemobject")
oldPath = "\\Plu20\dfs01\USMiKAR\docs\"
newPath = oldPath & "New\"
If Dir(newPath, vbDirectory) = "" Then MkDir newPath
fName = Dir(oldPath & "*.*")
With ActiveSheet
Do While Len(fName) > 0
'find the current filename
Set f = .Columns(2).Find(fso.getbasename(fName), lookat:=xlWhole)
If Not f Is Nothing Then
'got a match
FileCopy oldPath & fName, _
newPath & f.Offset(0, -1).Value & "." & fso.getextensionname(fName)
'.Cells(i, 2) = oldPath & fName 'ïðîâåðêà
'Kill oldPath & fName 'óäàëåíèå ñòàðûõ
Else
'no match...
Debug.Print "filename:" & fName & " was not matched"
End If
fName = Dir
Loop
End With
End Sub
Sorry for my bad English :( I have a task - i should write a program in Excel VBA,that will in folder and subfolders find all .xml files, scan them and make changes if it necessary. Then program will save all changed files in the folder with name "Todays date_changed" and all non-changed files just transfer to the folder with name "Today date". In the end program should display message about how many files was changed and non-changed. I've already wrote code, that changed .xml file in the proper condition. Here it is:
Sub EditXML()
Dim doc As New DOMDocument
Const filePath As String = "D:\Test3.xml" 'path to the editing file
Dim isLoaded As Boolean
isLoaded = doc.Load(filePath)
If isLoaded Then
Dim oAttributes As MSXML2.IXMLDOMNodeList
Set oAttributes = doc.getElementsByTagName("Operation")
Dim attr As MSXML2.IXMLDOMAttribute
Dim node As MSXML2.IXMLDOMElement
Dim tdate As String
tdate = Format(Now(), "yyyy-mm-dd")
For Each node In oAttributes
If (node.getAttributeNode("Client") Is Nothing) Then
node.setAttribute "Client", "UL"
End If
For Each attr In node.Attributes
If attr.Name = "Client" Then
If attr.Value <> "UL" Then
attr.Value = "UL"
End If
ElseIf attr.Name = "Date" Then
If attr.Value <> "tdate" Then
attr.Value = tdate
End If
End If
Next attr
Next node
doc.Save filePath
End If
End Sub
Also i wrote a code, that in theory should pick all .xml files in the selected folder, editing them and then save to specific folder, but it doesn't do anything-it compiles, doing something, but saves nothing. Here it is:
Sub EditXML()
Dim MyFolder As String
Dim MyFile As String
Dim oDoc As MSXML2.DOMDocument
Dim doc As New DOMDocument
On Error Resume Next
Application.ScreenUpdating = False
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Choose a folder"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then
Exit Sub
End If
MyFolder = .SelectedItems(1) & "\"
End With
MyFile = Dir(MyFolder & "*.xml")
Do While MyFile <> ""
oDoc.Load (MyFolder & MyFile)
Dim oAttributes As MSXML2.IXMLDOMNodeList
Set oAttributes = doc.getElementsByTagName("Operation")
Dim attr As MSXML2.IXMLDOMAttribute
Dim node As MSXML2.IXMLDOMElement
Dim tdate As String
tdate = Format(Now(), "yyyy-mm-dd")
For Each node In oAttributes
If (node.getAttributeNode("Client") Is Nothing) Then
node.setAttribute "Client", "UL"
End If
For Each attr In node.Attributes
If attr.Name = "Client" Then
If attr.Value <> "UL" Then
attr.Value = "UL"
End If
ElseIf attr.Name = "Date" Then
If attr.Value <> "tdate" Then
attr.Value = tdate
End If
End If
Next attr
Next node
doc.Save "D:\Test\Output\*.xml"
MyFile = Dir
Loop
Application.ScreenUpdating = True
End Sub
So, at conclusion, i asking for help in writing this program, because this is my first try to write something in VBA. I need parts of code, that will scaning for xml in folders and subfolders, editing them as i mentioned up here and saving the to a proper folder (depending on whether they were changed or not), as i describe in the begining and messaging about working. Here is an example of xml files with which i working:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document>
<Operations>
<Operation Date="2018-11-06" Client="UL"/>
<Operation Date="2018-11-06" Client="UL"/>
<Operation Date="2018-11-06"/>
</Operations>
</Document>
Thank you very much for your help :)
Wow. You are trying to do A LOT of things here. Let's start with a couple items, make sure you get that working, and then build out additional features over time. For starters, you can edit all XML files in a folder in this way.
Sub ReplaceStringInFile()
Const sSearchString As String = "c:\your_path_here\*.xml"
Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String
Dim sFilePath As String
sFileName = Dir(sSearchString)
Do While sFileName <> ""
sFilePath = "c:\temp\" & sFileName 'Get full path to file
iFileNum = FreeFile
sTemp = "" 'Clear sTemp
Open sFilePath For Input As iFileNum
Do Until EOF(iFileNum)
Line Input #iFileNum, sBuf
sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum
sTemp = Replace(sTemp, "THIS", "THAT")
iFileNum = FreeFile
Open sFilePath For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum
sFileName = Dir() 'Get the next file
Loop
End Sub
Now, that goes into a single folder to look for XML files, but you said you want to go through all folders and all sub-folders in a directory, right, so you have a recursively loop through this 'list' of folders. You can use the code below to do that.
Sub loopAllSubFolderSelectStartDirector()
'Another Macro must call LoopAllSubFolders Macro to start to procedure
Call LoopAllSubFolders("C:\your_path_here\")
End Sub
'List all files in sub folders
Sub LoopAllSubFolders(ByVal folderPath As String)
Dim fileName As String
Dim fullFilePath As String
Dim numFolders As Long
Dim folders() As String
Dim i As Long
If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
fileName = Dir(folderPath & "*.*", vbDirectory)
While Len(fileName) <> 0
If Left(fileName, 1) <> "." Then
fullFilePath = folderPath & fileName
If (GetAttr(fullFilePath) And vbDirectory) = vbDirectory Then
ReDim Preserve folders(0 To numFolders) As String
folders(numFolders) = fullFilePath
numFolders = numFolders + 1
Else
'Insert the actions to be performed on each file
'This example will print the full file path to the immediate window
Debug.Print folderPath & fileName
End If
End If
fileName = Dir()
Wend
For i = 0 To numFolders - 1
LoopAllSubFolders folders(i)
Next i
End Sub