How to insert and offset an image based on cell value - excel

I'm facing a bit of an issue.
We needed to make a small, single cell, change to about a 1000 client statements (excel). I ran the change in python using openpyxl and all the company logos disappeared.
I have compiled a VBA to put the images back but am struggling with getting them in the right position on the second page as the top of the second page is not a set row number.
However, the clients name marks the top of the second page.
Is there a way I can search column B for the clients name and insert the companies logo in the same row but 9 columns to the right.
This is what I have so far:
Sub Example()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String, Fnum As Long
Dim mybook As Workbook
Dim CalcMode As Long
Dim sh As Worksheet
Dim ErrorYes As Boolean
'Fill in the path\folder where the files are
MyPath = "Path\to\excels"
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'If there are no Excel files in the folder exit the sub
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
'Fill the array(myFiles)with the list of Excel files in the folder
Fnum = 0
Do While FilesInPath <> ""
Fnum = Fnum + 1
ReDim Preserve MyFiles(1 To Fnum)
MyFiles(Fnum) = FilesInPath
FilesInPath = Dir()
Loop
'Change ScreenUpdating, Calculation and EnableEvents
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
'Loop through all files in the array(myFiles)
If Fnum > 0 Then
For Fnum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
On Error GoTo 0
If Not mybook Is Nothing Then
'Change cell value(s) in one worksheet in mybook
On Error Resume Next
With mybook.ActiveSheet.Pictures.Insert("C:Path\to\Pic.jpg")
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = 40
.Height = 55
End With
.Left = ActiveSheet.Range("K1").Left
.Top = ActiveSheet.Range("K1").Top
.Placement = 1
.PrintObject = True
End With
With ActiveSheet.Range("B12:L13").BorderAround(ColorIndex:=xlAutomatic, Weight:=xlMedium)
End With
If Err.Number > 0 Then
ErrorYes = True
Err.Clear
'Close mybook without saving
mybook.Close savechanges:=False
Else
'Save and close mybook
mybook.Close savechanges:=True
End If
On Error GoTo 0
Else
'Not possible to open the workbook
ErrorYes = True
End If
Next Fnum
End If
If ErrorYes = True Then
MsgBox "There are problems in one or more files, possible problem:" _
& vbNewLine & "protected workbook/sheet or a sheet/range that not exist"
End If
'Restore ScreenUpdating, Calculation and EnableEvents
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub

You could use:
Option Explicit
Sub image()
Dim i As Long, Lastrow As Long
Dim pic As Picture
Dim rng As Range
With ThisWorkbook.Worksheets("Sheet1")
Lastrow = .Cells(.Rows.Count, "O").End(xlUp).Row
For i = 1 To Lastrow
If .Range("O" & i).Value = "Import" Then
Set rng = .Range("O" & i).Offset(0, -9)
With .Pictures.Insert("C:\Users\XXXXX\Desktop\download.jpg")
.Top = rng.Top
.Left = rng.Left
End With
End If
Next i
End With
End Sub

Related

Unmerging all Cells in Many Workbooks in Certain Folder Path

Here is the code am using but unfortunately its not working
am using excel 365 and windows 10
it gets stuck on excel interface with no errors showing and no action or processing and no file is open
Please help me find a solution or provide me with a ready made Excel VBA macro for doing the same task as I a use an old erp that exports its reports into htm then i convert them into excel and then have to merge all cells in order to work with them efficiently.
Sub UnmergeAllCellsinWorkbooksinOneFolder()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String, Fnum As Long
Dim mybook As Workbook
Dim CalcMode As Long
Dim sh As Worksheet
Dim ErrorYes As Boolean
'Fill in the path\folder where the files are
MyPath = "F:\Sales Rates"
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'If there are no Excel files in the folder exit the sub
FilesInPath = Dir(MyPath & "*.xlsx*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
'Fill the array(myFiles)with the list of Excel files in the folder
Fnum = 0
Do While FilesInPath <> ""
Fnum = Fnum + 1
ReDim Preserve MyFiles(1 To Fnum)
MyFiles(Fnum) = FilesInPath
FilesInPath = Dir()
Loop
'Change ScreenUpdating, Calculation and EnableEvents
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
'Loop through all files in the array(myFiles)
If Fnum > 0 Then
For Fnum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
On Error GoTo 0
If Not mybook Is Nothing Then
'Change cell value(s) in one worksheet in mybook
On Error Resume Next
With mybook.Worksheets(1)
sh.Cells.MergeCells = False
End With
If Err.Number > 0 Then
ErrorYes = True
Err.Clear
'Close mybook without saving
mybook.Close savechanges:=False
Else
'Save and close mybook
mybook.Close savechanges:=True
End If
On Error GoTo 0
Else
'Not possible to open the workbook
ErrorYes = True
End If
Next Fnum
End If
If ErrorYes = True Then
MsgBox "There are problems in one or more files, possible problem:" _
& vbNewLine & "protected workbook/sheet or a sheet/range that not exist"
End If
'Restore ScreenUpdating, Calculation and EnableEvents
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
sh is nothing. I think it should be fixed as below.
With mybook.Worksheets(1)
'sh.Cells.MergeCells = False
.Cells.MergeCells = False
End With

finding values from several workbooks using the directory

I want to copy data from several workbooks
the directory of the workbooks have order like this
c:\sheets\#number #month\worksheet #date
I would like to copy the same range in all workbooks
The month format is MMM
The date format us DD-MMM-YYYY
This will do what you want.
Sub Example()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String, Fnum As Long
Dim mybook As Workbook
Dim CalcMode As Long
Dim sh As Worksheet
Dim ErrorYes As Boolean
'Fill in the path\folder where the files are
MyPath = "C:\your_path_here\"
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'If there are no Excel files in the folder exit the sub
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
'Fill the array(myFiles)with the list of Excel files in the folder
Fnum = 0
Do While FilesInPath <> ""
Fnum = Fnum + 1
ReDim Preserve MyFiles(1 To Fnum)
MyFiles(Fnum) = FilesInPath
FilesInPath = Dir()
Loop
'Change ScreenUpdating, Calculation and EnableEvents
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
'Loop through all files in the array(myFiles)
If Fnum > 0 Then
For Fnum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
On Error GoTo 0
If Not mybook Is Nothing Then
' do your copy process here ...
If Err.Number > 0 Then
ErrorYes = True
Err.Clear
'Close mybook without saving
mybook.Close savechanges:=False
Else
'Save and close mybook
mybook.Close savechanges:=True
End If
On Error GoTo 0
Else
'Not possible to open the workbook
ErrorYes = True
End If
Next Fnum
End If
If ErrorYes = True Then
MsgBox "There are problems in one or more files, possible problem:" _
& vbNewLine & "protected workbook/sheet or a sheet/range that not exist"
End If
'Restore ScreenUpdating, Calculation and EnableEvents
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
https://www.rondebruin.nl/win/s3/win010.htm

Copy multiple workbooks and paste in a single sheet

I have multiple workbooks with same columns and I need to consolidate it to one single sheet with the column names to be copied only once.
Couldn't find a comprehensive solution. Please hep.
Try the below, you will have to adjust this to your needs.
in nutshell, you need the below steps
Get the folder location you have the sheets
get xl files that you are interested , with a specific name etc
for each of these files, and for each sheet in these files
3a. copy the cells to the last filled row
3b. paste in the target, from the first empty row.
Test
Option Explicit
Sub LoopAllExcelflesInFolder()
Dim wb As Workbook
Dim target As Worksheet
Dim flePath As String
Dim fle As String
Dim fleDlg As fleDialog
Dim ws As Worksheet
Dim firstEmptyRowTarget As Long
Dim lastRowSource As Long
Dim RangeToMove As Range
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'get folder loc from the user
Set fleDlg = Application.fleDialog(msofleDialogFolderPicker)
With fleDlg
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo nxt 'in case cancelled get to next block
flePath = .SelectedItems(1) & "\"
End With
nxt:
flePath = flePath
If flePath = "" Then GoTo closeandgo
Set target = ActiveWorkbook.Sheets("Sheet1") 'change your target here
fle = Dir(flePath & "*.xls*")
LRDest = 1 '(assuming starting row is 1)
Do While fle <> ""
Set wb = Workbooks.Open(flename:=flePath & fle)
'' for each worsheet , copy the contents / include your logic here if the sheet has a specific name/pattern etc. assuming the column headers are the same
For Each ws In wb.Sheets
lastRowSource = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row ' find the last row in the source
Set RangeToMove = ws.Range("A1:AJ" & LRSrc) 'Change the columns you want to copy here
RangeToMove.Copy target.Cells(firstEmptyRowTarget, 1)
firstEmptyRowTarget = target.Cells(target.Rows.Count, 1).End(xlUp).Row + 1 ''Save the last row in the target after copyin
Next
DoEvents
'Get next fle name
fle = Dir
Loop
MsgBox "done..."
closeandgo:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
I see these types of questions come up every once in a while. There are a few ways you could go with this. Try the code below, and see how you get along. Post back if you have additional questions.
Sub Basic_Example_1()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String
Dim SourceRcount As Long, Fnum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim rnum As Long, CalcMode As Long
'Fill in the path\folder where the files are
MyPath = "C:\Users\Ron\test"
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'If there are no Excel files in the folder exit the sub
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
'Fill the array(myFiles)with the list of Excel files in the folder
Fnum = 0
Do While FilesInPath <> ""
Fnum = Fnum + 1
ReDim Preserve MyFiles(1 To Fnum)
MyFiles(Fnum) = FilesInPath
FilesInPath = Dir()
Loop
'Change ScreenUpdating, Calculation and EnableEvents
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
'Add a new workbook with one sheet
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
rnum = 1
'Loop through all files in the array(myFiles)
If Fnum > 0 Then
For Fnum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
With mybook.Worksheets(1)
Set sourceRange = .Range("A1:C1")
End With
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
Else
'if SourceRange use all columns then skip this file
If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
Set sourceRange = Nothing
End If
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
SourceRcount = sourceRange.Rows.Count
If rnum + SourceRcount >= BaseWks.Rows.Count Then
MsgBox "Sorry there are not enough rows in the sheet"
BaseWks.Columns.AutoFit
mybook.Close savechanges:=False
GoTo ExitTheSub
Else
'Copy the file name in column A
With sourceRange
BaseWks.cells(rnum, "A"). _
Resize(.Rows.Count).Value = MyFiles(Fnum)
End With
'Set the destrange
Set destrange = BaseWks.Range("B" & rnum)
'we copy the values from the sourceRange to the destrange
With sourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = sourceRange.Value
rnum = rnum + SourceRcount
End If
End If
mybook.Close savechanges:=False
End If
Next Fnum
BaseWks.Columns.AutoFit
End If
ExitTheSub:
'Restore ScreenUpdating, Calculation and EnableEvents
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
https://www.rondebruin.nl/win/s3/win008.htm

How To Merge different workbooks with same structure in to one using dynamic Range

I have multiple work books with one sheet each all with the same structure would like to merge these in to one workbook found some examples on the net but been unable to achieve what I want this code I have will create the merge but it only picks one column. I would like to copy the entire used range starting from a point eg "A2" have tried a couple here is what I tried the commented lines are what I have tried and did not work any suggestions welcome please
Sub Trymerge()
Dim FolderPath As String, Path As String, count As Integer
Dim ThisWB As String, lngFilecounter As Long
Dim wbDest As Workbook, shtDest As Worksheet, ws As Worksheet
Dim Filename As String, Wkb As Workbook
Dim CopyRng As Range, Dest As Range
Dim RowofCopySheet As Integer
ThisWB = ActiveWorkbook.Name
FolderPath = "H:\Staging\Testmerge"
' path = FolderPath & "\*.xls*"
'Filename = Dir(path)
Filename = Dir(FolderPath & "\*.xls*", vbNormal)
MsgBox Filename
RowofCopySheet = 11
Application.EnableEvents = False
Application.ScreenUpdating = False
Set shtDest = ActiveWorkbook.Sheets(1)
Do While Filename <> ""
MsgBox Filename
count = count + 1
If Not Filename = ThisWB Then
Set Wkb = Workbooks.Open(Filename:=FolderPath & "\" & Filename)
MsgBox "working file" & Filename
Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(Cells(Rows.count, 1).End(xlUp).Row, Cells(1, Columns.count).End(xlToLeft).Column))
'Wkb.Sheets(1).Range("A11").Select
' Set CopyRng = Wkb.Sheets(1).Range(RowofCopySheet, ActiveCell.End(xlDown).End(xlToRight))
'Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(.UsedRange.Rows.count, .UsedRange.Columns.count))
Set Dest = shtDest.Range("A" & shtDest.Cells(Rows.count, 1).End(xlUp).Row + 1)
CopyRng.Copy
Dest.PasteSpecial xlPasteFormats
Dest.PasteSpecial xlPasteValuesAndNumberFormats
Application.CutCopyMode = False 'Clear Clipboard
Wkb.Close False
End If
Filename = Dir()
Loop
' Range("Q8").Value = count
MsgBox count & " : files found in folder"
End Sub
This is the script that I use to loop through a folder, copy data out of all files, and then save that data into a combined spreadsheet located elsewhere. You'll need to change myPath to the path to your file folder, change the i variable to the range you need, and the j variable to the location/range of your combined spreadsheet.
Sub CombineReports()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim i As Long
Dim j As Long
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.CutCopyMode = False
'Target Folder Path For Macro
myPath = "I:\Pricing\mt access\Tier Reports\Final Reports\"
'In Case of Cancel
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Loop through each Excel file in folder
myFile = Dir(myPath)
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
DoEvents
'Count rows in your spreadsheet and set range to copy
i = wb.Worksheets(1).Range("A" & Rows.Count).End(xlUp).Row
wb.Worksheets(1).Range("A5", "N" & i).Copy
'Combine data from each spreadsheet into one main sheet
With Workbooks.Open("I:\Pricing\mt access\Tier Reports\Final Reports\Combined Report\CombinedTierReport.xlsx")
DoEvents
j = Workbooks("CombinedTierReport.xlsx").Worksheets("AllStores").Range("B" & Rows.Count).End(xlUp).Row
Workbooks("CombinedTierReport.xlsx").Worksheets("AllStores").Range("A" & j + 1).PasteSpecial xlPasteValues
Workbooks("CombinedTierReport.xlsx").Save
Workbooks("CombinedTierReport.xlsx").Close
End With
DoEvents
'Save and Close Workbook
Application.DisplayAlerts = False
wb.Close SaveChanges:=False
Application.DisplayAlerts = True
DoEvents
'Get next file name
myFile = Dir
Loop
'Reset Macro Optimization Settings
ResetSettings:
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.CutCopyMode = True
End Sub
If your code is already working you can just change your code as below:
Code you have:
Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(Cells(Rows.count, 1).End(xlUp).Row, Cells(1, Columns.count).End(xlToLeft).Column))
You can make it slightly more simple by changing your copyrange:
Assuming the Column A goes to the bottom of your sheet and Assuming the first Row goes to the last Column of your sheet
Dim LastRow As Long
Dim LastCol As Long
LastRow = Range("A" & Rows.Count).End(xlUp).Row
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column
Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(LastRow, LastCol))
With this the CopyRng will take your whole Range and not only the last column.
You can easily merge data from all workbooks in a folder (below each other).
Sub Basic_Example_1()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String
Dim SourceRcount As Long, Fnum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim rnum As Long, CalcMode As Long
'Fill in the path\folder where the files are
MyPath = "C:\Users\Ron\test"
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'If there are no Excel files in the folder exit the sub
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
'Fill the array(myFiles)with the list of Excel files in the folder
Fnum = 0
Do While FilesInPath <> ""
Fnum = Fnum + 1
ReDim Preserve MyFiles(1 To Fnum)
MyFiles(Fnum) = FilesInPath
FilesInPath = Dir()
Loop
'Change ScreenUpdating, Calculation and EnableEvents
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
'Add a new workbook with one sheet
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
rnum = 1
'Loop through all files in the array(myFiles)
If Fnum > 0 Then
For Fnum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
With mybook.Worksheets(1)
Set sourceRange = .Range("A1:C1")
End With
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
Else
'if SourceRange use all columns then skip this file
If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
Set sourceRange = Nothing
End If
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
SourceRcount = sourceRange.Rows.Count
If rnum + SourceRcount >= BaseWks.Rows.Count Then
MsgBox "Sorry there are not enough rows in the sheet"
BaseWks.Columns.AutoFit
mybook.Close savechanges:=False
GoTo ExitTheSub
Else
'Copy the file name in column A
With sourceRange
BaseWks.cells(rnum, "A"). _
Resize(.Rows.Count).Value = MyFiles(Fnum)
End With
'Set the destrange
Set destrange = BaseWks.Range("B" & rnum)
'we copy the values from the sourceRange to the destrange
With sourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = sourceRange.Value
rnum = rnum + SourceRcount
End If
End If
mybook.Close savechanges:=False
End If
Next Fnum
BaseWks.Columns.AutoFit
End If
ExitTheSub:
'Restore ScreenUpdating, Calculation and EnableEvents
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
If, for some reason, you wanted to do the merge and have the data sets arranged horizontally, instead of vertically, you could use the script below.
Sub Basic_Example_3()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String
Dim SourceCcount As Long, Fnum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim Cnum As Long, CalcMode As Long
'Fill in the path\folder where the files are
MyPath = "C:\Users\Ron\test"
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'If there are no Excel files in the folder exit the sub
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
'Fill the array(myFiles)with the list of Excel files in the folder
Fnum = 0
Do While FilesInPath <> ""
Fnum = Fnum + 1
ReDim Preserve MyFiles(1 To Fnum)
MyFiles(Fnum) = FilesInPath
FilesInPath = Dir()
Loop
'Change ScreenUpdating, Calculation and EnableEvents
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
'Add a new workbook with one sheet
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
Cnum = 1
'Loop through all files in the array(myFiles)
If Fnum > 0 Then
For Fnum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
Set sourceRange = mybook.Worksheets(1).Range("A1:A10")
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
Else
'if SourceRange use all rows then skip this file
If sourceRange.Rows.Count >= BaseWks.Rows.Count Then
Set sourceRange = Nothing
End If
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
SourceCcount = sourceRange.Columns.Count
If Cnum + SourceCcount >= BaseWks.Columns.Count Then
MsgBox "Sorry there are not enough columns in the sheet"
BaseWks.Columns.AutoFit
mybook.Close savechanges:=False
GoTo ExitTheSub
Else
'Copy the file name in the first row
With sourceRange
BaseWks.cells(1, Cnum). _
Resize(, .Columns.Count).Value = MyFiles(Fnum)
End With
'Set the destrange
Set destrange = BaseWks.cells(2, Cnum)
'we copy the values from the sourceRange to the destrange
With sourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = sourceRange.Value
Cnum = Cnum + SourceCcount
End If
End If
mybook.Close savechanges:=False
End If
Next Fnum
BaseWks.Columns.AutoFit
End If
ExitTheSub:
'Restore ScreenUpdating, Calculation and EnableEvents
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub

Grabbing data from all sheets in given directory

I am trying to create a macro that will grab information from all sheets in all workbook(s) located in a specific directory. I am a VBA newbie, so I'm basically limited to what I can copy or modify with extremely limited programming knowledge. I have been trying to modify the macro I got off a website below.
How would I modify the SearchValue line to filter any date in general? Would I have to create a new variable? Also, how would modify the ShName line to scan every single sheet in the workbooks?
Sub ConsolidateErrors()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String
Dim SourceRcount As Long, FNum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim rnum As Long, CalcMode As Long
Dim rng As Range, SearchValue As String
Dim FilterField As Integer, RangeAddress As String
Dim ShName As Variant, RwCount As Long
MyPath = "C:\Documents and Settings\user\Desktop\New Folder"
ShName = 1
RangeAddress = Range("A1:N" & Rows.Count).Address
FilterField = 1
SearchValue = "10/21/2010"
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
FNum = 0
Do While FilesInPath <> ""
FNum = FNum + 1
ReDim Preserve MyFiles(1 To FNum)
MyFiles(FNum) = FilesInPath
FilesInPath = Dir()
Loop
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
rnum = 1
If FNum > 0 Then
For FNum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(FNum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
With mybook.Worksheets(ShName)
Set sourceRange = .Range(RangeAddress)
End With
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
rnum = RDB_Last(1, BaseWks.Cells) + 1
With sourceRange.Parent
Set rng = Nothing
.AutoFilterMode = False
sourceRange.AutoFilter Field:=FilterField, _
Criteria1:=SearchValue
With .AutoFilter.Range
RwCount = .Columns(1).Cells. _
SpecialCells(xlCellTypeVisible).Cells.Count - 1
If RwCount = 0 Then
Else
Set rng = .Resize(.Rows.Count - 1, .Columns.Count). _
Offset(1, 0).SpecialCells(xlCellTypeVisible)
If rnum + RwCount < BaseWks.Rows.Count Then
rng.Copy BaseWks.Cells(rnum, "A")
End If
End If
End With
.AutoFilterMode = False
End With
End If
mybook.Close savechanges:=False
End If
Next FNum
BaseWks.Columns.AutoFit
MsgBox "Look at the merge results in the new workbook after you click on OK"
End If
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
You can use the InputBox() method to grab data from the user when the code is run. Here is a simple example:
Option Explicit
Sub test()
Dim SearchValue As String
SearchValue = InputBox("Enter Date", "Date, please")
If (SearchValue = "") Then Exit Sub ' case when "Cancel" or nothing is entered
If (IsDate(SearchValue) = False) Then
MsgBox "Sorry, that is not a valid date."
Exit Sub
End If
' Do other stuff
End Sub
Here is some documentation from Microsoft:
http://msdn.microsoft.com/en-us/library/office/aa195768(v=office.11).aspx
To answer the 2nd question you had Also, how would modify the ShName line to scan every single sheet in the workbooks?
Try this syntax ...
Dim wks as Worksheet
For each wks in myBook.Worksheets
'run code here
Next
Your above code will need a bit of tweaking to make sure it's referencing the right sheet each time and such, but that wks variable will help tremendously.

Resources