I take a bunch of .CSV files from a server, open them and save them to another server as .XLSX. My issue is with:
'Get the folder object associated with the directory
Set objPickup = objFSO.GetFolder(pickUp)
Set objDropoff = objFSO.GetFolder(Dropoff)
I keep getting an error and i'm guessing it's because I am pulling in an array pickUp.
Sub ListfilesAndMove()
'List all files in selected folder
Dim objFSO As Object, objPickup As Object, objDropoff As Object, objFile As Object
Dim wb As Workbook, Dropoff As String, pickUp As Variant
Dim LastRowMonthly46 As Long, b As Long, c As Long
Dim ADay As Integer, AMonth As Integer, AYear As Integer, myDate As Date
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim ws As Worksheet: Set ws = ActiveSheet
Dim B3 As Range: Set B3 = ws.Range("B3")
Dim B26 As Range: Set B26 = ws.Range("B26")
Worksheets("Menu").Activate 'Go to worksheet Menu
'Make variable Pickup equal to value of B3
With Application
pickUp = .Transpose(ws.Range(B3, B26))
End With
Dim i As Long
For i = LBound(pickUp) To UBound(pickUp)
Debug.Print pickUp(i)
Next i
Dropoff = ActiveSheet.Range("B28").Value
Worksheets("Report").Activate 'Go to worksheet Report
Worksheets("Report").Visible = True
Worksheets("Menu").Visible = False
'Get the folder object associated with the directory
Set objPickup = objFSO.GetFolder(pickUp)
Set objDropoff = objFSO.GetFolder(Dropoff)
'Set values for cells A1,B1 and C1 and align text
Worksheets("Report").Range("A1").Value = "The files found in " & objPickup.Name & " are:"
Worksheets("Report").Range("A1").VerticalAlignment = xlCenter
Worksheets("Report").Range("A1").HorizontalAlignment = xlLeft
Worksheets("Report").Range("B1").Value = "Processed Yes/No"
Worksheets("Report").Range("B1").HorizontalAlignment = xlCenter
Worksheets("Report").Range("C1").Value = "New File Location"
Worksheets("Report").Range("C1").VerticalAlignment = xlCenter
Worksheets("Report").Range("C1").HorizontalAlignment = xlLeft
'Loop through the Files collection
Application.DisplayAlerts = False
For Each objFile In objPickup.Files
Worksheets("Report").Cells(Worksheets("Report").UsedRange.Rows.Count + 1, 1).Value = objFile.Name
'Open and Save File
Dim Filename As String
Filename = objFile
If Right(Filename, 4) = ".csv" Then
Application.ScreenUpdating = False
Set wb = Application.Workbooks.Open(Filename)
File_name = ActiveWorkbook.Name
File_name2 = ActiveWorkbook.Name
FileLength = Len(File_name2)
File_name2 = Left(File_name2, FileLength - 4)
ActiveWorkbook.ActiveSheet.Name = "Sheet1" 'Rename sheet
With wb 'Save File
'save file to dropoff location
.SaveAs (objDropoff & "\" & File_name2 & ".xlsx"), FileFormat:=xlOpenXMLWorkbook, ConflictResolution:=xlLocalSessionChanges
.Close SaveChanges:=False 'close file
End With
Dim FSO As Object
Set FSO = CreateObject("scripting.filesystemobject")
'Add Processed Comment
Worksheets("Report").Cells(Worksheets("Report").UsedRange.Rows.Count, 2).Value = "Yes"
'Add location of new File
Worksheets("Report").Cells(Worksheets("Report").UsedRange.Rows.Count, 3).Value = objDropoff
Else
Worksheets("Report").Cells(Worksheets("Report").UsedRange.Rows.Count, 2).Value = "No"
End If
Next
Application.DisplayAlerts = True
'Apply wrap text to B1
Worksheets("Report").Range("B1").WrapText = True
Worksheets("Report").Columns("A:C").AutoFit
'Clean up!
Set objPickup = Nothing
Set objDropoff = Nothing
Set objFile = Nothing
Set objFSO = Nothing
End Sub
I'm not sure why all that code is necessary; based on the explanation of what you need to do, you should only need to run two lines of code for each file:
one to open the .CSV:
Workbooks.OpenText "C:\yourPath\yourFile.csv", 65001, 1, , , , True
and one to save as .XLSX:
ActiveWorkbook.SaveAs "C:\yourPath\yourFile.xlsx", xlOpenXMLWorkbook
I don't memorize syntax for rarely used commands like this; instead I let Excel write the code for me using the Macro Recorder. I do the task once and then clean up the code that Excel generates (which resulted in the examples above).
More Information:
MSDN : Workbooks.OpenText Method
MSDN : Workbook.SaveAs Method
MSDN : Recording a Macro to Generate Code
MSDN : Revising Recorded VBA Macros
Related
First time I ask a question here, but so far answers from this forum have always helped me a lot. However, now I have been dealing with a problem for weeks and unfortunately never found sufficient answers.
The current task is to update an already existing macro regarding data processing and display to a newer UI and increased usability. However, in the same sense I would like to improve the speed of the macro.
My current problem is opening, loading, splitting and pasting multiple selected .txt files into appropriately named sheets. The files can very quickly have over a hundred thousand entries of data, all separated by either space or enter. For importing and splitting a single file, I stumbled across this code, which I have subsequently adapted for my circumstances:
Private Sub testModule1()
Dim arr, tmp, output
Dim Datei
Dim FSO
Dim x, y As Integer
Dim str_string, filePath As String
Set FSO = CreateObject("Scripting.FilesystemObject")
filePath = Application.GetOpenFilename
Set Datei = FSO.OpentextFile(filePath)
str_string = Datei.readall
Datei.Close
arr = Split(str_string, vbCrLf)
ReDim output(UBound(arr), 50)
For x = 0 To UBound(arr)
tmp = Split(arr(x), " ")
For y = 0 To UBound(tmp)
output(x, y) = tmp(y)
Next
Next
Sheets("Sheet1").Range("A1").Resize(UBound(output) + 1, UBound(output, 2)) = output
End Sub
This part lets me select a single file, splits the cells as desired, and finally posts it to the first sheet.
For importing multiple files and naming the sheet after the file name, I found code here (the first solution):
https://www.mrexcel.com/board/threads/importing-multiple-text-files-in-to-multiple-work-sheets-with-text-file-names.1147363/
However, it currently opens in a new workbook, Windows tells me several times that data is overwritten when I do this, and the delimiter is also limited to only one character.
I am currently failing to find a reasonable combination of these two actions. The direct opening and reasonable splitting of several selected files and the subsequent integrating into several sheets named accordingly by file name.
In the old version of the macro, all file paths were first retrieved and stored in cells for this purpose, and later looped through these cells while reading and integrating the individual data in the process. However, everything in a sheet and rather, as I find, cumbersome.
I hope to find a more elegant solution for this problem than having to store data in sheets during editing and I am also happy about other suggestions and solutions.
EDIT:
After the hint from Solar Mike I was able to adapt the code to this:
Private Sub testModule2()
Dim fDialog As FileDialog
Dim fPath As Variant
Dim FSO
Dim Datei
Dim arr, tmp, output
Dim file, fileName As String
Dim x, y As Integer
Dim newSht As Worksheet
Application.ScreenUpdating = False
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.AllowMultiSelect = True
.Title = "Please select files to import"
.Filters.Clear
.Filters.Add "VBO Files", "*.vbo"
If .Show = True Then
For Each fPath In .SelectedItems
Set FSO = CreateObject("Scripting.FilesystemObject")
fileName = FSO.GetFilename(fPath)
Set Datei = FSO.OpentextFile(fPath)
file = Datei.readall
Datei.Close
arr = Split(file, vbCrLf)
ReDim output(UBound(arr), 50)
For x = 0 To UBound(arr)
tmp = Split(arr(x), " ")
For y = 0 To UBound(tmp)
output(x, y) = tmp(y)
Next
Next
Set newSht = ActiveWorkbook.Sheets.Add(after:=ActiveWorkbook.Worksheets(ActiveWorkbook.Worksheets.Count))
newSht.Name = fileName
Sheets(fileName).Range("A1").Resize(UBound(output) + 1, UBound(output, 2)) = output
Next
End If
End With
Application.ScreenUpdating = True
End Sub
This does what is actually required, but just importing only 5 files already takes about a minute. Since on average up to 20 files can/should be imported and the processing of the data still takes place afterwards, this still seems a bit much to me.
It should be noted that the data sets are reduced again during processing, something between 40 and 80% of the data are filtered. Unfortunately I don't have the expertise to do this before, even if this would reduce the loading time.
Does this do what you want?
Sub CombineTextFiles()
'updateby Extendoffice
Dim xFilesToOpen As Variant
Dim I As Integer
Dim xWb As Workbook
Dim xTempWb As Workbook
Dim xDelimiter As String
Dim xScreen As Boolean
On Error GoTo ErrHandler
xScreen = Application.ScreenUpdating
Application.ScreenUpdating = False
xDelimiter = "|"
xFilesToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "Kutools for Excel", , True)
If TypeName(xFilesToOpen) = "Boolean" Then
MsgBox "No files were selected", , "Kutools for Excel"
GoTo ExitHandler
End If
I = 1
Set xTempWb = Workbooks.Open(xFilesToOpen(I))
xTempWb.Sheets(1).Copy
Set xWb = Application.ActiveWorkbook
xTempWb.Close False
xWb.Worksheets(I).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
Do While I < UBound(xFilesToOpen)
I = I + 1
Set xTempWb = Workbooks.Open(xFilesToOpen(I))
With xWb
xTempWb.Sheets(1).Move after:=.Sheets(.Sheets.Count)
.Worksheets(I).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=xDelimiter
End With
Loop
ExitHandler:
Application.ScreenUpdating = xScreen
Set xWb = Nothing
Set xTempWb = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description, , "Kutools for Excel"
Resume ExitHandler
End Sub
Unfortunately, after a bit more trial and error with my edited code, I haven't found a better way to optimize the process, so I'm posting the final code in response to the question.
The reduction of the amount of data is now done by a third party program and speeds up the processing sufficiently.
Option Explicit
Public Sub fileImporter()
Dim fDialog As FileDialog
Dim fPath As Variant
Dim FSO
Dim Data
Dim arr, tmp, output
Dim file, fileName As String
Dim x, y As Integer
Dim newSht As Worksheet
Application.ScreenUpdating = False
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.AllowMultiSelect = True
.Title = "Please select files to import"
.Filters.Clear
.Filters.Add "VBO Files", "*.vbo" 'VBO Files are opened and handled like Text Files
If .Show = True Then
For Each fPath In .SelectedItems
Set FSO = CreateObject("Scripting.FilesystemObject")
fileName = FSO.GetFilename(fPath)
Set Data = FSO.OpentextFile(fPath)
file = Data.readall
Data.Close
arr = Split(file, vbCrLf)
ReDim output(UBound(arr), 50)
For x = 0 To UBound(arr)
tmp = Split(arr(x), " ")
For y = 0 To UBound(tmp)
output(x, y) = tmp(y)
Next
Next
Set newSht = ActiveWorkbook.Sheets.Add(after:=ActiveWorkbook.Worksheets(ActiveWorkbook.Worksheets.Count))
newSht.Name = fileName
Sheets(fileName).Range("A1").Resize(UBound(output) + 1, UBound(output, 2)) = output
Next
End If
End With
Application.ScreenUpdating = True
End Sub
Thanks for all the help and I hope this can help someone else too.
I have more than 50 files needed to create the pivot table and each file has the same exact formort with different contents. So far, I have finished creating the code for the pivot and it works very well when running alone, however, it failed when I tried to run the code for all workbooks in the same folder. I don't know what happened and why it kept showing that no files could be found despite nothing wrong about the pathname.
Sub DoAllFiles()
Dim Filename, Pathname As String
Dim WB As Workbook
Pathname = "D:\Reports"
Filename = Dir(Pathname & "\*.xls*")
Do While Filename <> ""
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set WB = Workbooks.Open(Pathname & Filename) 'open all files
PivotX WB
WB.Close SaveChanges:=True
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Filename = Dir()
Loop
End Sub
Here is the code for pivot and it works very well when running it alone:
Sub PivotX(WB As Workbook)
Dim Lrow, Lcol As Long
Dim wsData As Worksheet
Dim rngRaw As Range
Dim PvtTabCache As PivotCache
Dim PvtTab As PivotTable
Dim wsPvtTab As Worksheet
Dim PvtFld As PivotField
Set wsData = ActiveSheet
Lrow = wsData.Cells(Rows.Count, "B").End(xlUp).Row
Lcol = wsData.Cells(1, Columns.Count).End(xlToLeft).Column
Set rngRaw = wsData.Range(Cells(1, 1), Cells(Lrow, Lcol))
Set wsPvtTab = Worksheets.Add
wsData.Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rngRaw, Version:=xlPivotTableVersion12).CreatePivotTable TableDestination:=wsPvtTab.Range("A3"), TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion12
Set PvtTab = wsPvtTab.PivotTables("PivotTable1")
PvtTab.ManualUpdate = True
Set PvtFld = PvtTab.PivotFields("Month")
PvtFld.Orientation = xlPageField
PvtTab.PivotFields("Month").ClearAllFilters
Set PvtFld = PvtTab.PivotFields("Year")
PvtFld.Orientation = xlPageField
PvtTab.PivotFields("Year").ClearAllFilters
Set PvtFld = PvtTab.PivotFields("Fund_Code")
PvtFld.Orientation = xlRowField
PvtFld.Position = 1
Set PvtFld = PvtTab.PivotFields("Curr")
PvtFld.Orientation = xlColumnField
PvtFld.Position = 1
wsPvtTab.PivotTables("PivotTable1").PivotFields("Curr").PivotItems("USD").Position = 1
With PvtTab.PivotFields("Trx_Amount")
.Orientation = xlDataField
.Function = xlSum
.NumberFormat = "#,##0;[red](#,##0)"
End With
wsPvtTab.PivotTables("Pivottable1").RowAxisLayout xlTabularRow
'Remove grand total
wsPvtTab.PivotTables("Pivottable1").RowGrand = False
For Each PvtTbCache In ActiveWorkbook.PivotCaches
On Error Resume Next
PvtTbCache.Refresh
Next PvtTbCache
'Determine filter value
Set PvtFld = PvtTab.PivotFields("Year")
PvtFld.ClearAllFilters
PvtFld.EnableMultiplePageItems = True
With PvtFld
.AutoSort xlmnual, .SourceName
For Each Pi In PvtFld.PivotItems
Select Case Pi.Name
Case "2014"
Case Else
Pi.Visible = False
End Select
Next Pi
.AutoSort xlAscending, .SourceName
End With
'determine filter value
Set PvtFld = PvtTab.PivotFields("Month")
PvtFld.ClearAllFilters
PvtFld.EnableMultiplePageItems = True
With PvtFld
.AutoSort xlmnual, .SourceName
For Each Pi In PvtFld.PivotItems
Select Case Pi.Name
Case "11"
Case Else
Pi.Visible = False
End Select
Next Pi
.AutoSort xlAscending, .SourceName
End With
PvtTab.ManualUpdate = False
End Sub
Any help would be very much appreciated. Thank you very much in advance.
This should solve your problem:
Set WB = Workbooks.Open(Pathname & "\" & Filename)
When I tried using your code, for some reason, it did not retain the backslash you put at the beginning of the "Filename" variable. That would explain why VBA couldn't find the files. Adding it back should between the path name and file name should make it work correctly
I believe you have the answer to your base problem above but I would offer the following 'tweaks' to avoid screen flashing and unrecovered variable assignment.
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Do While Filename <> ""
Set WB = Workbooks.Open(Pathname & "\" & Filename) 'open all files
Call PivotX(WB)
WB.Close SaveChanges:=True
Set WB = Nothing
Filename = Dir()
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
The Set WB = Nothing is really only purposeful on the last pass when WB is not reassigned but your PivotX sub could use several Set nnn = Nothing before exiting. While the reference count is supposed to be decremented (and memory consequently released), that is not always the case. (see Is there a need to set Objects to Nothing inside VBA Functions) In short, it is just good coding practise.
Finally, using Dim Filename, Pathname As String declares Filename as a variant, not a string type. It isn't making any difference here but you should be aware of what your variables are being declared as.
I am new in Access been trying this for over 3days now. im tyingin to create a module or anything that when a press a button from a form the module will show a file dialog. get the .txt file and insert it into a table
here is how far i have got
Private Sub FileUpload()
'Requires reference to Microsoft Office 12.0 Object Library.
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Const MyFile = "TXT_Import_Spec" 'change to suit
'Clear listbox contents.
'Me.FileList.RowSource = ""
'Set up the File Dialog.
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
'Allow user to make multiple selections in dialog box.
.AllowMultiSelect = False
'Set the title of the dialog box.
.Title = "Please choose FM16 text files"
'Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add ".txt FM16 Files", "*.TXT"
.Show
obJaces
'Import Myfile
DoCmd.TransferText acImportDelim, "TXT_Import_Spec", "DM1", "MyFile", False
'Delete old records from Tbl_Import
'CurrentDb.Execute "DELETE * FROM DM1"
'Add new records to Tbl_Import
CurrentDb.Execute "INSERT INTO DM1 SELECT * FROM MyFile WHERE MyFile.JobNo IN (SELECT MyFile.JobNo FROM MyFile LEFT JOIN Tbl_Import ON MyFile.JobNo = Tbl_Import.JobNo WHERE Tbl_Import.JobNo Is Null)"
'Delete Myfile Table
CurrentDb.Execute "DROP TABLE MyFile"
End With
End Sub
been a stress full week. will appreciate any help.
#DonGeorge I have manage to get the script working please check the script below but the problem is its taking for ever. because the txt file has like 900,000 records.
so what i did to avoid overflow error is the script to show notification in every 100,000 records uploaded. but that takes like 5 mins for a good computer.
Option Compare Database
Sub uploadData()
On Error GoTo 11:
Dim strFile As String
Dim db As DAO.Database
Dim rs1 As DAO.Recordset
Dim cnt As Double
strFile = GetFile
If strFile <> "" Then
Set db = CurrentDb()
Set rs1 = db.OpenRecordset("BM1")
Dim firstLine As Boolean
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFile)
firstLine = False
msg = MsgBox("Do you want to delete all records from BM1 before loading ?", vbCritical + vbYesNo, "Upload File")
If msg = vbYes Then
DoCmd.SetWarnings False
DoCmd.RunSQL "delete * from BM1"
DoCmd.SetWarnings True
End If
Do Until objFile.AtEndOfStream
strEmployee = objFile.ReadLine
If firstLine = True Then
arrEmployee = Split(strEmployee, ",")
If UBound(arrEmployee) = 20 Then
rs1.AddNew
For i = 0 To rs1.Fields.Count - 1
rs1.Fields(i).Value = Replace(arrEmployee(i), """", "")
Next
rs1.Update
End If
Else
firstLine = True
End If
cnt = cnt + 1
If cnt Mod 100000 = 0 Then
MsgBox "Records Added " & cnt
End If
Loop
rs1.Close
MsgBox "Records Upload Completed"
End If
Exit Sub
11:
MsgBox Err.Description
End Sub
Function GetFile() As String
Dim f As Object
Set f = Application.FileDialog(3)
Dim varfile As Variant
f.AllowMultiSelect = False
f.Filters.Clear
f.Filters.Add "Text File", "*.txt"
f.Show
For Each varfile In f.selecteditems
GetFile = varfile
Exit For
Next varfile
End Function
Need help, in this line....If IsError(Application.Match(iLine, arr, 0)) Then ...
Its runtime error is that an object is required. I've tried a number of different things to solve, but am stuck. Been researching but not finding anything as a resolution.
When I try to declare..."Dim arr as variant" it retorts that "Expected end of statement". I am simply clicking on "ProcessCollection.vbs" to run the script. I'm using EditPlus3, and it does highlight "Application" in red text in this line.
I've tried VbsEdit and when it debugs to this line, iLine, arr, are defined, but the value of "Application" is "Empty".
GetFiles()
'WriteCSV()
'*****
Function GetFiles
Dim arr
'Dim arr as Variant
Dim iFileLines
Dim iLine
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\hgis\a"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
'Wscript.Echo objFile.Name
mfn = objStartFolder +"\"+ objFile.Name
Wscript.Echo mfn
'open file & process each file
set fso = CreateObject("Scripting.FileSystemObject")
Set theFile = fso.OpenTextFile(mfn, 8, True)
iFileLines = theFile.Line
iLine = 0
arr = Array(2, 3, iFileLines - 1) ' second, third, and 2nd from last
msgbox iFileLines
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile(mfn,1)
Dim strLine, TotStr
TotStr = "CellA"
do while not objFileToRead.AtEndOfStream
strLine = objFileToRead.ReadLine()
msgbox strline
'Parse lines for specific data - i.e. "-2014-" to get date/time stamp
iLine = iLine + 1
'And then check if the line number is in the array:
'Capture data and store to csv file for Excel analysis
If IsError(Application.Match(iLine, arr, 0)) Then
' It isn't in the array, do this....
msgbox "no"
Else
' It is in the array, grab it
TotStr = TotStr +","+ strline
msgbox TotStr
End If
loop
objFileToRead.Close
Set objFileToRead = Nothing
Next
'csvFile.Close
End Function
'*****
I found a function from Justin Doles at DigitalDeviation.com that I used to replace the Application.Match function.
Function IsInArray(strIn, arrCheck)
'IsInArray: Checks for a value inside an array
'Author: Justin Doles - www.DigitalDeviation.com
Dim bFlag
bFlag = False
If IsArray(arrCheck) AND Not IsNull(strIn) Then
Dim i
For i = 0 to UBound(arrCheck)
If LCase(arrcheck(i)) = LCase(strIn) Then
bFlag = True
Exit For
End If
Next
End If
IsInArray = bFlag
End Function
'*****
I am another newb to scripting. I've done a lot of searching and haven't been able to find a solution that suits my problem.
I have a folder with a varying number of CSV's that each contain 1
worksheet and 2 values in the same cells (A2 & B2).
The worksheet names are not the same.
Logically I need to create a script that goes to each CSV in this folder, grabs the 2 values and puts them into a single worksheet in an XLS called MonthlyAvg in 2 columns
ie 1st Range goes to A2 & B2 in master document, second A2 & B2 goes into A3 & B3 in master document. My thoughts are that this should be handled in an array. Alas this is where I am stuck as I'm unable to put what I've found on creating arrays logically into what I've put together so far. Any help or guidance would be greatly appreciated.
strPath = "D:\MacWP\MacWork\Thermometers\TOT\MonthlyAvg\"
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.DisplayAlerts = False
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFso.GetFolder (strPath)
For Each objFile In objFolder.Files
If objFso.GetExtensionName (objFile.Path) = "csv" Then
Set objWorkbook = objExcel.Workbooks.Open(objFile.Path)
'Find the first worksheet name
FirstSheetName = objExcel.Activeworkbook.Worksheets(1).Name
'Set the first worksheet name
Set objSheet = objWorkbook.Sheets (FirstSheetname)
'Display the value in B2 of the first worksheet
MsgBox objSheet.Range("B2").Value
'Display the value in A2 of the first worksheet
MsgBox objSheet.Range ("A2").Value
objWorkbook.Close False 'Save changes
End If
Next
objExcel.Quit
If I understand, your file searching is already done, and your only question is how to storage the partial values in a master excel file, right ?
For that, you can use a For cycle with an "index".
Dim i As Integer, j As Integer, n As Integer
Dim filesOpen As Long
With Application.FileSearch
.LookIn = "C:\Examples"
.FileType = msoFileTypeExcelWorkbooks
'There are wb's
If .Execute > 0 Then
For n = 1 To .FoundFiles.Count
Workbooks.Open (.FoundFiles(i))
Next n
filesOpen = n
end With
For i = 2 To filesOpen
'i = 2 'fila
j = 1 'columna
'column A2
Application.Workbooks("MasterFile").Worksheets("nameOfYourMasterSheet").Cells(i, j).Value = Application.Workbooks("Book1.cvs").Worksheets("nameOfYourSheet").Cells(2, j).Value
'column B2
Application.Workbooks("MasterFile").Worksheets("nameOfYourMasterSheet").Cells(i, j+1).Value = Application.Workbooks("Book1.cvs").Worksheets("nameOfYourSheet").Cells(2, j+1).Value
next i
So, the last for cycle is for giving the values to your Master File. The "i" index is the only one which is ascending until you dont have more workbooks.
You don't have to use Arrays, just watch out the "i" value.
You could use a vbs as below to write all the values to a csv file directly. The code below creats a file output.csv under strPath
Dim objExcel
Dim objFSO
Dim objTF
Dim objWB
strpath = "c:\temp"
Set objExcel = CreateObject("Excel.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strpath)
Set objTF = objFSO.CreateTextFile(strpath & "\output.csv", True, False)
objExcel.DisplayAlerts = False
For Each objFile In objFolder.Files
If objFSO.GetExtensionName(objFile.Path) = "csv" Then
Set objWB = objExcel.Workbooks.Open(objFile.Path)
objTF.WriteLine objWB.Sheets(1).Range("B2") & "," & objWB.Sheets(1).Range("A2")
objWB.Close False 'Save changes
End If
Next
objTF.Close
With objExcel
.DisplayAlerts = True
.Quit
End With