简体   繁体   中英

How to open text files and move them to a folder using VBA?

I need some help with a project in which I must open a list of text files, find a pattern in their contents and then move to other folders according to the pattern.

For example, in a list of text files, I must find which of them have the word "blue" written inside and them move only those to another folder named "Blue".

I was tring to do it using the command FileSystemObject, but I was kind of lost.

Thanks a lot in advance!!

Dim sDir As String
Dim sPath As String
Dim sPattern as String
Dim sReadedData as String
dim sDestiny as string
dim sPathDestiny as string
Dim fso As Object

Set fso = VBA.CreateObject("Scripting.FileSystemObject")

sPath$ = "c:\YourFolder"
sDir$ = Dir(sPath, vbDirectory)
sPattern= "abcdefg"
sDestiny="c:\DestinyFolder"

If sDir = "" Then
MsgBox "Path " & sDir & " Not Found"
End
End If
sDir$ = Dir(sPath & "\*.txt")
Do Until sDir = ""
     sPathDestiny=Replace(sDir, sPath, sDestiny)
     Open sDir$ For Input As #1
     do until EOF(1)   
         Input #1, sReadedData
     loop
     if InStr(sReadedData, sPattern)>0 then
         Call fso.CopyFile(sDir, sPathDestiny)
     end if
Loop

This is the main idea. Play with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM