VBA - copy / paste one cell from multiple workseets to master sheet - excel

I have code which opens multiple files in a folder, prints the name of that file into column 1 (continuing down the column) of a masterfile, closes the current file, and moves onto the next one until the folder is empty.
There is information in cell J1(preferably written as 1,10) of all of the files that I want to copy while the file is open, paste into column 4 (continuing down the column, equal with the names of each file), and continue to close the current file and move on.
I cannot figure out how to copy just one cell since a range requires information over multiple rows. Here is my working code for looping through files and just printing their name. Any ideas? Thanks!
Sub LoopThroughDirectory()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim MyFolder As String
Dim Sht As Worksheet
Dim i As Integer
Dim LastRow As Integer, erow As Integer
'Speed up process by not updating the screen
'Application.ScreenUpdating = False
MyFolder = "C:\Users\trembos\Documents\TDS\progress\"
Set Sht = ActiveSheet
'create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'get the folder object
Set objFolder = objFSO.GetFolder(MyFolder)
i = 1
'loop through directory file and print names
For Each objFile In objFolder.Files
If LCase(Right(objFile.Name, 3)) = "xls" Or LCase(Left(Right(objFile.Name, 4), 3)) = "xls" Then
'print file name
Sht.Cells(i + 1, 1) = objFile.Name
i = i + 1
Workbooks.Open fileName:=MyFolder & objFile.Name
End If
'Macro recording of manual copy/paste but I want to apply on general scale
'Range("J1").Select
'Selection.Copy
'Windows("masterfile.xlsm").Activate
'Range("D2").Select
'ActiveSheet.Paste
ActiveWorkbook.Close SaveChanges:=False
Next objFile
'Application.ScreenUpdating = True
End Sub

Incorporate this, renaming "MySheet":
Option Explicit
Sub CopyFromSheets()
Dim WB As Workbook
Dim ws As Worksheet
Dim i As Integer
Set WB = ActiveWorkbook
i = 1
With WB
For Each ws In .Worksheets
With ws
.Range("J1").Copy Workbooks("masterfile.xlsm").Sheets("MySheet").Cells(i, 10) 'Rename Mysheet
i = i + 1
End With
Next ws
End With
End Sub
This should do it:
Option Explicit
Sub LoopThroughDirectory()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim MyFolder As String
Dim Sht As Worksheet, ws As Worksheet
Dim WB As Workbook
Dim i As Integer
Dim LastRow As Integer, erow As Integer
Application.ScreenUpdating = False
MyFolder = "C:\Users\trembos\Documents\TDS\progress\"
Set Sht = Workbooks("masterfile.xlsm").Sheets("MySheet")
'create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'get the folder object
Set objFolder = objFSO.GetFolder(MyFolder)
i = 1
'loop through directory file and print names
For Each objFile In objFolder.Files
If LCase(Right(objFile.Name, 3)) = "xls" Or LCase(Left(Right(objFile.Name, 4), 3)) = "xls" Then
'print file name
Workbooks.Open Filename:=MyFolder & objFile.Name
Set WB = ActiveWorkbook
With WB
For Each ws In .Worksheets
Sht.Cells(i + 1, 1) = objFile.Name
With ws
.Range("J1").Copy Sht.Cells(i + 1, 4)
End With
i = i + 1
Next ws
.Close SaveChanges:=False
End With
End If
Next objFile
Application.ScreenUpdating = True
End Sub

Related

VBA Copy and Paste without formatting

