Compile a list/ summary of a specific cell from multiple workbooks with VBA? - vba

I have multiple workbooks in the same layout. In the cell "I8" I have calculated a specific value that I want to compile from all workbooks.
Here is an example of my code:
Sub Code()
Dim file As String
Dim wbResults As Workbook
Dim myPath As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
myPath = "C:\Test\"
file = Dir$(myPath & "*.xls*")
While (Len(file) > 0)
Set wbResults = Workbooks.Open(Filename:=myPath & file, UpdateLinks:=0)
With wbResults.Worksheets(Split(file, ".")(0))
With .Range("I8")
.Formula = "=10^(D28+(I7*I2))"
End With
End With
wbResults.Close SaveChanges:=True
file = Dir
Wend
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
I would like to add to this code and compile a list in another excel workbook where column A puts the name of the file of a workbook and column B puts the value of "I8" in that respective workbook.

Here is my answer:
Sub Code()
Dim file As String
Dim wbResults As Workbook
Dim myPath As String
myPath = "C:\Test\"
'---------------- Create a new workbook then save it ----------------
Dim WBSummary As Workbook
Set WBSummary = Excel.Application.Workbooks.Add
WBSummary.SaveAs myPath & "WBSummary.xls"
'--------------------------------------------------------------------
Application.ScreenUpdating = False
Application.DisplayAlerts = False
file = Dir$(myPath & "*.xls*")
Dim i As Long 'To update row number in WBSummary
While (Len(file) > 0)
i = i + 1
If file <> "WBSummary.xls" Then
Set wbResults = Workbooks.Open(Filename:=myPath & file, UpdateLinks:=0)
With wbResults.Worksheets(Split(file, ".")(0))
With .Range("I8")
.Formula = "=10^(D28+(I7*I2))"
.Calculate 'To update value in "I8"
WBSummary.Worksheets(1).Cells(i, 1).Value = file
WBSummary.Worksheets(1).Cells(i, 2).Value = .Value
End With
End With
wbResults.Close SaveChanges:=True
End If
file = Dir
Wend
WBSummary.Close True 'Close and Save WBSummary
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

Related

Copy and paste a fixed column to a master sheet next to each other

I am trying to copy a fixed column from files in a folder, I am extracting column N only and pasting them onto an active sheet with columns right next to each other. However, I am getting error message, please help me
Sub LoopThroughDirectory()
Dim MyFile As String
Dim Filepath As String
Dim Wb As Workbook, _
Ws As Worksheet, _
PasteRow As Long
Filepath = "\\123.20.0.89\Risk_dept\"
Set Ws = ActiveSheet
Application.DisplayAlerts = False
Application.ScreenUpdating = False
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
If MyFile = "zmaster.xlsm" Then
Exit Sub
End If
PasteCloumn = Ws.Range("A" & Ws.Columns.Count).End(xlToRight).Column + 1
Set Wb = Workbooks.Open(Filepath & MyFile)
Worksheets("part 5").Range("N2:N200").Copy
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range("A:A").End(xlToRight).Column + 1
Applicaiotn.CutCopyMode = False
MyFile = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
This works for me. Extracts column N from files in folder and pastes them into active sheet.
Sub LoopThroughDirectory()
Dim filePath As String, target As Worksheet, file As String, wb As Workbook, col As Long
filePath = "\\123.20.0.89\Risk_dept\"
Set target = ActiveSheet
Application.DisplayAlerts = False
Application.ScreenUpdating = False
file = Dir(filePath)
Do While Len(file) > 0
If file = "zmaster.xlsm" Then
Exit Sub
End If
Set wb = Workbooks.Open(filePath & file)
col = target.Range("A1").End(xlToRight).Column + 1
wb.Worksheets("part 5").Range("N2:N200").Copy Destination:=target.Cells(1, col)
file = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

VBA code to format 6 excel sheets with multiple tabs by offsetting table data by a few rows

