I have created a file which I run multiple macros (for example 5). Everything works when I run all macros and I shared the file to a colleague (A) who said it works good. But when colleague (A) share to colleague (B), they encountered this error.
Can you please guide me on where I have been wrong?
Sub CaseListing()
Dim wbSource As Workbook, lastRow As Long
Application.ScreenUpdating = False
ThisWorkbook.Sheets("SR - Information").Range("A2:B1048576").Clear
Set wbSource = Workbooks.Open(Filename:="https://*/All_Region_Case_List_CURRENT.xlsx", UpdateLinks:=False, ReadOnly:=True)
lastRow = wbSource.Sheets("Sheet1").Range("B" & Rows.Count).End(xlUp).Row
wbSource.Activate
Range("B4:B" & lastRow & ",K4:K" & lastRow).Copy ThisWorkbook.Sheets("SR - Information").Range("A2")
wbSource.Close
With ThisWorkbook.Sheets("SR - Information").Range("A1:A" & Range("A" & Rows.Count).End(xlDown).Row)
.NumberFormat = "General"
.Value = .Value
End With
ThisWorkbook.Sheets("SR - Information").Range("E1") = "<-- last refreshed on " & Now()
Application.ScreenUpdating = True
End Sub
EMAIL
Public wsSR As Worksheet
Sub CreateEmail()
Dim TempFilePath As String, TempFileName As String, FileExtStr As String, myFile As String
Dim LastCell As Long, endR As Long
Dim Fname As String, Lname As String, EmailAddress As String
Dim ol As Outlook.Application
Dim mi As Outlook.MailItem
Dim c1, c2 As Collection, msg As String, i As Variant
Set wbMe = ThisWorkbook
Set wsBW = wbMe.Sheets("B+W")
Set wsSR = wbMe.Sheets("SR - Information")
Set wsFinal = wbMe.Sheets("Report")
Set wsCNA = ThisWorkbook.Sheets("C+N ")
Set wsWebCNA = ThisWorkbook.Sheets("Web")
Set c1 = New Collection
Set c2 = New Collection
pwd = "abc"
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
wsFinal.Unprotect pwd
'Clear and Copy to the Final sheet
wsFinal.Range("A5:V1048576").Clear
LastCell = wsBW.Range("A" & Rows.Count).End(xlUp).Row
wsBW.Range("A4:V" & LastCell).Copy
wsFinal.Range("A4").PasteSpecial Paste:=xlPasteValues
Set wsSR = ThisWorkbook.Sheets("SR - Information")
endR = wsSR.Range("Q" & Rows.Count).End(xlUp).Row
wsSR.Visible = False
wsBW.Visible = False
wsCNA.Visible = False
wsWebCNA.Visible = False
wsFinal.Range("A4:V" & Cells(Rows.Count, 1).End(xlUp).Row).Columns.AutoFit
Set ol = New Outlook.Application
Set mi = ol.CreateItem(olMailItem)
For Each cel In Sheets("SR - Information").Range("Q2:Q" & endR).Cells
wsFinal.Activate
wsFinal.Unprotect pwd
Range("A4:V" & Cells(Rows.Count, 22).End(xlUp).Row).AutoFilter Field:=22, Criteria1:=cel ', visibledropdown:=False
Set IndxLookupRange = Sheets("SR - Information").Range("H:I")
Set Matchlookuprange = Sheets("SR - Information").Range("H:H")
cel.Offset(0, 1) = Application.WorksheetFunction.IfError(Application.Index(IndxLookupRange, Application.Match(cel, Matchlookuprange, 0), 2), "-")
EmailAddress = cel.Offset(0, 1)
'Temporary file details
TempFilePath = Environ$("temp") & "\"
TempFileName = " Report - " & Format(Now, "mmmm dd, yyyy")
FileExtStr = "." & LCase(Right(ThisWorkbook.Name, Len(ThisWorkbook.Name) - InStrRev(ThisWorkbook.Name, ".", , 1)))
If EmailAddress <> "-" Then
For Each oAccount In ol.Session.Accounts
If oAccount = "pqrs.abc#xyz.com" Then 'BD_Best_Practice
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
'Get the file ready - protection and hide
wsBW.protect pwd
wbMe.protect Password:=pwd, Structure:=True, Windows:=True
'Keep the desired sheet activate and save as temp file
wsFinal.Activate
wsFinal.protect pwd
wbMe.SaveCopyAs TempFilePath & TempFileName & FileExtStr
On Error Resume Next
With OutMail
.To = EmailAddress
.CC = ""
.BCC = ""
.Subject = " Report" '& Format(Now, "mmmm dd, yyyy") '" & Fname & "," & "<br> <br> "
.HTMLBody = "<BODY style='font-family:Calibri; font-size:11pt';>Hi, <br><br>" & _
"Please find the attached the Report. This report shows your Plan Sponsor's Enhanced Access user activity." & _
"<br> <br> Thank you, <br> xyz" & Range("F3") & "</font></BODY>"
.Attachments.Add TempFilePath & TempFileName & FileExtStr
Set .SendUsingAccount = oAccount
'.Display
.send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End If
Next oAccount
'Delete the temp file
Kill TempFilePath & TempFileName & FileExtStr
Else
c1.Add cel, CStr(cel)
c2.Add cel, CStr(cel)
End If
Next cel
wbMe.Unprotect Password:=pwd
wsBW.Visible = True
wsSR.Visible = True
wsCNA.Visible = True
wsWebCNA.Visible = True
If c1.Count = 0 Then
msg = "All Service Reps are matched!"
Range("Q:R").Clear
MsgBox msg
Exit Sub
Else
msg = "Make sure to update the below list of Service Reps information manually!" & vbCrLf
For i = 1 To c1.Count
msg = msg & vbCrLf & c1.Item(i)
Next i
End If
MsgBox msg '& vbCrLf & vbCrLf & "Make sure Service Reps Details are updated manually!"
wsSR.Range("Q:R").Clear
wsBW.Select
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
IMPORTFILES
Public wbMe As Workbook
Public wsBW As Worksheet, wsSR As Worksheet, wsFinal As Worksheet
Public wsBoxi As Worksheet, wsWeb As Worksheet, wsWebCNA As Worksheet, wsNDR As Worksheet
Public pwd As Variant, domain As String
Public wsCNA As Worksheet
Sub ImportFiles()
'PURPOSE: 1 B and 1 W
Dim f, fpath As String
If MsgBox("Is it 2 B and 1 W?", vbYesNo) = vbNo Then
Set wbMe = ThisWorkbook
Set wsBW = wbMe.Sheets("B+W")
Set wsSR = wbMe.Sheets("SR - Information")
Set wsFinal = wbMe.Sheets("Report")
pwd = "abc"
Application.ScreenUpdating = False
wsBW.Unprotect pwd
If wsBW.AutoFilterMode = True Then wsBW.AutoFilterMode = False
wsBW.Range("A4:Y1048576").Clear
wbMe.Unprotect Password:=pwd ', Structure:=False, Windows:=False
wsSR.Visible = True
wsSR.Columns("P:R").Clear
P = wbMe.Sheets.Count
For m = P To 1 Step -1
t = wbMe.Sheets(m).Name
If t <> "B+W" And t <> "SR - Information" And t <> "Report" And t <> "C+ " And t <> "Web" And t <> "NDRs" Then
Application.DisplayAlerts = False
wbMe.Sheets(m).Delete
Application.DisplayAlerts = True
End If
Next m
fpath = GetFolder & "\"
Application.ScreenUpdating = False
If fpath = "\" Then
Exit Sub
Else
f = Dir(fpath)
Do While Len(f) > 0
Select Case Right(f, Len(f) - InStrRev(f, "."))
Case "xls", "xlsx", "csv"
OpenFile (fpath & f)
End Select
f = Dir
Loop
Set wsBoxi = wbMe.Sheets("Sheet1")
Set wsWeb = wbMe.Sheets("GBA Access IDS")
Call Merger
Call Reorder_Columns
'Apply Formats
wsWeb.Range("A1").Copy
wsBW.Range("A4:W4").PasteSpecial xlFormats
wsBW.Rows("4:4").Columns.AutoFit
Application.CutCopyMode = False
Range("A4").Select
P = wbMe.Sheets.Count
For m = P To 1 Step -1
t = wbMe.Sheets(m).Name
If t <> "BOXI+WEB" And t <> "SR - Information" And t <> "Report" And t <> "C+N " And t <> "Web" And t <> "NDRs" Then
Application.DisplayAlerts = False
wbMe.Sheets(m).Delete
Application.DisplayAlerts = True
End If
Next m
wsBW.Range("$A$4:$U$1048576").AutoFilter Field:=1, Criteria1:="C ", Operator:=xlOr, Criteria2:="N "
MsgBox "Merge Successful!"
Application.ScreenUpdating = True
End If
Else
Call LoopAllFilesInFolder
End If
End Sub
Function GetFolder() As String
Dim f As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select multiple Files"
.AllowMultiSelect = False
.InitialFileName = ThisWorkbook.Path
If .Show <> -1 Then GoTo There
f = .SelectedItems(1)
End With
There:
GetFolder = f
End Function
Private Sub OpenFile(filepath)
Dim sh, wb As Workbook
Set wb = Workbooks.Open(filepath)
'Debug.Print filepath
For Each sh In wb.Sheets
sh.Copy After:=wbMe.Sheets(wbMe.Sheets.Count)
Next sh
wb.Close False
End Sub
Private Sub Merger()
Dim lastRow As Long
wsBoxi.Rows("2:2").EntireRow.Delete
wsWeb.Rows("1:2").EntireRow.Delete
'Reorder BOXI columns
wsBoxi.Columns("D:D").Cut
wsBoxi.Columns("A:A").Insert Shift:=xlToRight
Set IndexRange = wsBoxi.Range("A:G") 'BOXI
Set MatchLookupRng = wsBoxi.Range("A:A")
lastRow = wsWeb.Range("A" & Rows.Count).End(xlUp).Row
wsWeb.Activate
For Each AdID In wsWeb.Range("E2:E" & lastRow).Cells
Range("P" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 2), "-") 'Market Segment
Range("Q" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 3), "-") 'Region code
Range("R" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 4), "-") 'Cleint#
Range("S" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 5), "-") 'Admin Access Level
Range("T" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 6), "-") 'Admin Location Access
Range("U" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 7), "-") 'Admin Access to all Locations
Next AdID
wsWeb.Range("P1").Value = "Market Segment"
wsWeb.Range("Q1").Value = "Region Code"
wsWeb.Range("R1").Value = "Client#"
wsWeb.Range("S1").Value = "Admin Access Level"
wsWeb.Range("T1").Value = "Admin Location Access"
wsWeb.Range("U1").Value = "Admin Access to all Locations"
wsWeb.Range("A1:U" & lastRow).Copy wsBW.Range("A4")
wsBW.Range("A4:Y1048576").Font.Name = "Calibri"
wsBW.Range("A4:Y1048576").Font.Size = 10
End Sub
Private Sub Reorder_Columns() 'Final Columns
Dim ColumnOrder As Variant, ndx As Integer
Dim Found As Range, counter As Integer
ColumnOrder = Array("Market Segment", "Region Code", "Requestor Access ID", "Requestor Email", "Client#", "Transaction Type", _
"Date Processed", "Admin First Name", "Admin Last Name", "Admin Language", "Admin Email", "Admin Access ID", "Admin Access Level", _
"Admin Location Access", "Admin Access to all Locations", "Changed Admin First Name", "Changed Admin Last Name", "Changed Admin Language", _
"Changed Admin Email", "Changed Admin Access Level", "Changed Admin Location Access")
counter = 1
wsBW.Activate
For ndx = LBound(ColumnOrder) To UBound(ColumnOrder)
Set Found = Rows("4:4").Find(ColumnOrder(ndx), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
If Not Found Is Nothing Then
If Found.Column <> counter Then
Found.EntireColumn.Cut
Columns(counter).Insert Shift:=xlToRight
Application.CutCopyMode = False
End If
counter = counter + 1
End If
Next ndx
Call HighlightPlanAdmin
End Sub
Private Sub HighlightPlanAdmin()
Dim ReqID As Range, nReqID As String, rReqID As String, tType As String, ntType As String
wsBW.Activate
For Each ReqID In Range("C5:C" & Cells(Rows.Count, 1).End(xlUp).Row).Cells
rReqID = Trim(ReqID)
tType = Trim(ReqID.Offset(0, 3)) '"Add Plan Admin"
If tType = "Add Plan Admin" Then
nReqID = Trim(ReqID.Offset(1, 0)) 'Requestor ID next row
If rReqID = nReqID Then
ntType = Trim(ReqID.Offset(1, 3))
If ntType <> "Add Plan Admin to OASIS." Then
ReqID.Offset(0, 3).Font.ColorIndex = 3
End If
Else
ReqID.Offset(0, 3).Font.ColorIndex = 3
End If
If nReqID = "" Then
ntType = Trim(ReqID.Offset(1, 3))
If ntType = "" Then
ReqID.Offset(0, 3).Font.ColorIndex = 3
End If
End If
End If
Next ReqID
End Sub
Sub LoopAllFilesInFolder()
'PURPOSE: 2 B and 1 W. To loop through all Excel files in a user specified folder and perform ...
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set wsBW = ThisWorkbook.Sheets("B+W")
Set wsCNA = ThisWorkbook.Sheets("C+N ")
Set wsWebCNA = ThisWorkbook.Sheets("Web")
Set wsFinal = ThisWorkbook.Sheets("Report")
Set wsSR = ThisWorkbook.Sheets("SR - Information")
wsBW.Unprotect "abc"
If wsBW.AutoFilterMode = True Then wsBW.AutoFilterMode = False
wsSR.Range("Q1:R1048576").Clear
wsBW.Range("A4:Y1048576").Clear
wsCNA.Range("A1:G1048576").Clear
wsWebCNA.Range("A1:Z1048576").Clear
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = "Select A Target Folder"
.Show
If .SelectedItems.Count <> 0 Then
xDirect = .SelectedItems(1) & "\"
xFname = Dir(xDirect, 7)
Do While xFname <> ""
If InStr(1, xFname, "C ", vbTextCompare) <> 0 Then
Set wb = Workbooks.Open(Filename:=xDirect & xFname)
dendRow = wsCNA.UsedRange.Rows.Count
wb.Worksheets(1).UsedRange.Copy
If dendRow = 1 Then
wsCNA.Range("A" & dendRow).PasteSpecial Paste:=xlPasteValues
Else
wsCNA.Range("A" & dendRow + 1).PasteSpecial Paste:=xlPasteValues
End If
wb.Close
ElseIf InStr(1, xFname, "N ", vbTextCompare) <> 0 Then
Set wb = Workbooks.Open(Filename:=xDirect & xFname)
dendRow = wsCNA.UsedRange.Rows.Count
wb.Worksheets(1).UsedRange.Copy
wsCNA.Range("A" & dendRow + 1).PasteSpecial Paste:=xlPasteValues
wb.Close
ElseIf InStr(1, xFname, "Web", vbTextCompare) <> 0 Then
Set wb = Workbooks.Open(Filename:=xDirect & xFname)
wb.Worksheets(1).UsedRange.Copy
wsWebCNA.Range("A1").PasteSpecial Paste:=xlPasteValues
wb.Close
End If
xFname = Dir
Loop
End If
End With
wsCNA.Activate
For Each cel In wsCNA.Range("A3:A" & Range("A" & Rows.Count).End(xlUp).Row).Cells
If InStr(1, cel, "Market Segment", vbTextCompare) <> 0 Then
cel.Offset(1, 0).EntireRow.Delete
cel.EntireRow.Delete
End If
Next cel
Call MergerFolder
Call Reorder_Columns_Folder
'Apply Formats
wsBW.Range("A4:W4").Font.Bold = True
wsBW.Range("A4:W4").Font.Underline = xlUnderlineStyleSingle
wsBW.Rows("4:4").Columns.AutoFit
Application.CutCopyMode = False
Range("A4").Select
wsBW.Range("$A$4:$U$1048576").AutoFilter Field:=1, Criteria1:="Corporate Accounts", Operator:=xlOr, Criteria2:="N "
MsgBox "Merge Successful!"
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Private Sub MergerFolder()
Dim lastRow As Long
wsCNA.Rows("2:2").EntireRow.Delete
wsWebCNA.Rows("1:2").EntireRow.Delete
'Reorder BOXI columns
wsCNA.Columns("D:D").Cut
wsCNA.Columns("A:A").Insert Shift:=xlToRight
Set IndexRange = wsCNA.Range("A:G") 'BOXI
Set MatchLookupRng = wsCNA.Range("A:A")
lastRow = wsWebCNA.Range("A" & Rows.Count).End(xlUp).Row
wsWebCNA.Activate
For Each AdID In wsWebCNA.Range("E2:E" & lastRow).Cells
Range("P" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 2), "-") 'Market Segment
Range("Q" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 3), "-") 'Region code
Range("R" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 4), "-") 'Cleint#
Range("S" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 5), "-") 'Admin Access Level
Range("T" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 6), "-") 'Admin Location Access
Range("U" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 7), "-") 'Admin Access to all Locations
Next AdID
wsWebCNA.Range("P1").Value = "Market Segment"
wsWebCNA.Range("Q1").Value = "Region Code"
wsWebCNA.Range("R1").Value = "Client#"
wsWebCNA.Range("S1").Value = "Admin Access Level"
wsWebCNA.Range("T1").Value = "Admin Location Access"
wsWebCNA.Range("U1").Value = "Admin Access to all Locations"
wsWebCNA.Range("A1:U" & lastRow).Copy wsBW.Range("A4")
wsBW.Range("A4:Y1048576").Font.Name = "Calibri"
wsBW.Range("A4:Y1048576").Font.Size = 10
End Sub
Private Sub Reorder_Columns_Folder() 'Final Columns
Dim ColumnOrder As Variant, ndx As Integer
Dim Found As Range, counter As Integer
ColumnOrder = Array("Market Segment", "Region Code", "Requestor Access ID", "Requestor Email", "Client#", "Transaction Type", _
"Date Processed", "Admin First Name", "Admin Last Name", "Admin Language", "Admin Email", "Admin Access ID", "Admin Access Level", _
"Admin Location Access", "Admin Access to all Locations", "Changed Admin First Name", "Changed Admin Last Name", "Changed Admin Language", _
"Changed Admin Email", "Changed Admin Access Level", "Changed Admin Location Access")
counter = 1
wsBW.Activate
For ndx = LBound(ColumnOrder) To UBound(ColumnOrder)
Set Found = Rows("4:4").Find(ColumnOrder(ndx), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
If Not Found Is Nothing Then
If Found.Column <> counter Then
Found.EntireColumn.Cut
Columns(counter).Insert Shift:=xlToRight
Application.CutCopyMode = False
End If
counter = counter + 1
End If
Next ndx
Call HighlightPlanAdmin_Folder
End Sub
Private Sub HighlightPlanAdmin_Folder()
Dim ReqID As Range, nReqID As String, rReqID As String, tType As String, ntType As String
wsBW.Activate
For Each ReqID In Range("C5:C" & Cells(Rows.Count, 1).End(xlUp).Row).Cells
ReqID.Select
rReqID = Trim(ReqID)
tType = Trim(ReqID.Offset(0, 3)) '"Add Plan Admin"
If tType = "Add Plan Admin" Then
nReqID = Trim(ReqID.Offset(1, 0)) 'Requestor ID next row
If rReqID = nReqID Then
ntType = Trim(ReqID.Offset(1, 3))
If ntType <> "Add Plan Admin to OASIS." Then
ReqID.Offset(0, 3).Font.ColorIndex = 3
End If
Else
ReqID.Offset(0, 3).Font.ColorIndex = 3
End If
If nReqID = "" Then
ntType = Trim(ReqID.Offset(1, 3))
If ntType = "" Then
ReqID.Offset(0, 3).Font.ColorIndex = 3
End If
End If
End If
Next ReqID
End Sub
SRMATCH
Public wsSR As Worksheet
Sub ServiceRepMatch()
Set wsSR = ThisWorkbook.Sheets("SR - Information")
Set wsBW = ThisWorkbook.Sheets("B+W")
Set SRLookupRng = wsSR.Range("A:B")
Set macth = wsSR.Range("B1:B1048576")
Application.ScreenUpdating = False
wsBW.Range("V4").Value = "Service Reps"
For Each cel In wsBW.Range("E5:E" & Cells(Rows.Count, 1).End(xlUp).Row).Cells
cel.Offset(0, 17) = Application.IfError(Application.VLookup(cel, SRLookupRng, 2, 0), "-")
Next cel
wsBW.Range("V4:V" & Cells(Rows.Count, 22).End(xlUp).Row).Copy wsSR.Range("P1")
wsSR.Select
wsSR.Range("P1:P" & Cells(Rows.Count, 16).End(xlUp).Row).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=wsSR.Range("Q1"), Unique:=True
wsSR.Columns("P").Clear
wsBW.Select
MsgBox "DONE!"
Application.ScreenUpdating = True
End Sub
In nutshell, we first run IMPORTFILES to merge 2 reports it can either be 2 or 3 and perform some data manipluations. Secondly, CASELISTING is used to get the SR's client#. Third, we match the respective sales representatives through SRMATCH. Last, we use CREATEEMAIL to send individual emails for SR's their report and confidently message in the Body.
Im currently trying to edit a previously created Macro by another team
It very successfully is able to retrieve all file names and paths from a specific location, very useful if all the files are there.
My issue is Im trying to adapt this to another area where the files are held in a "Storage" directory
From here they go:
Storage\ProposalFolder\(1 of 3 folders)\File
the 1 of 3 folders thing helps sort them based on what type of proposal they are
Project, Prospect or Suspect
So what I need to do is have a macro thats given the Storage directory and then scans through each Proposal subfolder, then sees which folder type the file is stored in (if the file is in Project, the other 2 folders WILL be empty)
Please see below
Storage View
Proposal Folder
Project/prospect/suspect folder
This is the code left behind - I've edited it here and there
Sub ListFilesInDirectory()
If MsgBox("Are you sure you want to list the files?", vbYesNo) = vbNo Then
End
Else
End If
Select Case MsgBox("Press Yes to retrieve ALL files." & vbNewLine & vbNewLine & "Press No to retrieve *** files only", vbQuestion + vbYesNoCancel + vbDefaultButton1, "Which Do You Want To Retrieve?")
Case vbCancel
End
Case vbNo
***_Option = 1
Case vbYes
***_Option = 2
End Select
Dim counter As Single
counter = Timer
On Error GoTo error_message
Application.StatusBar = "The macro is running. Please wait..."
Application.Calculation = xlCalculationManual
Range("A7:KZ10000").Select
Selection.ClearContents
Cells.FormatConditions.Delete
Range("A1").Select
Application.ScreenUpdating = False
'Populate columns A to C
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim ws As Worksheet
Dim objSubfolders As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ws = ActiveSheet
startrow = 7
If IsEmpty(Range("file_directory")) Then
GoTo skip_this
Else
filedir = Range("file_directory").Value
End If
'Get the folder object associated with the directory
Set objFolder = objFSO.GetFolder(filedir)
Set objSubfolders = objFolder.subfolders
'ws.Cells(1, 1).Value = "The files found in " & objFolder.Name & " are:"
'Loop through the Files collection
If ***_Option = 1 Then
For Each objFile In objFolder.Files
DoEvents
If InStr(UCase(objFile.Name), "****") > 0 Then
ws.Cells(startrow, 1).Value = filedir
' ws.Cells(startrow, 2).Value = "=HYPERLINK(" & Chr(34) & filedir & "\" & objFile.Name & Chr(34) & "," & Chr(34) & objFile.Name & Chr(34) & ")"
ws.Cells(startrow, 2).Value = objFile.Name
ws.Cells(startrow, 2).Hyperlinks.Add ws.Cells(startrow, 2), filedir & "\" & objFile.Name
ws.Cells(startrow, 3).Value = objFile.DateLastModified
startrow = startrow + 1
End If
Next
End If
If ***_Option = 2 Then
For Each objFile In objFolder.Files
DoEvents
ws.Cells(startrow, 1).Value = filedir
' ws.Cells(startrow, 2).Value = "=HYPERLINK(" & Chr(34) & filedir & "\" & objFile.Name & Chr(34) & "," & Chr(34) & objFile.Name & Chr(34) & ")"
ws.Cells(startrow, 2).Value = objFile.Name
ws.Cells(startrow, 2).Hyperlinks.Add ws.Cells(startrow, 2), filedir & "\" & objFile.Name
ws.Cells(startrow, 3).Formula = "=CONCATENATE(" & startrow & "2," & startrow & "3)"
startrow = startrow + 1
Next
' For Each SubFolder In objSubfolders
'
' For Each objFile In objSubfolders.Files
' DoEvents
' ws.Cells(startrow, 1).Value = filedir
'' ws.Cells(startrow, 2).Value = "=HYPERLINK(" & Chr(34) & filedir & "\" & objFile.Name & Chr(34) & "," & Chr(34) & objFile.Name & Chr(34) & ")"
' ws.Cells(startrow, 2).Value = objFile.Name
' ws.Cells(startrow, 2).Hyperlinks.Add ws.Cells(startrow, 2), filedir & "\" & objFile.Name
' ws.Cells(startrow, 3).Value = objFile.DateLastModified
' startrow = startrow + 1
' Next
' Next SubFolder
End If
' For Each SubFolder In SourceFolder.subfolders
' ListFilesInFolder SubFolder.Path, True
' Next SubFolder
'
' If subfolders = True Then
' For Each SubFolder In SourceFolder.subfolders
' ListFilesInFolder SubFolder.Path, True
' Next SubFolder
' End If
skip_this:
Next
Set objFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing
lastrow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
'Format any potential error files in red
Cells.FormatConditions.Delete
Range("B7:B" & lastrow).Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=RIGHT(B7,5)<>"".xlsm"""
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.ThemeColor = xlThemeColorDark1
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=LEFT(B7,1)=""~"""
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.ThemeColor = xlThemeColorDark1
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = True
'Range("C4").Select
'ActiveCell.FormulaR1C1 = "Date" & Chr(10) & "Modified"
Range("C7:C" & lastrow).Select
Selection.NumberFormat = "dd/mm/yyyy hh:mm:ss"
Selection.HorizontalAlignment = xlCenter
Range("A1").Select
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.StatusBar = False
MsgBox ("Time taken to list files (hr:min:sec): " & Format((Timer - counter) / 86400, "hh:mm:ss") & vbNewLine & vbNewLine & "Please now do an initial cleanup of the files listed:" & vbNewLine & " 1) Delete any obvious older versions of the files" & vbNewLine & " 2) Files highlighted red are likely to be incorrect and should be deleted")
Exit Sub
error_message:
If Err.Number <> 0 Then
Msg = "Error # " & Str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
End If
Range("A7:KZ10000").Select
Selection.ClearContents
Cells.FormatConditions.Delete
Range("A1").Select
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.StatusBar = False
MsgBox ("You have entered an incorrect directory path. Please ensure the 3 cells in the Variables tab are showing valid directory paths, or the cells are empty")
End Sub
What I need to do is list the files in the subfolders just like the "For each objFile" code does, but I cant get my head around how to go further than one level of subfolders - the code commented out about subfolders was me :/
Any help would be super!
Further to comments above...
A recursive procedure generally repeats into "lower levels" by calling itself. Obviously this can cause an issue if not coded properly, but there are countless code example on this site and others, such as:
Stack Overflow : List all files in a folder and subfolders in excel
Stack Overflow: Loop through files in a folder using VBA?
Stack Overflow: get list of subdirs in vba
Stack Overflow: List files in folder and subfolder with path to .txt file
Allen Browne: List files recursively
Chip Pearson: Recursion And The FileSystemObject
Wikipedia : Recursion in Computer Science
Everything you need to know is contained in (or linked from) those pages.
hi what i am doing right now is scrapping data. after the process complete it will pop msgbox "Completed" and the new file contains the data will be save to network path. my question is. what code do i need to add so that. after the scraping operation complete, it will automatically open the new file created by the scrap tool.
Here is my code
Global FilePath As String
Global strPath As String
Declare Function WNetGetUser Lib "mpr.dll" _
Alias "WNetGetUserA" (ByVal lpName As String, _
ByVal lpUserName As String, lpnLength As Long) As Long
Const NoError = 0
Sub Clear_Internet_Cache()
Shell "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255"
End Sub
''==========================================================================================
''Copy_Paste function creates the log of excel files with the issues in it
''==========================================================================================
Function Copy_Paste() As String
Dim SourceBook As Workbook
Dim DBook As Workbook
Dim strPath As String
Dim count As Double
Dim name As String
Dim TemplateBook, MyTime, Mydate As String
Dim FileName As String
Dim directoryName As String
Dim FY1 As String
Dim WK As String
Dim MyInput As Integer
Dim layer As String
Dim CrawlerName As String
Dim fixedpath As String
Dim region As String
Dim segment As String
If Sheet1.Cells(2, 6) = "Upload to Sharedrive" Then
fixedpath = "\\"
FY1 = Sheet1.Cells(2, 7)
WK = Sheet1.Cells(2, 8)
MyInput = Sheet9.Cells(3, 26)
CrawlerName = "AIO"
region = "EMEA"
segment = Sheet1.Cells(2, 9)
If MyInput = 1 Then
layer = "Staging"
Else
layer = "Production"
End If
''''''''''''''''''''''''''''''FOR USER NAME
Const lpnLength As Integer = 255
Dim status As Integer
Dim lpName, lpUserName As String
lpUserName = Space$(lpnLength + 1)
status = WNetGetUser(lpName, lpUserName, lpnLength)
If status = NoError Then
lpUserName = Left$(lpUserName, InStr(lpUserName, Chr(0)) - 1)
End If
'''''''''''''''''''''''''''''''''''''''''''
directoryName = fixedpath & "\" & region
If Not DirExists(directoryName) Then
MkDir (directoryName)
End If
directoryName = fixedpath & "\" & region & "\" & segment
If Not DirExists(directoryName) Then
MkDir (directoryName)
End If
directoryName = fixedpath & "\" & region & "\" & segment & "\" & FY1
If Not DirExists(directoryName) Then
MkDir (directoryName)
End If
directoryName = fixedpath & "\" & region & "\" & segment & "\" & FY1 & "\" & WK
If Not DirExists(directoryName) Then
MkDir (directoryName)
End If
directoryName = fixedpath & "\" & region & "\" & segment & "\" & FY1 & "\" & WK & "\" & layer
If Not DirExists(directoryName) Then
MkDir (directoryName)
End If
directoryName = fixedpath & "\" & region & "\" & segment & "\" & FY1 & "\" & WK & "\" & layer & "\" & CrawlerName
If Not DirExists(directoryName) Then
MkDir (directoryName)
End If
strPath = directoryName
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
TemplateBook = "AIO_Report"
TemplateBook = Left(TemplateBook, Len(TemplateBook) - 5)
Mydate = Format(Date, "mmm d yyyy")
MyTime = Format(Time, "hh:mm:ss")
MyTime = Replace(MyTime, ":", "_")
FileName = TemplateBook & "_" & Mydate & "_" & MyTime
FilePath = ""
FilePath = strPath & "\" & FileName & "_" & lpUserName & ".xlsx"
Set SourceBook = ActiveWorkbook
Set DBook = Workbooks.Add
SourceBook.Sheets("Bundle List").Cells.copy Destination:=DBook.Sheets("Sheet1").Cells
DBook.Sheets("Sheet1").name = "Error Report"
Sheets("Error Report").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Range("A1").Select
Selection.EntireRow.Select
Selection.Delete
Range("A1").Select
Selection.EntireRow.Select
Selection.Delete
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
DBook.SaveCopyAs FilePath
DBook.Close False
End If
Sheets("Bundle List").Select
Columns("W:An").Select
Selection.Delete Shift:=xlToLeft
Columns("a").Select
MsgBox ("Completed.")
Application.StatusBar = ""
End Function
If DBook is the file you want left open, then I'd probably change this:
DBook.SaveCopyAs FilePath
DBook.Close False
To:
DBook.SaveAs FilePath
This will leave the workbook open, and you've already saved it. Just keep it open for the user to have their way with. As for SaveCopyAs don't think you need to save a copy of an unsaved workbook, right? Have fun!
Assuming you saved some file such as "xyz.xlsx",
call something like
Shell("cmd /c ..pathto...xyz.xlsx")
what it will do is to launch cmd prompt as a conduit to launching the program
registered for xlsx. It will work for any registered extension such as pdf.
I'm working with importing a fixed text file into excel file using VBA.
I had a problem fixing the fitting of columns (auto fit) also with the decimal of numbers.
I have a Decimal as much as this 5027.1202024.0000.0000.000.0000.0000.0000 and would like to simplified to just 5027.12 since my columns is not fitting and just separating. is there another way besides declaring several arrays and fixing it's width? the text file is somehow fixed already.
I'm still new to vba I would appreaciate every help. Thanks
EDIT:
Option Explicit
Sub ImportPrepayment()
Dim fpath
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
'Call import_TExtFileR12
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
fpath = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If TypeName(fpath) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
x = 1
Set wkbTemp = Workbooks.Open(FileName:=fpath(x))
wkbTemp.Sheets(1).Copy
Set wkbAll = ActiveWorkbook
wkbTemp.Close (False)
wkbAll.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
x = x + 1
While x <= UBound(fpath)
Set wkbTemp = Workbooks.Open(FileName:=fpath(x))
With wkbAll
wkbTemp.Sheets(1).Move After:=.Sheets(.Sheets.Count)
.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=sDelimiter
End With
x = x + 1
Wend
Range("A17:XFD" & x).Delete shift:=xlUp
'Range("A1").Value = "Supplier Name"
' Range("C1").Value = "Supplier Number"
'Range("D1").Value = "Inv Curr Code"
'Range("E1").Value = "Payment Cur Code"
'Range("F1").Value = "Invoice Type"
'Range("G1").Value = "Invoice Number"
'Range("H1").Value = "Voucher Number"
'Range("I1").Value = "Invoice Date"
'Range("J1").Value = "GL Date"
'Range("K1").Value = "Invoice Amount"
'Range("L1").Value = "Witheld Amount"
'Range("M1").Value = "Amount Remaining"
'Range("N1").Value = "Description"
'Range("O1").Value = "Account Number"
'Range("P1").Value = "Invoice Amt"
'Range("Q1").Value = "Withheld Amt"
'Range("R1").Value = "Amt Remaining"
'Range("S1").Value = "User Name"
Call ProcessUsedRange
Columns.EntireColumn.HorizontalAlignment = xlCenter
Columns.EntireColumn.AutoFit
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Set wkbTemp = Nothing
Exit Sub
ErrHandler:
If Err.Number <> 0 Then MsgBox Err.Number & " " & Err.Description
Resume ExitHandler
End Sub
Sub ProcessUsedRange()
Dim r As Range
Dim regex As Object, Match As Object
Set regex = CreateObject("VBScript.RegExp")
With regex
.Pattern = "\d{4}.\d{4}.\d{4}.\d{3}.\d{4}.\d{4}.\d{4}"
.Global = True
End With
For Each r In ActiveSheet.UsedRange
If regex.Test(r.Text) Then
For Each Match In regex.Execute(r.Value)
r.Value = "'" & Replace(r.Value, Match.Value, "")
Next
End If
Next
End Sub
Instead of using TextToColumns or Workbooks.OpenText; just read the text file and process the data.
Sub ImportPrepayment2()
Dim fpath As Variant
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim Text As String
On Error GoTo terminatemsg
Set wb = Excel.ActiveWorkbook
Set ws = Excel.ActiveSheet
fpath = Application.GetOpenFilename(Filefilter:="text Files(*.txt; *.txt), *.txt; *.txt", Title:="open")
If fpath = False Then Exit Sub
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Text = getTextfileData(fpath)
If Len(Text) Then
ProcessData Text
AdjustDates
Else
MsgBox fpath & " is empty", vbInformation, "Import Cancelled"
Exit Sub
End If
Columns.EntireColumn.AutoFit
Sheets(1).Move Before:=wb.Sheets(1)
terminatemsg:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
If Err.Number <> 0 Then MsgBox Err.Number & " " & Err.Description
End Sub
Sub ProcessData(Text As String)
Dim x As Long, y As Long, z As Long
Dim data, vLine
data = Split(Text, vbCrLf)
x = 2
Range("A1:R1").Value = Array("Supplier Name", "Supplier Number", "Inv Curr Code CurCode", "Payment CurCode", "Invoice Type", "Invoice Number", "Voucher Number", "Invoice Date", "GL Date", "Invoice Amount", "Withheld Amount", "Amount Remaining", "Description", "Account Number", "Invoice", "Withheld", "Amt", "User")
For y = 0 To UBound(data)
If InStr(data(y), "|") Then
vLine = Split(data(y), "|")
If Not Trim(vLine(0)) = "Supplier" Then
For z = 0 To UBound(vLine)
vLine(z) = Trim(vLine(z))
If vLine(z) Like "*.*.*.*.*.*.*.*" Then vLine(z) = Left(vLine(z), InStr(vLine(z), ".") + 2)
Next
Cells(x, 1).Resize(1, UBound(vLine) + 1).Value = vLine
x = x + 1
End If
End If
Next
End Sub
Sub AdjustDates()
Dim x As Long
For x = 2 To Range("B" & Rows.Count).End(xlUp).row
If Cells(x, "R") = vbNullString Then Cells(x, "M").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Next
End Sub
Function getTextfileData(FILENAME As Variant) As String
Const ForReading = 1
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.OpenTextFile(FILENAME, ForReading)
getTextfileData = MyFile.ReadAll
MyFile.Close
End Function
Add this code before Columns.EntireColumn.AutoFit.
Sub ProcessUsedRange()
Dim r As Range
Dim regex As Object, Match As Object
Set regex = CreateObject("VBScript.RegExp")
With regex
.Pattern = "\d{4}.\d{4}.\d{4}.\d{3}.\d{4}.\d{4}.\d{4}"
.Global = True
End With
For Each r In ActiveSheet.UsedRange
If regex.Test(r.Text) Then
For Each Match In regex.Execute(r.Value)
'The apostrophe is to keep the data formatted as text
r.Value = "'" & Replace(r.Value, Match.Value, "")
Next
End If
Next
End Sub
You should also change
MsgBox Err.Number & " " & Err.Description
to
If Err.Number <> 0 then MsgBox Err.Number & " " & Err.Description