Simple Copy Paste within a workbook matching program - excel

This program prompts the users to select to folders. In one folder is the data to be copied, in the other the destination files. The files share a naming structure of 4 digit numbers "el numbers".
Everything in this code is working, except for selecting the data, copying it, and pasting it to the destination folder.
Currently, it is notifying me that I have successfully matched up the files, and that both are open. I've confirmed that the matches are correct and the correct files are open. The close and save functions are currently commented out.
I just can't seem to get the code to select the sheets at all. I've been trying to do a simple clearcontents using the code below and that didn't work either.
Set myDatabook = ActiveWorkbook
ActiveWorkbook.Worksheets(1).Range("A1").ClearContents
The most relevant code to the question is between lines of %%%%%%%%%, but all of it is included for troubleshooting.
Sub OPDwgUpdateFromMatchingSheetsELNumber()
Dim CalcMode As Long
Dim sh As Worksheet
Dim ErrorYes As Boolean
' /////////////////// all OP Dwg opening and checks only\\\\\\\\\\\\\\\\\\\\\\\\
Dim MyOPDwgPath As String
Dim OPDwgCheckSheet As Worksheet
Dim FilesInPathOPDwg As String
Dim MyOPDwgFiles() As String, FnumOPDwg As Long 'dim () string means array , the comma means the FnumOPDwg is used with it
Dim myOPdwgbook As Workbook
Dim elNumOpDwg As String`enter code here`
Dim elNumOPDwgArray() As String, FnumEL As Long
MyOPDwgPath = GetOPDwgFolders() ' call getOPDwgFolder functoin
MsgBox (MyOPDwgPath) 'returns in msg box
'Add a slash at the end if the user forget it
If Right(MyOPDwgPath, 1) <> "\" Then
MyOPDwgPath = MyOPDwgPath & "\"
End If
FilesInPathOPDwg = Dir(MyOPDwgPath & "*.xl*")
If FilesInPathOPDwg = "" Then 'If there are no Excel files in the folder exit the sub
MsgBox "No files found"
Exit Sub
End If
'Fill the array(myFiles)with the list of Excel files in the folder
FnumOPDwg = 0
Do While FilesInPathOPDwg <> ""
FnumOPDwg = FnumOPDwg + 1
ReDim Preserve MyOPDwgFiles(1 To FnumOPDwg)
MyOPDwgFiles(FnumOPDwg) = FilesInPathOPDwg
FilesInPathOPDwg = Dir()
elNumOpDwg = Right(Left(MyOPDwgFiles(FnumOPDwg), 7), 4) 'parse out just el num **MAY HAVE TO BE CHANGED IF NAMING CONVENTION CHANGES**
ReDim Preserve elNumOPDwgArray(1 To FnumOPDwg)
elNumOPDwgArray(FnumOPDwg) = elNumOpDwg
'Debug.Print (elNumOpDwg & " " & FnumOPDwg) 'print in debugging window press control + G to open
Loop
'Debug.Print (elNumOPDwgArray(3))
' //////////// data sheet check \\\\\\\\\\\\\\\\\\\\\
'Data
Dim myDataPath As String
Dim myDatabook As Workbook
Dim myDataCheckSheet As Worksheet
Dim MyDataFiles() As String, FnumData As Long ' array of data file
Dim FilesInPathData As String 'location of data files
Dim elNumDataSheet As String 'elNum parse from data file name
Dim elNumDataArray() As String, FnumDataEL As Long
myDataPath = GetDataFolders()
MsgBox (myDataPath)
'Add a slash at the end if the user forget it
If Right(myDataPath, 1) <> "\" Then
myDataPath = myDataPath & "\"
End If
'If there are no Excel files in the folder exit the sub
FilesInPathData = Dir(myDataPath & "*.xl*")
If FilesInPathData = "" Then
MsgBox "No files found"
Exit Sub
End If
'Fill the array(myFiles)with the list of Excel files in the folder
FnumData = 0
Do While FilesInPathData <> ""
FnumData = FnumData + 1
ReDim Preserve MyDataFiles(1 To FnumData)
MyDataFiles(FnumData) = FilesInPathData
FilesInPathData = Dir()
elNumDataSheet = Right(Left(MyDataFiles(FnumData), 7), 4)
ReDim Preserve elNumDataArray(1 To FnumData)
elNumDataArray(FnumData) = elNumDataSheet
Loop
'/////////////////////end data retrieval\\\\\\\\\\\\\\\\
'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 FnumOPDwg > 0 Then
For FnumOPDwg = LBound(MyOPDwgFiles) To UBound(MyOPDwgFiles)
Set myOPdwgbook = Nothing
On Error Resume Next
Set myOPdwgbook = Workbooks.Open(MyOPDwgPath & MyOPDwgFiles(FnumOPDwg))
'Debug.Print (MyOPDwgPath)
'Debug.Print (MyOPDwgFiles(FnumOPDwg) & "1")
On Error GoTo 0
For FnumData = LBound(MyDataFiles) To UBound(MyDataFiles)
If FnumData > 0 Then
If elNumDataArray(FnumData) = elNumOPDwgArray(FnumOPDwg) Then
Set myDatabook = Nothing
On Error Resume Next
Set myDatabook = Workbooks.Open(myDataPath & MyDataFiles(FnumData))
On Error GoTo 0
'Debug.Print (FilesInPathData)
'Debug.Print (MyDataFiles(FnumData) & "2")
MsgBox (elNumDataArray(FnumData))
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
If Not myOPdwgbook Is Nothing Then
'Change cell value(s) in one worksheet in mybook
On Error Resume Next
With myOPdwgbook.Worksheets(1)
With myDatabook.Worksheets(1)
If .ProtectContents = False Then
' actual copy pasting done here
myDatabook.Range("A1:DE31").Value = myOPdwgbook.Cells("A59:DE90").Value
Else
ErrorYes = True
End If
End With
End With
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
If Err.Number > 0 Then
ErrorYes = True
Err.Clear
' myDatabook.Close savechanges:=False
Else
' myDatabook.Close savechanges:=False
End If
On Error GoTo 0
Else
'Not possible to open the workbook
ErrorYes = True
End If
End If
If Err.Number > 0 Then
ErrorYes = True
Err.Clear
'myOPdwgbook.Close savechanges:=False 'Close mybook without saving
Else
'myOPdwgbook.Close savechanges:=True
End If
On Error GoTo 0
End If
Next FnumData
Next FnumOPDwg 'iterate
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

The use of On Error Resume Next should be used sparingly and always be terminated by On Error Goto 0 (which you do). However, the lines:
On Error Resume Next
Set myDatabook = Workbooks.Open(myDataPath & MyDataFiles(FnumData))
On Error GoTo 0
should be followed by a check that myDatabook is properly assigned. If it is not the line:
myDatabook.Range("A1:DE31").Value = myOPdwgbook.Cells("A59:DE90").Value
will definitely cause an error.
Without analyzing your code I strongly suggest you follow Comintern's advice to comment out those lines.

Related

Loop through 2 lists in Excel with VBA to copy tab data from one to another

I have 2 sets of ranges; Source file paths and Destination file paths.
I want to loop through each list to open the source file and copy a tab/sheet to the destination file path.
Below is the code I have used to loop through the Source list and copy data from a tab in that workbook and paste it to a named sheet. The copy tab is named in the offset ,1 code below and the paste name will never change.
This step prepares the workbook so i can now copy this tab to a completely separate workbook that I have listed.
Is this possible to do efficiently with a for loop??
Sub RollQuarter()
Dim Wbk As Workbook
Dim Wks As Worksheet
Dim Filepath As String, Filename As String, sStg As String
Dim oDic As Scripting.Dictionary
Dim rng As Range, c As Range
Dim varKey As Variant
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
Set oDic = New Scripting.Dictionary
oDic.CompareMode = TextCompare
sStg = ""
Set rng = Union(Range("dummy")) 'Source files
For Each c In rng.Cells
If Not oDic.Exists(c.Value) Then
oDic.Add c.Value, c.Offset(, 1).Value
Else
MsgBox "Duplicate Item found", vbInformation, "Error Message"
Exit Sub
End If
Next c
For Each varKey In oDic.Keys
If Len(Dir(varKey)) = 0 Then
If sStg = "" Then
sStg = oDic.Item(varKey)
Else
sStg = sStg & ", " & vbCrLf & oDic.Item(varKey)
End If
Else
On Error Resume Next
Set Wbk = Workbooks.Open(varKey, False)
On Error GoTo 0
If Wbk Is Nothing Then
Else
With Wbk
.Sheets(oDic.Item(varKey)).Cells.Copy
.Sheets("dummy sheet").Cells.PasteSpecial xlPasteValues
Application.CutCopyMode = False
.Save
End With
Wbk.Close False
Set Wbk = Nothing
End If
End If
Next varKey
.....
If Len(sStg) > 0 Then MsgBox "The below files do not exist" & vbCrLf _
& sStg, vbCritical
End Sub

How to insert and offset an image based on cell value

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

Macros vba to list all inaccessible network folders

I have a vba code that scans a folder and its subdirectories for excel files and lists the connection strings and sql command. But my problem is my program doesn't list the inaccessible network folders that gives you the error "Access Denied." I wanna be able to list the path to the folder and indicate on the second column that the folder is inaccessible. How should I code it? I'm thinking
On Error GoTo Handler
Handler:
If Err.Number = x Then
oRng.Value = sFDR & sItem
oRng.Offset(0, 1).Value = "Inaccessible folder"
Resume Next
End If
But this code doesn't work. It doesn't specify the path of the 'access denied' folder at all. Instead, it puts the text "Inaccessible folder" to the next accessible excel file it sees.
Here's the code:
Private Const FILE_FILTER = "*.xl*"
Private Const sRootFDR = "Path" ' Root Folder
Private oFSO As Object ' For FileSystemObject
Private oRng As Range, N As Long ' Range object and Counter
Sub Main()
Application.ScreenUpdating = False
Set oFSO = CreateObject("Scripting.FileSystemObject")
N = 0
With ThisWorkbook.Worksheets("Sheet1")
.UsedRange.ClearContents ' Remove previous contents
.Range("A1:E1").Value = Array("Filename", "Connections", "Connection String", "Command Text", "Date Scanned")
Set oRng = .Range("A2") ' Initial Cell to start storing results
End With
Columns("A:E").Select
With Selection
.WrapText = True
.ColumnWidth = 45
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlCenter
End With
ListFolder sRootFDR
Application.ScreenUpdating = True
Set oRng = Nothing
Set oFSO = Nothing
Columns.AutoFit
MsgBox N & " Excel files has been checked for connections."
End Sub
Private Sub ListFolder(ByVal sFDR As String)
Dim oFDR As Object
' List the files of this Directory
ListFiles sFDR, FILE_FILTER
' Recurse into each Sub Folder
On Error GoTo Handler
Handler:
If Err.Number = 5 Then
oRng.Value = sFDR & sItem
oRng.Offset(0, 1).Value = "Inaccessible folder"
Resume Next
End If
For Each oFDR In oFSO.GetFolder(sFDR).SubFolders
ListFolder oFDR.Path & "\" ' Need '\' to ensure the file filter works
Next
End Sub
Private Sub ListFiles(ByVal sFDR As String, ByVal sFilter As String)
Dim sItem As String
On Error GoTo Handler
Handler:
If Err.Number = 52 Then
oRng.Value = sFDR & sItem
oRng.Offset(0, 1).Value = "Inaccessible folder"
Resume Next
End If
sItem = Dir(sFDR & sFilter)
Do Until sItem = ""
N = N + 1 ' Increment Counter
oRng.Value = sFDR & sItem
CheckFileConnections oRng.Value ' Call Sub to Check the Connection settings
oRng.Offset(0, 4) = Now
Set oRng = oRng.Offset(1) ' Move Range object to next cell below
sItem = Dir
Loop
End Sub
Private Sub CheckFileConnections(ByVal sFile As String)
Dim oWB As Workbook, oConn As WorkbookConnection
Dim sConn As String, sCMD As String
Dim ConnectionNumber As Integer
ConnectionNumber = 1
Application.StatusBar = "Opening workbook: " & sFile
On Error Resume Next
Set oWB = Workbooks.Open(Filename:=sFile, ReadOnly:=True, UpdateLinks:=False, Password:=userpass)
If Err.Number > 0 Then
oRng.Offset(0, 1).Value = "Password protected file"
Else
With oWB
For Each oConn In .Connections
If Len(sConn) > 0 Then sConn = sConn & vbLf
If Len(sCMD) > 0 Then sCMD = sCMD & vbLf
sConn = sConn & oConn.ODBCConnection.Connection
sCMD = sCMD & oConn.ODBCConnection.CommandText
oRng.Offset(0, 1).Value = ConnectionNumber ' 1 column to right (B)
oRng.Offset(0, 2).Value = oConn.ODBCConnection.Connection ' 2 columns to right (C)
oRng.Offset(0, 3).Value = oConn.ODBCConnection.CommandText ' 3 columns to right (D)
ConnectionNumber = ConnectionNumber + 1
Set oRng = oRng.Offset(1) ' Move Range object to next cell below
Next
End With
End If
oWB.Close False ' Close without saving
Set oWB = Nothing
Application.StatusBar = False
End Sub
Hum, I tried debugging your code and found the following.
Your error handlers are coded a bit goofy. If the handler gets triggered, yet the error code is NOT the one you are testing for, then you will re-invoke the loop from start. It would be more clean to code them as:
Private Sub ListFolder(ByVal sFDR As String)
Dim oFDR As Object, lFDR As Object
' List the files of this Directory
ListFiles sFDR, FILE_FILTER
' Recurse into each Sub Folder
On Error GoTo Handler
For Each oFDR In oFSO.GetFolder(sFDR).SubFolders
ListFolder oFDR.Path & "\" ' Need '\' to ensure the file filter works
Next
Exit Sub
Handler:
If Err.Number = 70 Then
oRng.Value = sFDR
oRng.Offset(0, 1).Value = "Inaccessible folder - access denied"
End If
Resume Next
End Sub
This ensures you perform a Resume Next for all errors that trigger the handler, not just the one error you are looking for. I know for the ListFiles() sub, that re-entrance into the loop should work properly, but still it is bad form. And that code format does not work for the ListFolder() sub as it causes hard aborts.
When I changed your ListFolder as shown (and changed Err.Number checked for to 70), you code seems to work for me. I made both inaccessible files and folders, and the proper error tag was shown with the proper file names and directory names that I made inaccessible.

Need some advice on how to stream line ACCESS/EXCEL VBA

I wrote this Access/VBA program. It works but only when I am not running other applications or few users are in the database. I need some ideas on streamlining the code. So it is not so system intensive. The program basically allows a user to pick a folder and then combines all worksheets in that folder in one excel document. My current idea is just to tell users to close all excel files when trying to run the program. Please Help:
Sub Excel_open()
Dim myXL As Excel.Application
Dim myXLS As Excel.Workbook
Const errExcelNotRunning = 429
On Error GoTo HandleIt
Set myXL = GetObject(, "Excel.application")
myXL.Visible = True
Set myXLS = myXL.Workbooks.Add
Call CombineWorkbooks(myXL)
HandleIt:
If Err.Number = errExcelNotRunning Then
Set myXL = CreateObject("Excel.Application")
Err.Clear
Resume Next
End If
End Sub
Sub CombineWorkbooks(myXL)
'Macro that combines the files into one folder
myXL.AskToUpdateLinks = False
myXL.DisplayAlerts = False
Dim CurFile As String, dirloc As String, strNamesheet As String
Dim DestWB As Workbook
Dim ws As Object ' allows for diffrent sheet types
'Add select the director function
dirloc = GetFolderName & "\" 'location of files not working want to select the file only
CurFile = Dir(dirloc & "*.xls*")
myXL.ScreenUpdating = False
myXL.EnableEvents = False
Set DestWB = Workbooks.Add(xlWorksheet)
Do While CurFile <> vbNullString
Dim OrigWB As Workbook
Set OrigWB = Workbooks.Open(FileName:=dirloc & CurFile, ReadOnly:=True)
'need to change a name active name is not doing it
CurFile = Left(CurFile, 4) ' This is no longer 29
'CurFile = Left(Left(CurFile, Len(CurFile) - 5), 29)
For Each ws In OrigWB.Sheets
ws.Copy After:=DestWB.Sheets(DestWB.Sheets.Count)
' Use the name to give the sheet a name
strNamesheet = Left((ws.Name), 25) & ";"
If OrigWB.Sheets.Count > 1 Then
DestWB.Sheets(DestWB.Sheets.Count).Name = strNamesheet & CurFile ' & ws.Index
Else
DestWB.Sheets(DestWB.Sheets.Count).Name = CurFile
End If
Next
OrigWB.Close SaveChanges:=False
CurFile = Dir
Loop
myXL.DisplayAlerts = False
DestWB.Sheets(1).Delete
myXL.DisplayAlerts = True
myXL.ScreenUpdating = True
myXL.EnableEvents = True
Set DestWB = Nothing
Call Delete_empty_Sheets(myXL)
Call Sort_Active_Book
MsgBox "Done"
'Call Xcombine_the_Matching
End Sub
Sub Delete_empty_Sheets(myXL)
'goes through all sheets and deletes
Reset_the_search:
For Each wsElement In Worksheets
If wsElement.Range("A2") = "" And wsElement.Range("B2") = "" Then
myXL.DisplayAlerts = False
wsElement.Delete
GoTo Reset_the_search
myXL.DisplayAlerts = True
End If
Next wsElement
End Sub
Sub Xcombine_the_Matching()
'I think I can make the order work
'change and transpose the array
Dim varStart As Variant
Dim wsCompare As Worksheet
Dim strMatch As String
'Dim varCompare As Variant
Dim strVareince As String
Dim strCurrentName As String
'you need to build a loop to solve this problem
For Each wsCompare In Worksheets
strVareince = Add_Array(Application.Transpose(wsCompare.Range("A1:Z1")))
For Each wsNompare In Worksheets
If wsNompare.Name <> strCurrentName Then
If strVareince = Add_Array(Application.Transpose(wsNompare.Range("A1:Z1"))) Then
MsgBox ("Matched with worksheet " & wsNompare.Name)
End If
End If
Next
Next
End Sub
Function array_to_string(x) As String
For Z = 1 To 26
array_to_string = array_to_string & x(Z, 1) & ";"
Next Z
End Function
Function GetFolderName(Optional OpenAt As String) As String
'Allows you to select the folder director that you want to combine
Dim lCount As Long
GetFolderName = vbNullString
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = OpenAt
.Show
For lCount = 1 To .SelectedItems.Count
GetFolderName = .SelectedItems(lCount)
Next lCount
End With
End Function
Function Add_Array(x) As String
'turns an excel document
For d = 1 To UBound(x)
Add_Array = Add_Array & x(d, 1)
Next d
End Function
Sub Read_data()
'this the
End Sub
Sub Sort_Active_Book()
Dim i As Integer
Dim j As Integer
Dim iAnswer As VbMsgBoxResult
'
' Prompt the user as which direction they wish to
' sort the worksheets.
'
iAnswer = MsgBox("Sort Sheets in Ascending Order?" & Chr(10) _
& "Clicking No will sort in Descending Order", _
vbYesNoCancel + vbQuestion + vbDefaultButton1, "Sort Worksheets")
For i = 1 To Sheets.Count
For j = 1 To Sheets.Count - 1
'
' If the answer is Yes, then sort in ascending order.
'
If iAnswer = vbYes Then
If UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
'
' If the answer is No, then sort in descending order.
'
ElseIf iAnswer = vbNo Then
If UCase$(Sheets(j).Name) < UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
End If
Next j
Next i
End Sub
You are passing your Excel Application object into your subroutines, but not using it fully, neither are you explicitly referencing the libraries:
Sub CombineWorkbooks(myXL)
Dim DestWB As Excel.Workbook ' <<<
Set DestWB = myXL.Workbooks.Add(xlWorksheet) ' <<<
End Sub
Run through your code and fix all of these first, then test & supply more feedback on what the precise symptoms of the problems are.

Iterate through spreadsheets in a folder and collect a value from each

I'm trying to write code that on Commandbutton2_Click searches through the folder that the file is in, takes a value from the same cell in each file and adds these together.
I have this:
Private Sub CommandButton2_Click()
Dim lCount As Long
Dim wbResults As Workbook
Dim wbCodeBook As Workbook
Dim strFolderPath As String
Dim strToolNumber As String
Dim RingCount As Integer
RingCount = 0
strToolNumber = CStr(Sheets("Sheet1").Range("B9").Value)
strFolderPath = "T:\Engineering\Tooling\Tooling Control Engineering\Press Tool Inspection Records\" & strToolNumber & "\"
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
On Error Resume Next
Set wbCodeBook = ThisWorkbook
With Application.FileSearch
.NewSearch
'Change path to suit
.LookIn = strFolderPath
.FileType = msoFileTypeExcelWorkbooks
If .Execute > 0 Then 'Workbooks in folder
For lCount = 1 To .FoundFiles.Count 'Loop through all
'Open Workbook x and Set a Workbook variable to it
Set wbResults = Workbooks.Open(FileName:=.FoundFiles(lCount), UpdateLinks:=0)
'DO YOUR CODE HERE
RingCount = Val(RingCount) + ActiveWorkbook.Sheets("Sheet1").Range("F11").Value
wbResults.Close SaveChanges:=False
Next lCount
End If
End With
On Error GoTo 0
ActiveSheet.Unprotect Password:=""
ActiveWorkbook.Sheets("Sheet1").Range("F13").Value = (RingCount + ActiveWorkbook.Sheets("Sheet1").Range("F11").Value)
ActiveSheet.Protect Password:=""
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub
whose main body was pieced together from different google searches - but it continually returns a value of 0 (despite the cells in the other sheets having values).
I read somewhere that Application.Filesearch does not work for versions of Excel later than 2003, could this be the source of the problem?
Its possible to pull that value youre interested in without opening each workbook. Its much more efficient and reliable.
This code iterates through all files in the path variable and pulls values without opening the Excel files. It then prints the values starting at F20. You can then make another wrapper function to sum them up and delete or whatever you want. Hope this helps
Private Sub CommandButton2_Click()
Dim tool As String
tool = CStr(Sheets("Sheet1").range("B9").Value)
Dim path As String
path = "T:\Engineering\Tooling\Tooling Control Engineering\Press Tool Inspection Records\" & strToolNumber & "\"
Dim fname
fname = Dir(CStr(path)) ' gets the filename of each file in each folder
Do While fname <> ""
If fname <> ThisWorkbook.Name Then
PullValue path, fname ' add values
End If
fname = Dir ' get next filename
Loop
End Sub
Private Sub PullValue(path As String, ByVal fname As String)
With range("F" & (range("F" & Rows.Count).End(xlUp).Row + 1))
.Formula = "='" & path & "[" & fname & "]Sheet1'!F11"
.Value = .Value
End With
End Sub

Resources