Dynamic Update last non empty cell in a column VBA Excel - excel

I'm trying to write in an Excel sheet with a VBA macro. After I open a workbook with:
Set wrk=open ("C:/text.xlsx")
I find last non empty cell in a column "B",
for example with:
LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
then I write one with:
cell(LastRow,2) =1
but when I want to write in column "D" the same way:
LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row
cell(lastRow,4)=1
the macro writes one in the same row as the first one, knowing that the last non empty cell in column "B" and column "D" are not the same.
I wrote:
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.AskToUpdateLinks = False
before opening the Excel sheet to make the macro faster.
Mycode:
Option Explicit
Private Sub maac() ' fonction de décharge de questionnaire type Compostage
Dim src_path, distination_Path As String
Dim source, distination As String 'workbooks
Dim src_feuil, via, distination_feuil As String 'sheets
Dim src_cell_address As String ' adresses
Dim count, countB, last_via_cell, distination_col_address As Integer
Dim last_dist_row As Long
Dim dist_path_fname As String
Dim co, wrk As Workbook
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.AskToUpdateLinks = False
'Desactive les alerts et les mises à jour écran
'App_prop.app_disable
Set co = ThisWorkbook
via = ActiveSheet.Name 'activated Via worksheet
last_via_cell = Sheets(via).UsedRange.Rows.count
'MsgBox ActiveSheet.Name ' nom de la feuil active
'MsgBox Sheets(via).Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
src_path = Sheets(via).Cells(2, 1).Value
source = "src.xlsx"
src_feuil = Sheets(via).Cells(2, 3).Value
src_cell_address = Sheets(via).Cells(Sheets(via).Cells(2, 6).Value, Sheets(via).Cells(2, 7).Value).Address
distination_Path = Sheets(via).Cells(2, 9) ' path of source file (questionnaire) bdd file path
distination = Sheets(via).Cells(2, 8) ' name of bdd file
distination_feuil = Sheets(via).Cells(2, 10) ' name of sheet of bdd file
distination_col_address = Sheets(via).Cells(2, 12)
'DoEvents
Set wrk = Workbooks.Open(distination_Path & "\" & distination & ".xlsx")
'Application.ScreenUpdating = False
last_dist_row = wrk.Sheets(distination_feuil).Cells(Rows.count, distination_col_address).End(xlUp).Row + 1
MsgBox last_dist_row
wrk.Sheets(distination_feuil).Cells(last_dist_row, distination_col_address) = GetValue(src_path, source, src_feuil, src_cell_address) 'GET VALUE
For count = 3 To last_via_cell
'---- SOURCE COORDINATIONS
'Workbooks("C:\Users\pc\Desktop\comp.xlsm").Sheets("Compostage").Activate
src_path = co.Sheets(via).Cells(count, 1) ' path of source file (questionnaire)
source = "src.xlsx" ' name of source file (questionnaire)
src_feuil = co.Sheets(via).Cells(count, 3) ' name of source file sheet (questionnaire)
src_cell_address = co.Sheets(via).Cells(co.Sheets(via).Cells(count, 6).Value, co.Sheets(via).Cells(count, 7).Value).Address
'----- BDD COORDINATIONS
distination_Path = co.Sheets(via).Cells(count, 9) ' path of source file (questionnaire) 'bdd file path
distination = co.Sheets(via).Cells(count, 8) ' name of bdd file
distination_feuil = co.Sheets(via).Cells(count, 10) ' name of sheet of bdd file
distination_col_address = co.Sheets(via).Cells(count, 12)
MsgBox "col" & distination_col_address
If co.Sheets(via).Cells(count, 8) <> co.Sheets(via).Cells(count - 1, 8) Then
wrk.Save
wrk.Close
Set wrk = Nothing
Set wrk = Workbooks.Open(distination_Path & "\" & distination & ".xlsx")
last_dist_row = wrk.Sheets(distination_feuil).Cells(Rows.count, distination_col_address).End(xlUp).Row + 1 ' get the last empty row in BDD
'MsgBox "row" & last_dist_row
wrk.Sheets(distination_feuil).Cells(last_dist_row, distination_col_address) = GetValue(src_path, source, src_feuil, src_cell_address) 'get value
Else
'--------------------------OPEN
'last_dist_row =wrk.Sheets(distination_feuil).Range("A1").End(xlDown).Row + 1 get the last empty row in BDD
last_dist_row = wrk.Sheets(distination_feuil).Cells(Rows.count, distination_col_address).End(xlUp).Row + 1
wrk.Sheets(distination_feuil).Cells(last_dist_row, distination_col_address) = GetValue(src_path, source, src_feuil, src_cell_address) 'GET VALUE
End If
Next count
wrk.Save
wrk.Close
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.AskToUpdateLinks = True
End Sub
Private Function GetValue(path, file, sheet, ref)
'Retrieves a value from a closed workbook
Dim arg As String
' Make sure the file exists
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetValue = "File Not Found"
Exit Function
End If
' Create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)
' Execute an XLM macro
If ExecuteExcel4Macro(arg) = 0 Then
GetValue = ""
Else: GetValue = ExecuteExcel4Macro(arg)
End If
End Function

Related

How can my excel macro update and refresh pivot table

I am using the below code to copy files from a folder on my i drive into the correcposning worksheet in an excel workbook. After the files are copied in I have to manually update the pivot table data source and refresh each pivot table. Does anyone know how I could make this happen within the macro?
Sub Update_Data()
Dim fileNames(12) As String
Dim WorksheetNames(12) As String
Dim i As Integer
Dim currentFileName As String
fileNames(0) = "ActiveCount_L2_Report"
fileNames(1) = "Apps_Per_Agent_L2" 'does not end in report
'fileNames(2) = "Cancel_Count_L2_Report"
fileNames(2) = "Data_Active_L2_Report"
fileNames(3) = "NonRapidDisenroll_count_L2" 'does not end in report
fileNames(4) = "RapidDisenroll_count_L2" 'does not end in report
'fileNames(5) = "RTSPercentages_L2_Report"
fileNames(5) = "SOLD_ENROLLED_Count_L2_Report"
fileNames(6) = "Sold_Policy_Count_L2_Report"
fileNames(7) = "TOH_NAME_L2_Report"
fileNames(8) = "TOH_DATA_L2_Report"
fileNames(9) = "RTSPercentages_L2_2023" 'does not end in report
fileNames(10) = "RTS Distribution -Master Contact List" 'does not end in report
WorksheetNames(0) = "Active_Count_L2"
WorksheetNames(1) = "Apps_Per_Agent_L2"
'WorksheetNames(2) = "Cancel_Count_L2"
WorksheetNames(2) = "DATA_Active_L2"
WorksheetNames(3) = "NonRapidDisenroll_count_L2"
WorksheetNames(4) = "RapidDisenroll_count_L2"
'WorksheetNames(5) = "RTSPercentages_L2"
WorksheetNames(5) = "SOLD_ENROLLED_Count_L2"
WorksheetNames(6) = "Sold_Policy_Count_L2"
WorksheetNames(7) = "TOH_NAME_L2"
WorksheetNames(8) = "TOH_DATA_L2"
WorksheetNames(9) = "RTSPercentages_L2_2023"
WorksheetNames(10) = "Distribution List"
For i = 0 To 10
'….Groups is the name of the tab I need to update the data for….
'… assigning nameoffile variable as the current wb
Scorecard = ActiveWorkbook.Name
'putting the used range into a variable (# of rows used)
clear_range = Sheets(WorksheetNames(i)).Cells(Rows.Count, "A").End(xlUp).Row
'clear_range = Sheets("ActiveCount_L2").Cells(Rows.Count, "A").End(xlUp).Row
'.. If there's data in Groups tab (aside from the headers) then delete it out before bringing in new data
If clear_range > 1 Then
Sheets(WorksheetNames(i)).Range("A2:G" & clear_range).Delete
'Sheets("ActiveCount_L2").Range("A2:G" & clear_range).Delete
End If
'Path to folder where data file exists..
folderPath = "I:\Health Business Operations\Channel Service Organization\DARU\01 - Reporting Tools\Medicare Sales Agencies\LVL2 Scorecard Files"
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
'…add in name of data file here
'Filename = Dir(folderPath & "ActiveCount_L2_Report.xlsx*")
currentFileName = fileNames(i)
'Filename = Dir(folderPath & currentFileName)
Filename = folderPath & currentFileName
If i = 1 And i = 4 And i = 5 And i = 11 Then
Filename = Filename & "_Report"
End If
Filename = Filename & ".xlsx*"
Do While Filename <> ""
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
'open up data file
Set wb = Workbooks.Open(Filename)
'determine the used range
used_range = Cells(Rows.Count, "A").End(xlUp).Row
' Range("A6:B" & used_range & ",d6:d" & used_range).Copy
'copy over the used range (will need to specify columns, this file had data in cols A:F)..
Range("A2:AE" & used_range).Copy
'activate the original workbook (that this macro should be in..
Windows(Scorecard).Activate
'..determine used range in group tab (Should be 1 bc it was cleared out above). Using range +1 because we want to 'paste the data 1 row below already used range
used_range_gps = Sheets(WorksheetNames(i)).Cells(Rows.Count, "A").End(xlUp).Row + 1
'used_range_gps = Sheets("ActiveCount_L2").Cells(Rows.Count, "A").End(xlUp).Row + 1
'..pasting the data in the group tab at column A and whatever row the used_range_gps is
Sheets(WorksheetNames(i)).Range("A2:AE" & used_range_gps).PasteSpecial xlValues
'Sheets("ActiveCount_L2").Range("A2:AE" & used_range_gps).PasteSpecial xlValues
'Filename = Dir
wb.Close False
Filename = ""
Loop
Next i
End Sub

Merge and filter Multiple CSV files Excel VBA

With Excel VBA Code I would like to merge multiple CSV files (; separated) and filter them according to one Column 'Résultat'.
So far I can read inside a folder and loop through all files. but my final file (where everything is suppose to be merged, ThisWorkbook.Sheets(1)) is empty at the end :
Dim NameFull As String
Dim NameB As String
folder_path = "C:\blabla"
my_file = Dir(folder_path & "*.csv")
Do While my_file <> vbNullString
Set target_workbook = Workbooks.Open(folder_path & my_file)
RowsInFile = target_workbook.Sheets(1).UsedRange.Rows.Count
NumOfColumns = target_workbook.Sheets(1).UsedRange.Columns.Count
LastRow = ThisSheet.Cells(Rows.Count, "A").End(xlUp).Row
'target_workbook.Worksheets(1).Range("A1").CurrentRegion.Copy data_sheet.Cells(LastRow + 1, "A")
Set RangeToCopy = target_workbook.Sheets(1).Range(target_workbook.Sheets(1).Cells(RowsInFile, 1), target_workbook.Sheets(1).Cells(RowsInFile, NumOfColumns))
'Range("F1").Copy Destination:=Cells(last_row + 1, "A")
RangeToCopy.Copy Destination:=ThisWorkbook.Sheets(1).Cells(LastRow + 1, "A")
target_workbook.Close False
Set target_workbook = Nothing
my_file = Dir()
Loop
I need to save the final merged file in csv (; separated FileFormat:=xlCSV, Local:=True)
PS : Is it possible to only copy specific lines filtering on one column ?
Amend the constants as required. Merged rows saved to new workbook.
Update 1 Add new sheet if not enough space to paste records.
Option Explicit
Sub MergeCSVtoXLS()
Const FOLDER = "C:\temp\so\csv\"
Const FILTER_COL = 1 ' Résultat
Const FILTER_CRITERIA = ">99"
Dim wb As Workbook, wbCSV As Workbook
Dim ws As Worksheet, wsCSV As Worksheet
Dim CSVfile As String, XLSfile As String, LogFile As String
Dim rng As Range, rngCopy As Range, a
Dim TargetRow As Long, RowCount As Long
Dim n As Long, r As Long, i As Long
' open new workbook for merged results
Set wb = Workbooks.Add
Set ws = wb.Sheets(1)
TargetRow = 1
i = 1 ' sheet no
Application.ScreenUpdating = False
' log file
LogFile = FOLDER & Format(Now, "yyyymmdd_hhmmss") & ".log"
Open LogFile For Output As #1
Print #1, "Folder", FOLDER
Print #1, "Time", "n", "CSV File", "Rows", "Target Sht", "Target Row"
' csv files
CSVfile = Dir(FOLDER & "*.csv")
Do While Len(CSVfile) > 0
n = n + 1
Set wbCSV = Workbooks.Open(FOLDER & CSVfile, ReadOnly:=True, Local:=True)
Set wsCSV = wbCSV.Sheets(1)
Set rng = wsCSV.UsedRange
' filter and ropy
rng.AutoFilter Field:=FILTER_COL, Criteria1:=FILTER_CRITERIA
Set rngCopy = rng.Cells.SpecialCells(xlVisible)
' count rows to paste in each non-contig area
RowCount = 0 '
For Each a In rngCopy.Areas
RowCount = RowCount + a.Rows.Count
Next
r = r + RowCount - 1
' check space available on sheet
If TargetRow + RowCount > ws.Rows.Count Then
wb.Sheets.Add after:=wb.Sheets(i)
i = i + 1
Set ws = wb.Sheets(i)
TargetRow = 1
End If
' log file
Print #1, Time, n, CSVfile, RowCount, i, TargetRow
' copy paste values
rngCopy.Copy
ws.Cells(TargetRow, 1).PasteSpecial xlPasteValues
Application.CutCopyMode = False
wbCSV.Close savechanges:=False
' remove header unless first file
If TargetRow > 1 Then
ws.Rows(TargetRow).Delete ' header
End If
TargetRow = ws.Cells(Rows.Count, "A").End(xlUp).Row + 1
' next file
CSVfile = Dir()
Loop
Close #1
Application.ScreenUpdating = True
' save merged file
XLSfile = FOLDER & Format(Now, "yyyymmdd_hhmmss") & "_Merged.xls"
wb.SaveAs XLSfile, FileFormat:=xlExcel8, Local:=True ' .xls Excel 97-2003 Workbook
wb.Close savechanges:=False
MsgBox n & " Files scanned " & r & " Rows added to " & i & " Sheets" & vbLf _
& " Saved to " & XLSfile, vbInformation, "See log " & LogFile
End Sub

Loop Through Excel Files and See if a Specific Cell Is Blank

I inherited VBA code that has not worked since my work updated our version of Excel.
The original code looped through all Excel files in a specific folder.
If data in specific cells was blank or a 0, would rename the whole workbook so I would know what files to delete after the fact.
This is the original code. I don't need it to do all of this anymore.
This is part one:
Sub AllFilesWeekly()
Dim folderPath As String
Dim filename As String
Dim wb As Workbook
folderPath = "C:\Users\" & (Environ$("Username")) & "\Desktop\Process Production\" 'change to suit
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
filename = Dir(folderPath & "*.xlsx")
Do While filename <> ""
Application.ScreenUpdating = False
Set wb = Workbooks.Open(folderPath & filename)
'Call a subroutine here to operate on the just-opened workbook
Call getmetrics
On Error Resume Next
If Not ActiveWorkbook.Name Like "Audit Hub Report Distribution*" Then
ActiveWorkbook.Close
End If
filename = Dir
Loop
Application.ScreenUpdating = True
End Sub
The second part:
Sub getmetrics()
Dim cell As Range
Dim procstring As String, wbname As String
'Dim OQAYTD As String
Dim OQAMTD As String
Dim ORLYTD As String
Dim ORLMTD As String
Dim DR As String
Dim Audits As Long
Dim permonth As String, peryear As String, permonthrl As String, peryearrl As String
Dim RS As Worksheet, AD As Worksheet, QD As Worksheet, ws As Worksheet, YN As Boolean
For Each ws In Worksheets
If ws.Name = "Audit Detail" Then
YN = True
End If
Next ws
If YN = True Then
ActiveWorkbook.Sheets(2).Name = ("Rep Summary")
Set RS = ActiveWorkbook.Sheets("Rep Summary")
Set AD = ActiveWorkbook.Sheets("Audit Detail")
Set QD = ActiveWorkbook.Sheets("Question Detail")
With Sheets("Process Summary")
For Each cell In Range(Range("A3"), Range("A9999").End(xlUp))
If cell.Value = "Record Level YTD" Then
ORLYTD = Range(cell.Address).Offset(0, 1).Value
Else
If cell.Value = "YTD Quality Average" Then
OQAYTD = Range(cell.Address).Offset(0, 1).Value
Else
If cell.Value = "Record Level Quality Average" Then
ORLMTD = Range(cell.Address).Offset(0, 1).Value
Else
If cell.Value = "Quality Average" Then
OQAMTD = Range(cell.Address).Offset(0, 1).Value
Else
If cell.Value = "Audits" Then
Audits = Range(cell.Address).Offset(0, 1).Value
End If
End If
End If
End If
End If
Next cell
End With
wbname = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)
peryear = VBA.Format(OQAYTD, "Percent")
permonth = VBA.Format(OQAMTD, "Percent")
peryearrl = VBA.Format(ORLYTD, "Percent")
permonthrl = VBA.Format(ORLMTD, "Percent")
DR = Right(Sheets("Process Summary").Range("A2").Value, Len(Sheets("Process
Summary").Range("A2").Value) - 12)
RS.Range(RS.Range("A1"), RS.Range("IV1").End(xlToLeft)).AutoFilter
RS.Range(RS.Range("A1"), RS.Range("IV1").End(xlToLeft)).EntireColumn.AutoFit
AD.Range(AD.Range("A1"), AD.Range("IV1").End(xlToLeft)).AutoFilter
AD.Range(AD.Range("A1"), AD.Range("IV1").End(xlToLeft)).EntireColumn.AutoFit
QD.Range(QD.Range("A1"), QD.Range("IV1").End(xlToLeft)).AutoFilter
QD.Range(QD.Range("A1"), QD.Range("IV1").End(xlToLeft)).EntireColumn.AutoFit
Application.DisplayAlerts = False
procstring = wbname & "|" & permonth & "|" & Audits & "|" & peryear & "|" & permonthrl & "|" &
peryearrl & "|" & DR ' & "|" & Users
Debug.Print procstring
Else
Application.DisplayAlerts = False
Dim AWN As String
AWN = ActiveWorkbook.FullName
Debug.Print "Not Audited: " & ActiveWorkbook.Name
ActiveWorkbook.SaveAs "C:\Users\" & (Environ$("Username")) & "\Desktop\Process Production\Delete -" & Second(Now)
Kill AWN
ActiveWorkbook.Close savechanges:=True
Application.DisplayAlerts = True
End If
End Sub
All I need to do is look at cell D3 on the "Process Summary" tab.
If the value in that space is "0.00%", rename the workbook to delete and loop on until all workbooks are looked at.
I do not need to screen print all the extra numbers any more.
Build a Collection of filenames that match the criteria and then use it to rename the files.
Option Explicit
Sub AllFilesWeekly()
Dim folderPath As String, filename As String
Dim wb As Workbook, ws As Worksheet
Dim col As Collection, n As Long
Set col = New Collection
folderPath = "C:\Users\" & (Environ$("Username")) & "\Desktop\Process Production\" 'change to suit
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
' scan folder
filename = Dir(folderPath & "*.xlsx")
Do While filename <> ""
Set wb = Workbooks.Open(folderPath & filename, True, True) ' update links, readonly
For Each ws In wb.Sheets
If ws.Name = "Process Summary" Then
If Format(ws.Range("D3"), "0.00%") = "0.00%" Then
col.Add wb.Name
End If
End If
Next
wb.Close
n = n + 1
filename = Dir
Loop
' result
MsgBox "Files scanned = " & n & vbCrLf & _
"To delete = " & col.Count, vbInformation, folderPath
' rename
If col.Count > 0 Then
If MsgBox("Continue to rename ?", vbYesNo) = vbYes Then
For n = 1 To col.Count
Name folderPath & col(n) As folderPath & "delete_" & col(n)
Next
MsgBox "Rename done"
End If
End If
End Sub

Macro VBA, can't get "SaveAs" to function

I have a process that I run on sets of workbooks. I'm trying to modify the filetype when I close the file. I'm trying to tack it onto the end of the process before closing each workbook. Right now, the opened file is in .xlsb. I'm trying to save it in basically any other format (.xsls, etc.)
Whenever I run the Macro the "SaveAs" command errors out. I've tried everything I can think of to have it just save the file with the same name, different filetype, but no luck.
What am I doing wrong?
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Path = ThisWorkbook.Sheets(1).Range("H6")
If Right(Path, 1) <> "\" Then
Path = Path & "\"
End If
wsheet = ThisWorkbook.Sheets(1).Range("F10")
ThisWorkbook.Sheets(3).Range("A2:B20000").ClearContents
OutLn = 2
Line = 1
Do While ThisWorkbook.Sheets(2).Cells(Line, 1) <> ""
OpnFil = ThisWorkbook.Sheets(2).Cells(Line, 1)
Workbooks.Open fileName:=Path & OpnFil, UpdateLinks:=False
ScanLn = 12
Do While ThisWorkbook.Sheets(1).Cells(ScanLn, 5) <> ""
ThisWorkbook.Sheets(3).Cells(OutLn, 1) = OpnFil
Addr = ThisWorkbook.Sheets(1).Cells(ScanLn, 5)
ThisWorkbook.Sheets(3).Cells(OutLn, 2) = Workbooks(OpnFil).Sheets(wsheet).Range(Addr)
OutLn = OutLn + 1
ScanLn = ScanLn + 1
Loop
Workbooks(OpnFil).SaveAs fileName:=Workbooks(OpnFil).GetBaseName, FileFormat:=51
Workbooks(OpnFil).Close
Line = Line + 1
Loop
End Sub```
Backup Workbooks
Use variables to avoid (long) unreadable lines (parameters).
Option Explicit
Sub BackupWorkbooks()
Dim swb As Workbook: Set swb = ThisWorkbook
Dim dFolderPath As String: dFolderPath = swb.Sheets(1).Range("H6").Value
If Right(dFolderPath, 1) <> "\" Then
dFolderPath = dFolderPath & "\"
End If
Dim dwsName As String: dwsName = swb.Sheets(1).Range("F10").Value
Application.ScreenUpdating = False
swb.Sheets(3).Range("A2:B" & swb.Sheets(3).Rows.Count).ClearContents
Dim OutLn As Long: OutLn = 2
Dim Line As Long: Line = 1
Dim dwb As Workbook
Dim dOldName As String
Dim dOldPath As String
Dim dNewPath As String
Dim dAddr As String
Dim ScanLn As Long
Do While swb.Sheets(2).Cells(Line, 1) <> ""
dOldName = swb.Sheets(2).Cells(Line, 1)
dOldPath = dFolderPath & dOldName
Set dwb = Workbooks.Open(Filename:=dOldPath, UpdateLinks:=False)
ScanLn = 12
Do While swb.Sheets(1).Cells(ScanLn, 5).Value <> ""
swb.Sheets(3).Cells(OutLn, 1).Value = dOldName
dAddr = swb.Sheets(1).Cells(ScanLn, 5).Value
swb.Sheets(3).Cells(OutLn, 2).Value _
= dwb.Worksheets(dwsName).Range(dAddr).Value
OutLn = OutLn + 1
ScanLn = ScanLn + 1
Loop
dNewPath = Left(dOldPath, InStrRev(dOldPath, ".") - 1) & ".xlsx"
' Or if you insist:
'dNewPath = dFolderPath & CreateObject("Scripting.FileSystemObject") _
.GetBaseName(dOldName) & ".xlsx"
Application.DisplayAlerts = False
dwb.SaveAs Filename:=dNewPath, FileFormat:=xlOpenXMLWorkbook ' 51
Application.DisplayAlerts = True
dwb.Close
Line = Line + 1
Loop
Application.ScreenUpdating = True
MsgBox "Backups created.", vbInformation, "Backup Workbooks"
End Sub

How to auto populate a single spreadsheet from multiple spreadsheets

I have a set of Excel spreadsheets to summarise. My sheets are numbered:
xxx-yy-zzzz; xxx-yy-zzz+1; etc.
I would like a reporting spreadsheet to retrieve information each time it is opened. I don't mind doing it with VBA or with formulae.
I've the macro below. I need to auto increment until it runs out of spreadsheets. All the files will be in the same folder, this file can be in any folder.
Sub Macro1()
'
' Macro1 Macro
' autopop
'
'
Range("C4").Select
ActiveCell.FormulaR1C1 = "='[413-05-001.xlsx]Cover'!R4C5"
Range("D4").Select
ActiveCell.FormulaR1C1 = "='[413-05-001.xlsx]Cover'!R5C3"
Range("E4").Select
ActiveCell.FormulaR1C1 = "='[413-05-001.xlsx]Order'!R27C9"
Range("F4").Select
ActiveCell.FormulaR1C1 = "='[413-05-001.xlsx]Cover'!R8C9"
End Sub
Siddharth's method above worked very well for when we were using very simple file names, but it got a lot harder when there were additions made to the filename... So i did some surfing and found a basis of a "list all files and put them in a worksheet" and using some of the code from Siddharth's answer above (thank you very much Mr. Siddharth) and the example i found online here http://alanmurray.blogspot.com/2013/08/excel-vba-list-all-excel-files-in-folder.html , i have finalised my code, and my little VBA app now does what i want - it opens a folder and goes through and pulls out particular cells and creates a summary report in seconds -> will save me hours of tedious work...
Code:
Sub ImportFileList()
Dim MyFolder As String 'Store the folder selected by the using
Dim FiletoList As String 'store the name of the file ready for listing
Dim NextRow As Long 'Store the row to write the filename to
On Error Resume Next
Application.ScreenUpdating = False
'Display the folder picker dialog box for user selection of directory
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then
MsgBox "You did not select a folder"
Exit Sub
End If
MyFolder = .SelectedItems(1) & "\"
End With
'Dir finds the first Excel workbook in the folder
FiletoList = Dir(MyFolder & "*.xls")
Range("A1").Value = "Filename"
Range("B1").Value = "Purchase Order Number"
Range("C1").Value = "Vendor"
Range("D1").Value = "Date of PO"
Range("E1").Value = "Currency"
Range("F1").Value = "Subtotal"
Range("G1").Value = "VAT"
Range("H1").Value = "Total"
Range("A1:H1").Font.Bold = True
'Find the next empty row in the list
NextRow = Application.CountA(Range("A:A")) + 1
NextRow = NextRow + 1 ' skip a line
'Do whilst the dir function returns an Excel workbook
Do While FiletoList <> ""
Cells(NextRow, 1).Value = FiletoList 'Write the filename into the next available cell
Cells(NextRow, 2).Formula = "='[" & FiletoList & "]Cover'!R4C4" ' Cover is the excel sheet name
Cells(NextRow, 3).Formula = "='[" & FiletoList & "]Cover'!R6C3"
Cells(NextRow, 4).Formula = "='[" & FiletoList & "]Cover'!R4C7"
Cells(NextRow, 5).Formula = "='[" & FiletoList & "]Cover'!R21C4"
Cells(NextRow, 6).Formula = "='[" & FiletoList & "]Cover'!R19C5"
Cells(NextRow, 7).Formula = "='[" & FiletoList & "]Cover'!R20C5"
Cells(NextRow, 8).Formula = "='[" & FiletoList & "]Cover'!R21C5"
NextRow = NextRow + 1 'Move to next row
FiletoList = Dir 'Dir returns the next Excel workbook in the folder
Loop
Application.ScreenUpdating = True
End Sub
Is this what you are trying? (UNTESTED)
'~~> Change this to the directory which has .xlsx files
Const sDir = "C:\Temp\"
Sub Sample()
Dim ws As Worksheet
Dim i As Long, num As Long, Calcmode As Long
Dim FilesCount As Long, startNum As Long
On Error GoTo Whoa
Set ws = ThisWorkbook.Sheets("Sheet1")
With Application
.ScreenUpdating = False
Calcmode = .Calculation
.Calculation = xlCalculationManual
End With
'~~> Get the number of files in that directory
FilesCount = getFileCount(sDir)
startNum = 1
If FilesCount <> 0 Then
With ws
For i = 4 To (FilesCount + 3)
num = Format(startNum, "000")
.Range("C" & i).Formula = "='[413-05-" & num & ".xlsx]Cover'!R4C5"
.Range("D" & i).Formula = "='[413-05-" & num & ".xlsx]Cover'!R5C3"
.Range("E" & i).Formula = "='[413-05-" & num & ".xlsx]Order'!R27C9"
.Range("F" & i).Formula = "='[413-05-" & num & ".xlsx]Cover'!R8C9"
startNum = startNum + 1
Next i
End With
End If
LetsContinue:
With Application
.ScreenUpdating = True
.Calculation = Calcmode
End With
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
Function getFileCount(s As String) As Long
Dim Path As String, Filename As String
Dim Count As Long
Path = s & "*.xlsx"
Filename = Dir(Path)
Do While Filename <> ""
Count = Count + 1
Filename = Dir()
Loop
getFileCount = Count
End Function

Resources