not my code completely.borrowed it from net with my changes in between
PURPOSE: To loop through all Excel files in a user specified folder and
perform a set task on them
SOURCE: www.TheSpreadsheetGuru.com
Sub LoopAllExcelFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Application.EnableEvents = False
'Retrieve Target Folder Path From User
myPath = ThisWorkbook.Worksheets(1).Range("B1").Value & "\" &
ThisWorkbook.Worksheets(1).Range("B2").Value & "\" &
ThisWorkbook.Worksheets(1).Range("B3").Value & "\"
End Sub
not my code completely.borrowed it from net with my changes in between
PURPOSE: To loop through all Excel files in a user specified folder and
perform a set task on them
SOURCE: www.TheSpreadsheetGuru.com
Sub LoopAllExcelFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Application.EnableEvents = False
'Retrieve Target Folder Path From User
myPath = ThisWorkbook.Worksheets(1).Range("B1").Value & "\" &
ThisWorkbook.Worksheets(1).Range("B2").Value & "\" &
ThisWorkbook.Worksheets(1).Range("B3").Value & "\"
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
WS_Count = wb.Worksheets.Count
' Begin the loop.
'Ensure Workbook has opened before moving on to next line of code
DoEvents
For I = 1 To WS_Count
'Change First Worksheet's Background Fill Blue
'following snippet arranges data in the 4th row and colors it
With wb.Worksheets(I)
If (Range("A1") <> "") Then
'Find the last used row in a Column: column A in this example
Dim LastRow As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
Dim LastCol As Integer
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column
LastColcell = Cells(1, LastCol).Address
Range("A1:" & LastColcell).Font.Color = vbWhite
Range("A1:" & LastColcell).Interior.Color = RGB(51, 98, 174)
Rows("1:3").Insert Shift:=xlDown
Range("G1").FormulaR1C1 = "=SUBTOTAL(9,R[5]C:R[" & LastRow & "]C)"
Range("G1").AutoFill Destination:=Range("G1:" & LastColcell)
Range("G1:" & LastColcell).Interior.Color = RGB(255, 255, 0)
AutoFilterMode = False
End If
End With
Next I
'Save and Close Workbook
Dt = Format(Date, "yyyymmdd")
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub

Find if workbook for individual user exists, if workbook does not exist, create a new workbook with template

I have a data file that I am trying to make for each person in my work group. The data file needs to be identical to a master file as each persons data will be collected into said master file as well as an individual data file.
So far, I have the following code where I try to identify whether a user already has a workbook. I want the created workbook to have the same first four sheets as the master workbook.
The folder specified only contains the "DataFile Master" Workbook so I wouldn't expect the macro to take longer than ~5 seconds. However, when I try to run the macro, the workbook becomes non responsive.
The program does not induce an error report or indicate something to debug.
Does anyone have any ideas?
Sub StoreToPersonal()
Application.ScreenUpdating = False
ckIndWkbk = False
folderpath = "\\netappa\Path\MACRO UPDATE WORKBOOKS" 'change to suit
If Right(folderpath, 1) <> "\" Then folderpath = folderpath + "\"
filename = Dir(folderpath & "*.xlsm")
'Look through path length and find if user has an individual Workbook with a Boolean Statement
Do While filename <> ""
If InStr(filename, Environ("Username")) Then
ckIndWkbk = True
Else
End If
Loop
If ckIndWkbk = False Then
Set wb = Workbooks.Open("\\netappa\Path\MACRO UPDATE WORKBOOKS\DataFile Master.xlsm")
ws = wb.Sheets.Count
For Each ws In wb
If ws.Index > 4 Then
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
wb.SaveAs ("\\netappa\Path\MACRO UPDATE WORKBOOKS\\DataFile For " & Environ("Username"))
End If
Application.ScreenUpdating = True
End Sub
The first Dir call sets the parameters and return the first file in the directory. You need to use the Dir in your Do Loop to return subsequent files.
Note: I added Exit Do to after the condition is met.
MSDN Dir Function
Sub StoreToPersonal()
Application.ScreenUpdating = False
ckIndWkbk = False
folderpath = "\\netappa\Path\MACRO UPDATE WORKBOOKS" 'change to suit
If Right(folderpath, 1) <> "\" Then folderpath = folderpath + "\"
Filename = Dir(folderpath & "*.xlsm")
'Look through path length and find if user has an individual Workbook with a Boolean Statement
Do While Filename <> ""
If InStr(Filename, Environ("Username")) Then
ckIndWkbk = True
Exit Do
End If
Filename = Dir
Loop
If ckIndWkbk = False Then
Set wb = Workbooks.Open("\\netappa\Path\MACRO UPDATE WORKBOOKS\DataFile Master.xlsm")
ws = wb.Sheets.Count
For Each ws In wb
If ws.Index > 4 Then
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
wb.SaveAs ("\\netappa\Path\MACRO UPDATE WORKBOOKS\\DataFile For " & Environ("Username"))
End If
Application.ScreenUpdating = True
End Sub