I've got this code but it pastes the cell formatting from the original document into the master file, how can I remove the formatting from the output please?
Option Explicit
Sub CopyPastefiles()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim MyFolder As String
Dim StartSht As Worksheet, ws As Worksheet
Dim WB As Workbook
Dim i As Integer
'turn screen updating off - makes program faster
'Application.ScreenUpdating = False
'location of the folder in which the desired TDS files are
MyFolder = "U:\Documents\DeleteMe\Sycle\"
Set StartSht = ActiveSheet
Set StartSht = Workbooks("masterfile.xlsx").Sheets("Sheet1")
'create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'get the folder object
Set objFolder = objFSO.GetFolder(MyFolder)
i = 1
'loop through directory file and print names
For Each objFile In objFolder.Files
If LCase(Right(objFile.Name, 3)) = "xls" Or LCase(Left(Right(objFile.Name, 4), 3)) = "xls" Then
'print file name to Column 1
Workbooks.Open Filename:=MyFolder & objFile.Name
Set WB = ActiveWorkbook
'print TOOLING DATA SHEET(TDS): values to Column 2
With WB
For Each ws In .Worksheets
StartSht.Cells(i + 1, 10) = objFile.Name
With ws
.Range("e6").Copy StartSht.Cells(i + 1, 4)
.Range("e7").Copy StartSht.Cells(i + 1, 5)
.Range("e8").Copy StartSht.Cells(i + 1, 6)
End With
i = i + 1
'move to next file
Next ws
'close, do not save any changes to the opened files
.Close SaveChanges:=False
End With
End If
'move to next file
Next objFile
'turn screen updating back on
'Application.ScreenUpdating = True
End Sub
thanks for you help.
Instead of using .Copy to directly paste the values into the destination, you can use .PasteSpecial Paste:=xlPasteValues.
I.e. something like
.Range("e6").Copy
StartSht.Cells(i + 1, 4).PasteSpecial Paste:=xlPasteValues
for your first line.
Or you can just set the cell equal to the range you're copying, as suggested in the comments on your question.
.StartSht.Cells(i + 1, 4) = .Range("E6")

Excel File not Recognized by VBA

