VBA Code Finding number of items in an Array - vba

Is there a way to find the number of items in an array?
My list of txt files is:
C.txt
D.txt
G.txt
H.txt
With the code below I aggregated the txt files for have output only one txt file (output.txt).
But I need aggregate the files txt only when all four txt files are presents in the path of server else I need alert message in the code.
Can you help me?
Thank you in advance.
Option Compare Database
Dim path
Function go()
Dim ArrTest() As Variant
Dim I As Integer
Dim StrFileName As String
path = CurrentProject.Path
Ouput:
ArrTest = Array("C", "D", "G", "H")
file_global = "" & path & "\Output.txt"
fn = FreeFile
Open file_global For Output As fn
Close
For I = 0 To UBound(ArrTest)
StrFileName = "" & path & "\Output_" & ArrTest(I) & ".txt"
fn = FreeFile
Open StrFileName For Input As fn
Open file_global For Append As fn + 1
Line Input #fn, datum
Do While Not EOF(fn)
Line Input #fn, datum
datums = Split(datum, Chr(9))
For d = 0 To UBound(datums)
If d = 0 Then
datum = Trim(datums(d))
Else
datum = datum & ";" & Trim(datums(d))
End If
Next
Print #fn + 1, datum
Loop
Close
Next I
Application.Quit
End Function

Try this (different than your method, but tried and tested, Assuming All text files including calling workbook reside in same folder) :
Option Explicit
Private Sub AppendTxtfilesConditional()
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim path As String, xp, J As Integer, I As Integer, K As Integer
Dim FSOStream As Object, FSOStream1 As Object, FSO As Object, fol As Object, fil As Object
Dim srcFile As Object, desFile As Object
Dim ArrTest() As Variant
ArrTest = Array("C", "D", "G", "H")
J = 0
path = ThisWorkbook.path
Set FSO = CreateObject("Scripting.FileSystemObject")
Set fol = FSO.GetFolder(path)
For I = 0 To UBound(ArrTest)
K = 0
For Each fil In fol.Files
If ArrTest(I) & ".txt" = fil.Name Then
MsgBox (ArrTest(I) & ".txt" & " is found")
J = J + 1
If J > UBound(ArrTest) Then GoTo L12
K = J
End If
Next
If K = 0 Then MsgBox ArrTest(I) & ".txt" & " not found"
Next
MsgBox "aborted"
GoTo final
L12:
For I = 0 To UBound(ArrTest)
Set srcFile = FSO.GetFile(path & "\" & ArrTest(I) & ".txt")
On Error GoTo erLabel
Set desFile = FSO.GetFile(path & "\Output.txt")
On Error GoTo 0
Set FSOStream = srcFile.OpenAsTextStream(iomode:=ForReading, Format:=TristateUseDefault)
Set FSOStream1 = desFile.OpenAsTextStream(iomode:=ForAppending, Format:=TristateUseDefault)
Do While Not FSOStream.AtEndOfStream
xp = FSOStream.ReadLine
FSOStream1.Write vbCrLf & xp ' vbCrLf & xp or 'xp & vbCrLf
Loop
FSOStream.Close
FSOStream1.Close
Next
erLabel:
If Err.Number = 53 Then
MsgBox "Aborted : destination file not found"
GoTo final
End If
final:
Set FSOStream = Nothing: Set FSOStream1 = Nothing: Set FSO = Nothing: Set fol = Nothing
Set fil = Nothing: Set srcFile = Nothing: Set desFile = Nothing
End Sub
N.B If works for you then mark as answer else comment end if

Related

Parse and format text file

I have a text file that is not in a format that I can use for printing labels. The current format is like this:
DY234-02 0.5 0.5 Qty 6
U21 U12 U14 U28
TR459-09 0.5 0.5 Qty 9
U11 U78 U7 U8 U30 U24
I need the file to end up like this:
DY234-02 0.5 0.5 Qty 6 U21 U12 U14 U28
TR459-09 0.5 0.5 Qty 9 U11 U78 U7 U8 U30 U24
The files contain about 100 lines of this format I have used vbscript to try to get what I need but the format is not much different. If someone could get me pointed in the right direction that would be great. I am open to all other methods for accomplishing this. Thanks
This is my code in vbscript, but is not doing the job correctly:
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Scripts\parse.txt", ForReading)
Do Until objFile.AtEndOfStream
strLine1 = objFile.ReadLine
strLine2 = ""
If Not objFile.AtEndOfStream Then
strLine2 = objFile.ReadLine
End If
strNewLine = strLine1 & strLine2
strNewContents = strNewContents & strNewLine & vbCrLf
Loop
objFile.Close
Set objFile = objFSO.OpenTextFile("C:\Scripts\B3.txt", ForWriting, True)
objFile.Write strNewContents
objFile.Close
If the format is repeated like this, you can read in the text file line by line, and check if there is data on each line. If so join the data to an output string, otherwise add a carriage return to the output string, before finally outputting it to a new text file. Something like this perhaps:
Dim strInFile As String
Dim strOutFile As String
Dim intInFile As Integer
Dim intOutFile As Integer
Dim strInput As String
Dim strOutput As String
strInFile = "J:\downloads\data-in.txt"
strOutFile = "J:\downloads\data-out.txt"
intInFile = FreeFile
Open strInFile For Input As intInFile
intOutFile = FreeFile
Open strOutFile For Output As intOutFile
Do
Line Input #intInFile, strInput
If Len(Trim(strInput)) > 0 Then
strOutput = strOutput & " " & strInput
Else
strOutput = strOutput & vbCrLf
End If
Loop Until EOF(intInFile)
Print #intOutFile, strOutput
Reset
Regards,
Try next code, please. It is fast due to the fact it reads all the text value at once and drop the result, also at once. Everything is happening in memory.
Sub testSplitTextFile()
Dim objFSO As Object, objTF As Object, strIn As String, fullFilename As String, retFile As String
Dim arrIn As Variant, strRet As String, i As Long
'use here your path
fullFilename = "C:\Teste VBA Excel\Teste StackOverflow\TestSplit.txt"
retFile = "C:\Teste VBA Excel\Teste StackOverflow\RetFile.txt"'your path
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTF = objFSO.OpenTextFile(fullFilename, 1)
strIn = objTF.ReadAll 'it reads all the txt file string
objTF.Close
arrIn = Split(strIn, vbCrLf) 'it splits the above string on lines
'Then, it builds a string based on your conditions:
For i = 0 To UBound(arrIn) - 1
If arrIn(i) <> "" And arrIn(i + 1) <> "" Then
strRet = strRet & arrIn(i) & " " & arrIn(i + 1) & vbCrLf
End If
Next i
strRet = left(strRet, Len(strRet) - 1)' it eliminates the last vbCrLf character
FreeFile 1
Open retFile For Output As #1
Print #1, strRet 'it drops, at once the created string
Close #1
End Sub

Rename all files in a folder using excel vba

I want to replace anything before an underscore and prefix underscore with an increasing integer i in excel vba to rename all the files in a folder.
Sub RenameFiles()
Const FolderLoc = "P:\yourfolder\"
Dim x As Long
x = 1
Dim s As String
s = Dir(FolderLoc & "*.*")
Do While s <> ""
Name FolderLoc & s As FolderLoc & x & Right(s, Len(s) - (InStr(s, "_") - 1))
s = Dir()
x = x + 1
Loop
End Sub
'MACRO to Rename backed up files and place in order
Sub Rename2()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object, abc As Object
Dim i As String
Dim s As String, dest As String
dest = "H:\Automation\outputs\"
Set objFSO = CreateObject("Scripting.FileSystemObject")
FolderLoc = dest
Set objFolder = objFSO.GetFolder(dest)
'MsgBox objFolder
i = 1
s = Dir(FolderLoc & "*.*")
On Error Resume Next
'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
Do While (InStr(s, "_")) > 0
'MsgBox s
'Name OldFile as NewFile
Name FolderLoc & s As FolderLoc & i & "." & Right(s, Len(s) - (InStr(s, "_") + 2))
s = i & "." & Right(s, Len(s) - (InStr(s, "_") + 2))
'MsgBox s
'abc = Name FolderLoc & s As FolderLoc & "(" & i & ")" & Right(s, Len(s) - (InStr(s, "#_#") + 2))
'i = i + 1
Loop
i = i + 1
s = Dir()
Next objFile
End Sub

How to rename multiple pdf files used excel database vba

Thanks in advance for your help and comments.
I have the following problem, but I do not know if it is possible ... I am trying to rename PDF files that are in the folder C: \ ... I need to rename according to a worksheet that I have in excel that is ordered according to the pdf files .. I would like to rename with the spreadsheet data in excel?
I have a code that I researched but it does not search my database, but it asks me to enter the name of each file
Public Sub lsSelecionaArquivo()
Dim Caminho As String
Dim NomeBase As String
Caminho = InputBox("Informe o local dos arquivos a serem renomeados:", "Pasta", "C:\TEMP")
NomeBase = InputBox("Informe o local dos arquivos a serem renomeados:", "Renomear", "")
lsRenomearArquivos Caminho, NomeBase
End Sub
Public Sub lsRenomearArquivos(Caminho As String, NomeBase As String)
Dim FSO As Object, Pasta As Object, Arquivo As Object, Arquivos As Object
Dim Linha As Long
Dim lSeq As Long
Dim lNovoNome As String
Set FSO = CreateObject("Scripting.FileSystemObject")
If Not FSO.FolderExists(Caminho) Then
MsgBox "A pasta '" & Caminho & "' não existe.", vbCritical, "Erro"
Exit Sub
End If
lSeq = 1
Set Pasta = FSO.GetFolder(Caminho)
Set Arquivos = Pasta.Files
Cells(1, 1) = "De"
Cells(1, 2) = "Para"
Linha = 2
For Each Arquivo In Arquivos
Cells(Linha, 1) = UCase$(Arquivo.Path)
lNovoNome = Caminho & "\" & NomeBase & lSeq & Right(Arquivo, 4)
Name Arquivo.Path As lNovoNome
Cells(Linha, 2) = lNovoNome
lSeq = lSeq + 1
Linha = Linha + 1
Next
End Sub
For the renaming part, consider this.
Sub RenameFiles()
'Updateby20141124
Dim xDir As String
Dim xFile As String
Dim xRow As Long
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show = -1 Then
xDir = .SelectedItems(1)
xFile = Dir(xDir & Application.PathSeparator & "*")
Do Until xFile = ""
xRow = 0
On Error Resume Next
xRow = Application.Match(xFile, Range("A:A"), 0)
If xRow > 0 Then
Name xDir & Application.PathSeparator & xFile As _
xDir & Application.PathSeparator & Cells(xRow, "B").Value
End If
xFile = Dir
Loop
End If
End With
End Sub
https://www.extendoffice.com/documents/excel/2339-excel-rename-files-in-a-folder.html
Also, consider this.
Sub ListFiles()
Dim MyFolder As String
Dim MyFile As String
Dim j As Integer
MyFolder = "C:\DealerExam"
MyFile = Dir(MyFolder & "\*.*")
a = 0
Do While MyFile <> ""
a = a + 1
Cells(a, 1).Value = MyFile
MyFile = Dir
Loop
End Sub
This will list all the files in your directory starting in cell 'A1'
Thanks for the help
It is a bit tense to change language since I study Java and started doing VBA.
When I ran the code, I saw that it is necessary for the spreadsheet to have the old file name and the new one to insert the data, but there is no way to get it to just get the new data? And I've tried searching on how to make them as PDF without having to put the file extension in the worksheet.
Sorry for the questions ... I do not have much contact with VBA.
I thank you very much for helping me.
Sub RenameFiles()
Dim xDir As String
Dim xFile As String
Dim xRow As Long
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show = -1 Then
xDir = .SelectedItems(1)
xFile = Dir(xDir & Application.PathSeparator & "*")
Do Until xFile = ""
xRow = 0
On Error Resume Next
xRow = Application.Match(xFile, Range("A:A"), 0)
If xRow > 0 Then
Name xDir & Application.PathSeparator & xFile As _
xDir & Application.PathSeparator & Cells(xRow, "B").Value
End If
xFile = Dir
Loop
End If
End With
End Sub
Sub ListFiles()
Dim MyFolder As String
Dim MyFile As String
Dim j As Integer
MyFolder = "C:\Users\AnaWill\Desktop\Holerites Folha\Nova pasta"
MyFile = Dir(MyFolder & "\*.*")
a = 0
Do While MyFile <> ""
a = a + 1
Cells(a, 2).Value = MyFile
MyFile = Dir
Loop
End Sub

Change File Names within Subfolders with VBA

I am trying to upload a few hundred folders each with files inside of them into SharePoint, but unfortunately SharePoint doesn't allow any special characters like "%".
I'm trying to use a VBA code that can automatically go into each subfolder and replace any special characters contained within the files such as "%", "#", etc.
So far what I have is:
Sub ChangeFileName()
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set Folder = objFSO.GetFolder("C:\Users\Documents\TEST\Subfolder")
'Currently the way I have it requires me to change my path a few hundred times
For Each File In Folder.Files
sNewFile = File.Name
sNewFile = Replace(sNewFile, "%", "_")
sNewFile = Replace(sNewFile, "#", "_")
'^and so on`
If (sNewFile <> File.Name) Then
File.Move (File.ParentFolder + "\" + sNewFile)
End If
Next
End Sub
However for the script above, you need the specific sub-folder path. Wondering if there's any way to automatically replace the special characters of files within subfolders. I can also paste all the specific subfolder paths into column A of my Excel worksheet if that helps.
Thank you!
I use this code
Sub GetFileFromFolder()
Dim fd As FileDialog
Dim strFolder As String
Dim colResult As Collection
Dim i As Long, k As Long
Dim vSplit
Dim strFn As String
Dim vR() As String
Dim p As String
Dim iLevel As Integer, cnt As Long
'iLevel = InputBox(" Subfolder step : ex) 2 ")
p = Application.PathSeparator
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
With fd
.Show
.InitialView = msoFileDialogViewList
.Title = "Select your Root folder"
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then
Else
strFolder = .SelectedItems(1)
Set colResult = SearchFolder(strFolder)
i = colResult.Count
For k = 1 To i
vSplit = Split(colResult(k), p)
strFn = vSplit(UBound(vSplit))
strFn = Replace(strFn, "%", "_")
strFn = Replace(strFn, "#", "_")
'If UBound(vSplit) - UBound(Split(strFolder, p)) = iLevel Then
cnt = cnt + 1
ReDim Preserve vR(1 To 3, 1 To cnt)
On Error Resume Next
Err.Clear
Name colResult(k) As strFolder & strFn
vR(1, cnt) = colResult(k)
If Err.Number = 58 Then
strFn = Split(strFn, ".")(0) & "_" & vSplit(UBound(vSplit) - 1) & "_" & Date & "." & Split(strFn, ".")(1)
Name colResult(k) As strFolder & strFn
vR(2, cnt) = strFolder & strFn
vR(3, cnt) = "Changed name " 'When filename is duplicated chage filename
Else
vR(2, cnt) = strFolder & strFn
End If
' End If
Next k
ActiveSheet.UsedRange.Offset(1).Clear
Range("a3").Resize(1, 3) = Array("Old file", "New file", "Ect")
If cnt > 0 Then
Range("a4").Resize(cnt, 3) = WorksheetFunction.Transpose(vR)
End If
With ActiveSheet.UsedRange
.Borders.LineStyle = xlContinuous
.Columns.AutoFit
.Font.Size = 9
End With
End If
End With
MsgBox cnt & " files moved!! "
End Sub
Function SearchFolder(strRoot As String)
Dim FS As Object
Dim fsFD As Object
Dim f As Object
Dim colFile As Collection
Dim p As String
On Error Resume Next
p = Application.PathSeparator
If Right(strRoot, 1) = p Then
Else
strRoot = strRoot & p
End If
Set FS = CreateObject("Scripting.FileSystemObject")
Set fsFD = FS.GetFolder(strRoot)
Set colFile = New Collection
For Each f In fsFD.Files
colFile.Add f.Path
Next f
SearchSubfolder colFile, fsFD
Set SearchFolder = colFile
Set fsFD = Nothing
Set FS = Nothing
Set colFile = Nothing
End Function
Sub SearchSubfolder(colFile As Collection, objFolder As Object)
Dim sbFolder As Object
Dim f As Object
For Each sbFolder In objFolder.subfolders
SearchSubfolder colFile, sbFolder
For Each f In sbFolder.Files
colFile.Add f.Path
Next f
Next sbFolder
End Sub

I want to merge all txt files to 1 txt files, but i get an error if a file is empty [duplicate]

This question already has an answer here:
VBscript error input past end of file
(1 answer)
Closed 5 years ago.
If i run it 1 time it works,the second time i runit the 2nd txt file is empty so the script stops running on this line:
strTxt = strTxt & txt.ReadAll
How can I solve it, that it doesn't stop if a file is empty?
Sub MergeTxtFiles()
Dim fso As Object, txt As Object, strTxt As String
Dim strParentFldr As String, strFile As String
Dim iFreeFile As Integer, strOutPutFile As String
KillProperly "D:\users\gf05856\Documents\TEst\RVA002ALL.txt"
Call DeleteLine1
Call DeleteLine2
strOutPutFile = "D:\users\gf05856\Documents\TEst\RVA002ALL.txt"
strParentFldr = "D:\users\gf05856\Documents\TEst"
Set fso = CreateObject("Scripting.FileSystemObject")
strFile = Dir(strParentFldr & "\Register van aankomst 002*.txt")
If Len(strFile) > 0 Then
Do
Set txt = fso.OpenTextFile(strParentFldr & "\" & strFile)
strTxt = strTxt & txt.ReadAll
strFile = Dir
Loop Until Len(strFile) = 0
If Left(strTxt, 2) = vbCrLf Then strTxt = Mid(strTxt, 2)
End If
iFreeFile = FreeFile
Open strOutPutFile For Output As #iFreeFile
Print #iFreeFile, strTxt
Close #iFreeFile
Set txt = Nothing
Set fso = Nothing
End Sub
Public Sub KillProperly(Killfile As String)
If Len(Dir$(Killfile)) > 0 Then
SetAttr Killfile, vbNormal
Kill Killfile
End If
End Sub
Sub DeleteLine1()
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("D:\users\gf05856\Documents\TEst\Register van aankomst 002 - D (Histo).txt", ForReading)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If InStr(strLine, "CLIFOUPAYCODE") = 0 Then
strNewContents = strNewContents & strLine & vbCrLf
End If
Loop
objFile.Close
Set objFile = objFSO.OpenTextFile("D:\users\gf05856\Documents\TEst\Register van aankomst 002 - D (Histo).txt", ForWriting)
objFile.Write strNewContents
objFile.Close
End Sub
Sub DeleteLine2()
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("D:\users\gf05856\Documents\TEst\Register van aankomst 002 - D.txt", ForReading)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If InStr(strLine, "CLIFOUPAYCODE") = 0 Then
strNewContents = strNewContents & strLine & vbCrLf
End If
Loop
objFile.Close
Set objFile = objFSO.OpenTextFile("D:\users\gf05856\Documents\TEst\Register van aankomst 002 - D.txt", ForWriting)
objFile.Write strNewContents
objFile.Close
End Sub
.ReadAll() fails on empty/zero length/size files:
>> WScript.Echo oFS.GetFile("x").Size
>> Set f = oFS.OpenTextFile("x")
>> s = f.ReadAll()
>>
0
Error Number: 62
Error Description: Eingabe hinter Dateiende.
>>
So you should check the .Size to determine whether the file should be opened at all.
(BTW: What's the real world problem you try to solve?)