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.
Related
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
This fills in a worksheet based on recursively looking at files in sub folders. Encountering this error when Recur sub is called, searched similar threads with no luck, trying to figure out what I'm missing here. As far as I can tell, the calls to Recur match its parameter. Am I missing something obvious? Thanks.
Public Wb As Workbook
Public Ws As Worksheet
Public CLP As String
''''''''''''''''''''''''''''''''''''''''''''''''''
Function GFold(Ttl, Dflt As String) As String
''''''''''''''''''''''''''''''''''''''''''''''''''
Dim FDlog As FileDialog
Dim FStr As String
Set FDlog = Application.FileDialog(msoFileDialogFolderPicker)
With FDlog
.Title = Ttl
.AllowMultiSelect = False
.InitialFileName = Dflt
If .Show <> -1 Then GoTo NextCode
FStr = .SelectedItems(1)
End With
NextCode:
GFold = FStr
Set FDlog = Nothing
End Function
''''''''''''''''''''''''''''''
Sub CheckOffDocs()
''''''''''''''''''''''''''''''
Dim MyFSO, MyFld As Object
Dim Wb As Workbook
Dim Path, CLPath As String
' • Get folder path
Path = GFold("Select Parent Folder", Application.DefaultFilePath)
' • Check folder path
If Len(Path) = 0 Then
Exit Sub
End If
' • Create file sys obj
Set MyFSO = CreateObject("Scripting.FileSystemObject")
' • Get ahold of folder at path address
Set MyFld = MyFSO.getfolder(Path)
Set Wb = ActiveWorkbook
Set Ws = Wb.Sheets(1)
'• prompt clear checks input
If MsgBox("Clear existing inventory?", vbQuestion + vbYesNo) = vbYes Then
For c = 1 To 2
For r = 14 To 113
If Len(Ws.Cells(r, (c * 3) - 2).Value) > 1 Then
Ws.Cells(r, c * 3).ClearContents
End If
Next r
Next c
End If
'• pass folder to recur
Call Recur(MyFld)
'• clean up
Set MyFld = Nothing
Set MyFSO = Nothing
' • Set default location and prompt for save as info
SvName = CLPath & "L01 Contract File Checklist.xlsm"
SvName = Application.GetSaveAsFilename(InitialFileName:=SvName, fileFilter:="Excel files (*.xlsm), *.xlsm")
' • Check valid info
If Len(SvName) > 0 And InStr(SvName, "FALSE") = 0 And SvName <> False Then
If Left(UCase(Ws.Cells(1, 14).Value), 3) = "L01" Then Ws.Cells(1, 14).Value = "X"
Wb.SaveAs Filename:=SvName, FileFormat:=xlOpenXMLWorkbookMacroEnabled
Else
MsgBox "File not saved."
End If
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''
Sub Recur(ByVal Fld As Object)
''''''''''''''''''''''''''''''''''''''''''''''''''
Dim r, c As Integer
Dim MySub, MyFIle As Object
'• Recursively loop all folders
For Each MySub In Fld.subfolders
Call Recur(MySub)
Next MySub
If InStr(UCase(Fld.Name), "CHECKLIST") > 0 Then
CLP = Fld.Path & "\"
End If
For Each MyFIle In Fld.Files
For c = 1 To 2
For r = 14 To 113
'• Check for valid code row and match to filename
If Len(Ws.Cells(r, (c * 3) - 2).Value) > 1 And UCase(Left(MyFIle.Name, 3)) = UCase(Ws.Cells(r, (c * 3) - 2).Value, 3) Then
'• Mark "x" column
Ws.Cells(r, (c * 3)).Value = "X"
'• Bail out of loops after match
GoTo bail
End If
Next r
Next c
bail:
Next MyFIle
End Sub
Note that in VBA, you need to specify the data type for each variable in declarations, otherwise they are Variants.
Change
Dim MySub, MyFIle As Object
to
Dim MySub As Object, MyFIle As Object
and similarly elsewhere.
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.
I get this error:
subscript out of range.
I do not have the debug option, only OK and HELP.
One time on 20 the macro works. The rest of time I'm getting this error.
The code makes you choose the path you want to search and next the text you want to find in the workbook in the path chosen. It searches in sub folders too. After that it sends back the file name, sheet name, which cell and what text is in the cell.
The macro runs but pops that error after searching 4 to 5 different files.
Dim AppObject As New Class1
Public WS As Worksheet
Sub SearchWKBooksSubFolders(Optional Folderpath As Variant, Optional Str As Variant)
Dim myfolder As String
Dim a As Single
Dim sht As Worksheet
Dim Lrow As Single
Dim Folders() As String
Dim Folder As Variant
ReDim Folders(0)
Dim wbk As Workbook
If IsMissing(Folderpath) Then
Set WS = Sheets.Add
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
myfolder = .SelectedItems(1) & "\"
End With
Str = Application.InputBox(prompt:="Nom de la Personne:", Title:="Personne a chercher", Type:=2)
If Str = "" Then Exit Sub
WS.Range("A1") = "Semaine"
WS.Range("B1") = "Journée"
WS.Range("C1") = "Cellule"
WS.Range("D1") = "Nom"
Folderpath = myfolder
Value = Dir(myfolder, &H1F)
Else
If Right(Folderpath, 2) = "\\" Then
Exit Sub
End If
Value = Dir(Folderpath, &H1F)
End If
Do Until Value = ""
If Value = "." Or Value = ".." Then
Else
If GetAttr(Folderpath & Value) = 16 Then
Folders(UBound(Folders)) = Value
ReDim Preserve Folders(UBound(Folders) + 1)
ElseIf Right(Value, 3) = "xls" Or Right(Value, 4) = "xlsx" Or Right(Value, 4) = "xlsm" Then
On Error Resume Next
Workbooks.Open Filename:=Folderpath & Value, Password:="zzzzzzzzzzzz"
If Err.Number <> 0 Then
WS.Range("A4").Offset(a, 0).Value = Value
WS.Range("B4").Offset(a, 0).Value = "Password protected"
a = a + 1
On Error GoTo 0
Else
For Each sht In ActiveWorkbook.Worksheets
'Expand all groups in sheet
sht.Outline.ShowLevels RowLevels:=8, ColumnLevels:=8
Set c = sht.Cells.Find(Str)
If Not c Is Nothing Then
firstAddress = c.Address
Do
Lrow = WS.Range("A" & Rows.Count).End(xlUp).Row
WS.Range("A1").Offset(Lrow, 0).Value = Value
WS.Range("B1").Offset(Lrow, 0).Value = sht.Name
WS.Range("C1").Offset(Lrow, 0).Value = c.Address
WS.Range("D1").Offset(Lrow, 0).Value = c.Value
Set c = sht.Cells.FindNext(c)
Loop While Not c Is Nothing And c.Address <> firstAddress
End If
Next sht
End If
Workbooks(Value).Close False
On Error GoTo 0
End If
End If
Value = Dir
Loop
For Each Folder In Folders
SearchWKBooksSubFolders (Folderpath & Folder & "\")
Next Folder
Cells.EntireColumn.AutoFit
End Sub
you can debug on your own without the debugger of the IDE.
Simply put On Error Resume Next/On Error Goto 0 very close to each other in order to restrict the statements which can raise errors. ie the second On Error Goto 0 is too far.
I can debug more effectively simply putting between statements something like that:
a = a + 1
debug.print "I am here"
b = b -5
debug.print "I am there"
c = 5 / 0
debug.print "You can't see me"
So you can find when the error is raised
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.