The error occurs on the Open.Workbooks MasterFile line. I get the error of "This file cannot be found. Has it been removed, renamed, or replaced?" I used the fso.FileExist function to make sure the file does actually exist, and when I debug.print, the file name is exactly as it is specified in the variable MasterFile. Why won't VBA recognize this .xlsm file?
Sub ProcessData()
Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
Dim fil As Scripting.File
Dim MyDir As String
Dim FolderSource As Scripting.Folder
'FolderSource is the fso enabled directory folder
Dim FolderDataSource As Scripting.Folder
'FolderDest is the fso enabled folder where the MasterFile is located
MyDir = "C:\Users..."
'MyDir is where all part number files will be stored
Dim MasterFile As String
Dim MasterFilePath As String
MasterFilePath = "C:\Users..."
MasterFile = "Function Master File.xlsm"
Dim wbSource As Workbook, wsSource As Worksheet
'The workbook and worksheet source will be the Master FIle
Dim wbDest As Workbook, wsDest As Worksheet
'The destination workbook and worksheet corresponding to the part number file
Dim myArray As Variant
Dim myTable As ListObject
Dim x As Long
myArray = Range("D13:D17")
'Array will draw from part number values that are entered in the appropriate area on the template
'Creating files for all new part numbers
Set FolderSource = fso.GetFolder(MyDir)
'For Each fil In FolderSource.Files
For x = LBound(myArray) To UBound(myArray)
If myArray(x, 1) <> "" Then
PartNumFile = MyDir & "\" & myArray(x, 1) & ".xlsx"
If Not fso.FileExists(PartNumFile) Then
Set newbook = Workbooks.Add
With newbook
.SaveAs Filename:=PartNumFile
End With
End If
End If
'Searching for the Part Number Data in the Master File
Set FolderDataSource = fso.GetFolder(MasterFilePath)
For Each fil In FolderDataSource.Files
Debug.Print fil.Name
If fso.FileExists(MasterFilePath & "\" & MasterFile) Then
Debug.Print fil.Name
Workbooks.Open MasterFile
Set wbSource = Workbooks(MasterFile)
Set wsSource = wbSource.Worksheets(1)
lrSource = wsSource.Range("A" & wsSource.Rows.Count).End(xlUp).Row
Set wbDest = Workbooks(myArray(x, 1) & ".xlsx")
Set wsDest = wbDest.Worksheets(1)
lrDest = wsDest.Range("A" & wsDest.Rows.Count).End(xlUp).Row + 1
wsSource.Range("A2:V" & lrSource).Copy Destination:=wsDest.Range("A" & lrDest)
End If
Next
Next
End Sub

Look through all files in ALL subfolders and retrieve data from one cell and paste on Master Workbook

I want to create something that would loop through all the files from a directory with subfolders. Then, it would open each excel file and copy the total amount. The cell that contains the total is not always in a specific row, but column B of that row contains the text " TOTAL AMOUNT". The cell that contains the total is ALWAYS in column I. After it copies the cell, paste in the Master workbook ( the workbook the macro is running from ) in a new sheet in cell (i,2)
Cell(1,1) and Cell(1,2) are headers. "GROUPER" and "EFT_AMOUNT"
Here is what I have so far :
Sub PaymentFileMatching()
Dim HostFolder As String
Dim f As String, i As Long, arr, sht As Worksheet
Dim FSO As Object, objFolder As Object, FileInFolder As Object
Dim wb As Workbook, Masterwb As Workbook
Set sht = ActiveSheet
Set FSO = CreateObject("Scripting.filesystemobject")
Dim objSubFolder As Object
HostFolder = "C:\Users\kxc8574\Documents\Payment Files\Payment Files (Corrected)\PE20170701\"
Set objFolder = FSO.GetFolder(HostFolder)
Set Masterwb = Workbooks("Master Template")
Sheets("Sheet9").Activate
sht.Cells(1, 1).Resize(1, 2).Value = _
Array("GROUPER", "EFT_AMOUNT")
i = 2
For Each objSubFolder In objFolder.subfolders
For Each FileInFolder In objSubFolder.Files
sht.Cells(i, 1).Value = Left(FileInFolder.Name, InStr(FileInFolder.Name, "PE 2017") - 1)
Set wb = Workbooks.Open(objSubFolder & "\" & FileInFolder.Name)
For Each sht In Worksheets
For Each Cell In Sheets("Payment Summary").Range("B:B")
If Cell.Value = "Final EFT Payment Amount" Then
matchRow = Cell.Row
Cells(matchRow, 8).Copy
Workbooks("Master Template").Worksheets("Sheet9").Cells(i, 2).PasteSpecial xlPasteValues
i = i + 1
End If
Next Cell
Next FileInFolder
Next objSubFolder
End Sub
You arent defining what Cell is - put Option Explicit at the very top of your module and then try compiling and it will tell you the things you forgot to define. To define it use
Dim Cell as Range
Untested:
Sub PaymentFileMatching()
Const HostFolder As String = _
"C:\Users\kxc8574\Documents\Payment Files\Payment Files (Corrected)\PE20170701\"
Dim i As Long
Dim FSO As Object, objFolder As Object, FileInFolder As Object
Dim wb As Workbook, Masterwb As Workbook, MasterSht As Worksheet, sht As Worksheet
Dim objSubFolder As Object, f As Range, fName As String
Set FSO = CreateObject("Scripting.filesystemobject")
Set objFolder = FSO.GetFolder(HostFolder)
Set Masterwb = Workbooks("Master Template")
Set MasterSht = Masterwb.Sheets("Sheet9")
MasterSht.Activate
MasterSht.Cells(1, 1).Resize(1, 2).Value = Array("GROUPER", "EFT_AMOUNT")
i = 2
For Each objSubFolder In objFolder.subfolders
For Each FileInFolder In objSubFolder.Files
fName = FileInFolder.Name
MasterSht.Cells(i, 1).Value = Left(fName, InStr(fName, "PE 2017") - 1)
Set wb = Workbooks.Open(objSubFolder & "\" & fName)
For Each sht In wb.Worksheets
Set f = sht.Columns(2).Find("Final EFT Payment Amount", , xlValues, xlWhole)
If Not f Is Nothing Then
MasterSht.Cells(i, 2).Value = f.EntireRow.Cells(8).Value
i = i + 1
Exit For 'found the value...
End If
Set f = Nothing
Next sht
wb.Close False
Next FileInFolder
Next objSubFolder
End Sub

Create range name in several files

I'm trying to create a range name in a number of excel files, and then write the file names and paths out to another excel. The files/paths are written correctly, but the range name doesn't appear to be created in the file. Can you tell me where I'm going wrong?
Sub directlisting()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim cell As Range
Dim RangeName As String
Dim CellName As String
Dim i As Integer
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder("\\xxxxxxxxxxx\testdata\Transfer")
'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
'open file if an Excel file
If Right(objFile, 4) = "xls*" Or Right(objFile, 3) = "xl*" Then
Application.Workbooks.Open (objFile)
'create range name
RangeName = "PVS"
CellName = "A4:AG27"
Set cell = Worksheets("PVS").Range(CellName)
objFile.Names.Add Name:=RangeName, RefersTo:=cell
'Save the file
Application.DisplayAlerts = False
objFile.Save
objFile.Close
Application.DisplayAlerts = True
End If
'print file name
Cells(i + 1, 1) = objFile.Name
'print file path
Cells(i + 1, 2) = objFile.path
i = i + 1
Next objFile
End If
End Sub
I tested this and it seemed to work for me. The main idea was to be more explicit with the workbook/worksheets and what you're calling them on:
Sub directlisting()
Dim objFSO As Object, objFolder As Object, objFile As Object
Dim cell As Range
Dim RangeName As String, CellName As String
Dim i As Integer
Dim tempWB As Workbook, mainWB As Workbook
Dim mainWS As Worksheet
'Assuming this is running from a "main" workbook
Set mainWB = ActiveWorkbook
Set mainWS = mainWB.ActiveSheet
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder("D:\User\Documents\Test") ' CHANGE TO YOUR PATH
'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
'open file if an Excel file
If Right(objFile, 4) = "xlsx" Or Right(objFile, 3) = "xl*" Then
Set tempWB = Application.Workbooks.Open(objFile)
'create range name
RangeName = "PVS"
CellName = "A4:AG27"
Set cell = tempWB.Worksheets("PVS").Range(CellName)
'ActiveWorkbook.Names.Add Name:="PVS", RefersToR1C1:="=PVS!R11C8:R18C14"
tempWB.Names.Add Name:=RangeName, RefersTo:=cell
'print file name
mainWS.Cells(i + 1, 1) = tempWB.Name
'print file path
mainWS.Cells(i + 1, 2) = tempWB.Path
i = i + 1
'Save the file
Application.DisplayAlerts = False
tempWB.Save
tempWB.Close
Application.DisplayAlerts = True
End If ' Right (objFile, 4) ...
Next objFile
End Sub
Small note: I had to change the ... = "xls*" Or Right ... to ... = "xlsx" Or ..., because for some reason it wouldn't open the .xlsx file. Curious. In any case, let me know if you get any errors or weird issues!
Also, I moved the part where you save the workbook name and path inside the If statement, so only if the file opens, will it mark it. Just tweak that line if you want to note every file, whether or not it opens.

Concatenate index name in the Workbooks Object

I am trying to create For Each loop for a several workbooks; however I am not able to set the workbook name in the array and thus resulted into this. I'm stuck in trying to concatenate the workbook name.
Here's my code:
'Open all .csv file in folder location
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(ThisWorkbook.Path)
For Each objFile In objFolder.Files
If InStr(objFile, ".csv") Then
Workbooks.Open (objFile)
End If
Next
' Declare variables
Dim WrkBkPrm As Workbook
Dim WrkBkSrc As Workbook
Dim WrkShtPrm As Worksheet
Dim WrkShtSrc As Worksheet
Dim TextSrc(4) As String
Dim SrcRng As Range
Dim DRng As Range
' Assign values to TextSrc() Array
TextSrc(0) = Cable
TextSrc(1) = Care
TextSrc(2) = MSD
TextSrc(3) = Business
'Set WrkBkPrm and WrkShtPrm values
Set WrkBkPrm = Workbooks("MasterFile" & ".xlsm")
Set WrkShtPrm = WrkBkPrm.Worksheets("Canvas")
'Activate Canvas Sheet
WrkBkPrm.Activate
WrkShtPrm.Select
Application.ScreenUpdating = False
'Start For Each Loop
For Each Src In TextSrc()
Set WrkBkSrc = Workbooks(Src & ".csv")
Set WrkShtSrc = WrkBkSrc.Worksheets(Src)
'Copy loop for 1st section
For i = 2 To 49
For j = 7 To 25
Set SrcRng = WrkShtSrc.Cells(i, j)
Set DRng = WrkShtPrm.Cells(i, j)
If SrcRng <> "" Then
DRng.Value = SrcRng.Value
End If
Next j
Next i
Next Src
Application.ScreenUpdating = True
I'd suggest you work on the file as soon as you get hold of the relevant info you need.
Something like:
Dim wb As Workbook
For Each objFile In objFolder.Files
If InStr(objFile.Name, ".csv") <> 0 Then
Set wb = Workbooks.Open(Thisworkbook.Path & "\" & objFile.Name)
'~~> Do your cool stuff with the opened CSV File
wb.Close False '~~> Close without saving
Set wb = Nothing '~~> Clean up although most of the time not necessary
End If
Next
As for the route you took, for you to use For Each Loop on TxtSrc, you need to declare it as variant.
Something like:
Dim TxtSrc As Variant, Src As Variant
TxtSrc = Array("Cable", "Care", "MSD", "Business")
For Each Src In TxtSrc
Set wb = Workbooks.Open(Thisworkbook.Path & "\" & Src & ".csv")
'~~> More cool stuff here
wb.Close False
Set wb = Nothing
Next
It is important that provide the correct argument for the Workbook Open Method.
You should always include the complete path in string format. HTH.

Resources