Optimizing my VBA code with a loop

jalrs

Active Member
Joined
Apr 6, 2022
Messages
300
Office Version
  1. 365
Platform
  1. Windows
Hello guys,

So on the last weeks I managed to optimize my current code with the help of Kevin9999, Mumps and Joe4. Credits to them. Currently my situation is that the code that I managed to get takes 7 clicks for each department to trigger the last action. My boss thinks this is too much, so I need help optimizing it.

1st action is regarding copying the filtered data and pasting into respective template according to the criteria.
2nd action is to save the template with a specific name, so the file can next follow as attachment with the correct name, avoiding losing the template and having to create a new one from the start.
3rd action is to send the e-mails.

I would like to know if it's possible to complete all actions through a loop, so instead of having 7 clicks for each action for each department, 3 clicks would make it, since I'm pretending to loop.

The dropbox files I'm uploading don't have any lines of code, since I created a brand new bogus information folder to share with whoever may help me.
Next you can find the code for whole process of Apoio SP department, as of now, as an example:

1st action:
VBA Code:
Sub filtroApoioSP()

    Dim wb1 As Workbook, wb2 As Workbook
    Dim ws1 As Worksheet, ws2 As Worksheet
   
    Set wb1 = ThisWorkbook
    Set wb2 = Workbooks("T_ApoioSP.xlsm")
   
    Set ws1 = wb1.Worksheets("Stock Trânsito")
    Set ws2 = wb2.Worksheets("Pendentes")
   
    ws2.UsedRange.Offset(1).ClearContents
   
    Dim lr1 As Long, lr2 As Long
   
    lr1 = ws1.Cells(Rows.Count, 1).End(3).Row
    lr2 = ws2.Cells(Rows.Count, 1).End(3).Row + 1
   
    With ws1.Range("A5:AV" & lr1)
   
        .AutoFilter 46, "Apoio SP"
        .AutoFilter 47, "Em tratamento"
        .Offset(1).Copy ws2.Cells(lr2, 1)
       
        With ws1.Range("BH6:BH" & lr1)
       
           .Copy ws2.Cells(2, 49)
          
        End With
       
        .AutoFilter
       
    End With
   
    lr2 = ws2.Cells.Find("*", , xlFormulas, , 1, 2).Row + 1
    ws2.Range("A" & lr2 & ":A1001").EntireRow.Delete
   
    wb2.Activate
   
    ws2.Activate
   
    Dim lr3 As Long
   
    lr3 = Cells(Rows.Count, "AT").End(xlUp).Row
   
    If lr3 > 1 Then
   
        Range("AY2:AY" & lr3).FormulaR1C1 = _
            "=IF(RC[-1]="""","""",VLOOKUP(RC[-1],TAB_FDB!C[-50]:C[-49],2,0))"
           
    End If
       
End Sub

2nd action:
VBA Code:
Sub copyPTApoioSP()

Dim path As String
Dim filename As String

path = "C:\Users\joafrodrigue\Desktop\prototipo\Difusao\"
filename = "ST_até31032022_Apoio SP"
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs filename:=path & filename & ".xlsx", FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = True

End Sub

3rd action:
VBA Code:
Sub mailptApoioSP()

Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

strbody = "<BODY style = font-size:12pt; font-familt:Arial>" & _
"Olá equipa, <br><br> Envio este e-mail com os pendentes em questão, até à data, em anexo.<br><br>" & _
"Cumprimentos,<br>João Rodrigues"

On Error Resume Next
    With OutMail
        .To = Cells(2, 11).Value
        .CC = Cells(2, 12).Value
        .BCC = Cells(2, 13).Value
        .Subject = Cells(2, 14).Value
        .Display
        .HTMLBody = strbody & .HTMLBody
        .Attachments.Add "C:\Users\joafrodrigue\Desktop\prototipo\Difusao\ST_até31032022_Apoio SP.xlsx"
       
    End With
    On Error GoTo 0

Set OutMail = Nothing

End Sub

Here is the share folder file share
There should be two folders inside main folder called "attachments" and "finaldocname"

I think the "Instructions" Sheet is clear on what I pretend, assuming it is possible.
Macro sheets (1,2,3,4) are there because on the instructions, the source columns to copy are different within each macro as you can see on instruction sheet. All of these are located inside Stock.xlsm

Any additional information regarding the "AS-IS" code just ask.
I hope my "TO-BE" is possible.

Thanks for your attention!
 
Last edited:
Unfortunately, I do not have the ability to download any files from my current location. That being said, I have a feeling that will only overcomplicate matters (where I keep imploring you to simplify things). You should be able to ask very specific, pointed questions.

I almost get the impression that you are looking something more like a consultant, someone to kind of advise you and help you work through this whole project. That is really not what this forum was designed for (not is it designed to "teach" people broad subjects like VBA). It is not meant to take the place of consultants or Excel/VBA courses, it is designed to deal with very pointed, specific Excel/VBA questions.

If you are looking to go the Consulting route, while we don't offer consulting services directly, there are people we can suggest, as noted here: Consulting Services

A notes on my previous code.
- It can be applied to any sheet by either selecting that sheet at the top of the code, or by using/setting sheet references in your code (see: VBA Guide To Referencing Worksheet Tabs — TheSpreadsheetGuru). You can even set up an array of sheet names and loop through them.
- Note that my code is "dynamic". It finds the last row in column AT at the time it runs. So if that ending spot changes, it is not a problem for the code since it dynamically finds the ending when it runs.

You can also set up your procedures to take in parameters (since you mentiond that).
See: Calling Sub and Function procedures (VBA)
I know you can't download files from your spot, you told me that once, that's why I suggested dropbox as you suggested.
What is supposed to happen inside the loop is already coded through individual routines, that's why I suggested uploading the file to dropbox, would make it easier to both of us.

But alright Joe, thanks for the effort, I won't take more of your time.

For context: I'm not looking for consulting services, I'm not the owner of the company, I don't get paid for being here 9 to 5.
I'm just allocated to a company in order to finish the last lecture I have to finish my Bsc. The lecture is not related to VBA, the lecture is related to logistics, where optimization is needed. Happens that I got allocated to a VBA project. That's it.

Not meant to be rude, and sorry if it sounded like, at this point I just wanna finish this. I didn't need you to tell me this was a big task, I'm not the problem here, as you can conclude, I believe. I tried to explain that to my boss, I mean, she didn't refuse, but "I see too many things locked on the code, the goal is to parametrize through cell values, If I add a new area, I'm not supposed to go to code and copy paste and making the required changes, I should just write new area name on cell A7, for example on macro 1, and the code would do the rest etc etc"

Anyways, I'll just open a new thread, on other language questions, and hopefully get some help and get the desired results, otherwise I don't know. I just don't want to sacrifice another year of studies because of one lecture, nor my sanity. And yes, I will address to this topic when opening new one, as per forum rules regarding cross-posting.

I'd like to reinforce that I truly appreciate the time you spent on this, even though we couldn't get to any conclusion.

Once again, thanks Joe.
 
Upvote 0

Excel Facts

What is =ROMAN(40) in Excel?
The Roman numeral for 40 is XL. Bill "MrExcel" Jelen's 40th book was called MrExcel XL.
Sloppy programming or not, here is the solution I came up with.

VBA Code:
Sub myloopattempt()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
Dim lr1 As Long, lr2 As Long, lr3 As Long, lr4 As Long, i As Long
Dim mypath As String, docname As String, valorfiltro As String

Set wb1 = ThisWorkbook
Set ws1 = wb1.Worksheets("Stock")
Set ws2 = wb1.Worksheets("MACRO 1")

lr1 = ws1.Cells(Rows.Count, "A").End(xlUp).Row
lr2 = ws2.Cells(Rows.Count, "A").End(xlUp).Row

ws2.Activate

    For i = 2 To lr2
        
        valorfiltro = Cells(i, 1).Value
        
        Workbooks.Open Filename:=ThisWorkbook.Path & "\Temp\ST_TEMPLATE_" & Cells(i, 1).Value & ".xlsx"
        
        Set wb2 = Workbooks("ST_TEMPLATE_" & valorfiltro & ".xlsx")
        
        Set ws3 = wb2.Worksheets("Pendentes")
        
        ws3.Activate
        
        ws3.UsedRange.Offset(1).ClearContents
        
        lr3 = ws3.Cells(Rows.Count, "A").End(xlUp).Row + 1
        
        ws1.Activate
        
        With ws1.Range("A5:AV" & lr1)
        
            .AutoFilter 46, valorfiltro
            .AutoFilter 47, "Em tratamento"
            
            With ws1
        
            .Range("A6:AV" & lr1).Copy ws3.Cells(2, 1)
            .Range("BH6:BH" & lr1).Copy ws3.Cells(2, 49)
            
            End With
            
            .AutoFilter
        
        End With
        
        lr3 = ws3.Cells.Find("*", , xlFormulas, , 1, 2).Row + 1
        ws3.Range("A" & lr3 & ":A1001").EntireRow.Delete
        
        wb2.Activate
        
        ws3.Activate
        
        lr4 = Cells(Rows.Count, "AT").End(xlUp).Row
        
        If lr4 > 1 Then
        
            Range("AY2:AY" & lr4).FormulaR1C1 = _
            "=IF(RC[-1]="""","""",VLOOKUP(RC[-1],TAB_FDB!C[-50]:C[-49],2,0))"
            
        End If
        
        ws3.Protect Password:="blabla", _
        DrawingObjects:=True, _
        Contents:=True, _
        Scenarios:=True, _
        UserInterfaceOnly:=True, _
        AllowFormattingCells:=False, _
        AllowFormattingColumns:=False, _
        AllowFormattingRows:=False, _
        AllowInsertingColumns:=False, _
        AllowInsertingRows:=False, _
        AllowInsertingHyperlinks:=False, _
        AllowDeletingColumns:=False, _
        AllowDeletingRows:=False, _
        AllowSorting:=True, _
        AllowFiltering:=False, _
        AllowUsingPivotTables:=False

        mypath = ThisWorkbook.Path & "\Anexos\"
            
        wb1.Activate
        
        ws2.Activate
        
        docname = Cells(i, 5).Value
        
        wb2.Activate
        
        ws3.Activate
        
        ActiveWorkbook.SaveAs Filename:=mypath & docname & ".xlsx", FileFormat:=xlOpenXMLWorkbook
    
        ActiveWorkbook.Close
        
    Next i
    
Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

VBA Code:
Sub mailmacro1()

Dim OutApp As Object
Dim OutMail As Object
Dim ws1 As Worksheet, ws2 As Worksheet
Dim lr As Long, i As Long

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

Set ws1 = ThisWorkbook.Worksheets("PainelControlo")
Set ws2 = ThisWorkbook.Worksheets("MACRO 1")

ws2.Activate

lr = Cells(Rows.Count, "A").End(xlUp).Row

    On Error Resume Next

        For i = 2 To lr
        
            Set OutMail = OutApp.CreateItem(0)

                With OutMail
    
                    .To = Cells(i, 2).Value
                    .CC = Cells(i, 3).Value
                    .Subject = Cells(i, 4).Value
                    .Body = Cells(i, 7).Value
                    .Display
                    .Attachments.Add ThisWorkbook.Path & "\Anexos\" & Cells(i, 5).Value & ".xlsx"
        
                End With
    
        Next i

    On Error GoTo 0
    
    Set OutMail = Nothing

ws1.Activate

End Sub

Thanks for the helpers along the project! Now only some minor things to go through. Credits to them, read #1.
 
Upvote 0
Solution

Forum statistics

Threads
1,223,230
Messages
6,170,883
Members
452,364
Latest member
springate

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top