Close file before moving onto the next file

This macro loops through all the files in a directory and formats the data as a table.
I need to sort Column J on the table from Largest to Smallest and then save the file before moving onto the next file. Currently it leaves all the files open.
Sub LoopThroughFiles()
FolderName = "C:\Folder1\"
If Right(FolderName, 1) <> Application.PathSeparator Then FolderName = FolderName & Application.PathSeparator
Fname = Dir(FolderName & "*.xls")
'loop through the files
Do While Len(Fname)
With Workbooks.Open(FolderName & Fname)
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium2"
Columns("A:L").Select
Columns("A:L").EntireColumn.AutoFit
End With
'go to the next file in the folder
Fname = Dir
Loop
End Sub
You are missing the line where you Close the workbook : WB.Close True.
(if you don't want to save the changes made to the workbook use WB.Close False)
Note: you are not setting the Worksheet object on the workbook you open, so by default it will assume the ActiveSheet, which is the last ActiveSheet the last time you saved this workbook.
Try the code below:
Sub LoopThroughFiles()
Dim WB As Workbook
FolderName = "C:\Folder1\"
If Right(FolderName, 1) <> Application.PathSeparator Then FolderName = FolderName & Application.PathSeparator
fname = Dir(FolderName & "*.xls")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'loop through the files
Do While Len(fname)
Set WB = Workbooks.Open(FolderName & fname) '<-- set the workbook object
With WB
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium2"
Columns("A:L").Select
Columns("A:L").EntireColumn.AutoFit
End With
WB.Close True ' <-- close workbook and save changes
' go to the next file in the folder
fname = Dir
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

Merge Many excel files to one new file with different sheet

I am trying to merge many excel files (workbooks) from a folder.
My problem is that I want to move different sheets to the new excel file.
At the moment my code can only move one sheet at the time from these different files.
Example:
I have 3 excel files named
1.xlsx
2.xlsx
3.xlsx
all 3 files have 3 sheets in it and I want to take sheet1 from 1.xlsx and sheet1 and sheet2 from 2.xlsx and finally sheet3 from 3.xlsx and put in a new excel file.
My code at the moment can only takes one sheet (and same sheet number) from each file and put in the new file.
My code so fare:
Sub MergeMultiSheets()
Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim Path As String
Dim Filename As String
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
path = "C:\Users\*ChangeThis*\Desktop\merge"
Set wbDst = Workbooks.Add(xlWBATWorksheet)
Filename = Dir(path & "\*.xlsx", vbNormal)
If Len(Filename) = 0 Then Exit Sub
Do Until Filename = ""
Set wbSrc = Workbooks.Open(Filename:=path & "\" & Filename)
sheet = 1
Set wsSrc = wbSrc.Worksheets(sheet)
wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)
wbSrc.Close False
Filename = Dir()
Loop
wbDst.Worksheets(1).Delete
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Many thank in advance
You need to loop through all the Sheets in the current Workbook found in your folder.
Try the code below:
Sub MergeMultiSheets()
Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim Path As String
Dim Filename As String
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
Path = "C:\Users\*ChangeThis*\Desktop\merge"
Set wbDst = Workbooks.Add(xlWBATWorksheet)
Filename = Dir(Path & "\*.xlsx", vbNormal)
If Len(Filename) = 0 Then Exit Sub
Do Until Filename = ""
Set wbSrc = Workbooks.Open(Filename:=Path & "\" & Filename)
Sheet = 1
' ****** you need to loop on all sheets per Excel workbook found in Folder ******
For Each wsSrc In wbSrc.Sheets
wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)
Next wsSrc
wbSrc.Close False
Filename = Dir()
Loop
wbDst.Worksheets(1).Delete
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub