Optimize slow VBA response - excel
I need to optimize the vba code used for database updates in my spreadsheet. It would be great if I can get the maximum optimized code. This macro will put currency conversions directly on the report & having to calculate them (The "Exchanges" tab that this report creates uses historical exchange rates )
Sub ZKDP5M()
Application.ScreenUpdating = False
'Add New sheet for marketplace and currency conversions
Sheets.Add After:=ActiveSheet
Sheets("Sheet1").Name = "Exchange Rates"
Range("A1").Select
' Add Marketplaces and Exchange Rates under a new tab
' Update the exchange rates on this tab with the exchange rates under the "Payment" tab of your KDP Report each month to get accurate royalties.
Range("A1").Select
ActiveCell.FormulaR1C1 = "Marketplace"
Range("B1").Select
ActiveCell.FormulaR1C1 = "Conversion Rate"
Range("B2").Select
Columns("A:A").EntireColumn.AutoFit
Range("A2").Select
ActiveCell.FormulaR1C1 = "US"
Range("B2").Select
ActiveCell.FormulaR1C1 = "1"
Range("A3").Select
ActiveCell.FormulaR1C1 = "UK"
Range("B3").Select
ActiveCell.FormulaR1C1 = "1.35"
Range("A4").Select
ActiveCell.FormulaR1C1 = "DE"
Range("B4").Select
ActiveCell.FormulaR1C1 = "1.12"
Range("A5").Select
ActiveCell.FormulaR1C1 = "JP"
Range("B5").Select
ActiveCell.FormulaR1C1 = "0.01"
Range("A6").Select
ActiveCell.FormulaR1C1 = "CA"
Range("B6").Select
ActiveCell.FormulaR1C1 = "0.76"
Range("A7").Select
ActiveCell.FormulaR1C1 = "IT"
Range("B7").Select
ActiveCell.FormulaR1C1 = "1.12"
Range("A8").Select
ActiveCell.FormulaR1C1 = "ES"
Range("B8").Select
ActiveCell.FormulaR1C1 = "1.11"
Range("A9").Select
ActiveCell.FormulaR1C1 = "FR"
Range("B9").Select
ActiveCell.FormulaR1C1 = "1.68"
Range("A10").Select
ActiveCell.FormulaR1C1 = "NL"
Range("B10").Select
ActiveCell.FormulaR1C1 = "1.12"
Range("A11").Select
ActiveCell.FormulaR1C1 = "IN"
Range("B11").Select
ActiveCell.FormulaR1C1 = "0.01"
Range("A12").Select
ActiveCell.FormulaR1C1 = "AU"
Range("B12").Select
ActiveCell.FormulaR1C1 = "0.72"
Range("A13").Select
ActiveCell.FormulaR1C1 = "BR"
Range("B13").Select
ActiveCell.FormulaR1C1 = "0.26"
Range("A14").Select
ActiveCell.FormulaR1C1 = "MX"
Range("B14").Select
ActiveCell.FormulaR1C1 = "0.05"
Range("B15").Select
Columns("B:B").EntireColumn.AutoFit
Range("A1:B1").Select
Selection.Font.Bold = True
'Preserve Data
'This preserves the original data in your report in case you need it.
Sheets("KENP Read").Select
Sheets.Add
Sheets("Sheet2").Select
Sheets("Sheet2").Name = "KENPBeforeConversion"
Sheets("KENP Read").Select
Range("A1:G2").Select
Selection.Copy
Sheets("KENPBeforeConversion").Select
Range("A1").Select
ActiveSheet.Paste
Sheets("KENP Read").Select
Range("E20").Select
Sheets("KENP Read").Select
Application.CutCopyMode = False
'Columns Work
'I included a "Retailer" column for my own purposes, but this may be useful to you if you want to aggregate this report onto a master spreadssheet. You can simply delete or hide if you do not need it.
Range("A1").Select
Selection.EntireRow.Delete
Columns("A:A").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("A1").Select
ActiveCell.FormulaR1C1 = "Retailer"
Range("B1").Select
ActiveCell.FormulaR1C1 = "Month"
Range("C1").Select
ActiveCell.FormulaR1C1 = "Year"
Columns("B:C").Select
Columns("B:C").EntireColumn.AutoFit
Range("A2").Select
Columns("A:A").ColumnWidth = 20.05
Range("H1").Select
ActiveCell.FormulaR1C1 = "KENP"
Range("K1").Select
ActiveCell.FormulaR1C1 = "GBP Conversion"
Range("L1").Select
ActiveCell.FormulaR1C1 = "DE Conversion"
Range("M1").Select
ActiveCell.FormulaR1C1 = "JPY Conversion"
Range("N1").Select
ActiveCell.FormulaR1C1 = "CAD Conversion"
Range("O1").Select
ActiveCell.FormulaR1C1 = "EUR IT Conversion"
Range("P1").Select
ActiveCell.FormulaR1C1 = "EUR ES Conversion"
Range("Q1").Select
ActiveCell.FormulaR1C1 = "EUR FR Conversion"
Range("R1").Select
ActiveCell.FormulaR1C1 = "EUR NL Conversion"
Range("S1").Select
ActiveCell.FormulaR1C1 = "INR Conversion"
Range("T1").Select
ActiveCell.FormulaR1C1 = "AUD Conversion"
Range("U1").Select
ActiveCell.FormulaR1C1 = "BRL Conversion"
Range("V1").Select
ActiveCell.FormulaR1C1 = "MXN Conversion"
Range("W1").Select
ActiveCell.FormulaR1C1 = "USD Conversion"
Range("X1").Select
ActiveCell.FormulaR1C1 = "AdjustedIncome"
Range("Y1").Select
ActiveCell.FormulaR1C1 = "AdjustedCurrency"
Columns("K:Y").Select
Range("Y1").Activate
Columns("K:Y").EntireColumn.AutoFit
Columns("D:D").ColumnWidth = 37.36
'Currency Conversions
'GBP Currency Conversion
Range("K2").Select
ActiveCell.Formula = "=IF(G2=""UK"",'Exchange Rates'!$B$3*I2,0)"
Range("K2").Select
Range("K2").AutoFill Destination:=Range("K2:K1000" & Cells(Rows.Count, "D").End(xlUp).Row)
'DE Currency Conversion
Range("L2").Select
ActiveCell.Formula = "=IF(G2=""DE"",'Exchange Rates'!$B$4*I2,0)"
Range("L2").Select
Range("L2").AutoFill Destination:=Range("L2:L1000" & Cells(Rows.Count, "D").End(xlUp).Row)
'JPY Currency Conversion
Range("M2").Select
ActiveCell.Formula = "=IF(G2=""JP"",'Exchange Rates'!$B$5*I2,0)"
Range("M2").Select
Range("M2").AutoFill Destination:=Range("M2:M1000" & Cells(Rows.Count, "D").End(xlUp).Row)
'CAD Currency Conversion
Range("N2").Select
ActiveCell.Formula = "=IF(G2=""CA"",'Exchange Rates'!$B$6*I2,0)"
Range("N2").Select
Range("N2").AutoFill Destination:=Range("N2:N1000" & Cells(Rows.Count, "D").End(xlUp).Row)
'EUR IT Currency Conversion
Range("O2").Select
ActiveCell.Formula = "=IF(G2=""IT"",'Exchange Rates'!$B$7*I2,0)"
Range("O2").Select
Range("O2").AutoFill Destination:=Range("O2:O1000" & Cells(Rows.Count, "D").End(xlUp).Row)
'EUR ES Currency Converter
Range("P2").Select
ActiveCell.Formula = "=IF(G2=""ES"",'Exchange Rates'!$B$8*I2,0)"
Range("P2").Select
Range("P2").AutoFill Destination:=Range("P2:P1000" & Cells(Rows.Count, "D").End(xlUp).Row)
'EUR FR Currency Conversion
Range("Q2").Select
ActiveCell.Formula = "=IF(G2=""FR"",'Exchange Rates'!$B$9*I2,0)"
Range("Q2").Select
Range("Q2").AutoFill Destination:=Range("Q2:Q1000" & Cells(Rows.Count, "D").End(xlUp).Row)
'EUR NL Currency Conversion
Range("R2").Select
ActiveCell.Formula = "=IF(G2=""NL"",'Exchange Rates'!$B$10*I2,0)"
Range("R2").Select
Range("R2").AutoFill Destination:=Range("R2:R1000" & Cells(Rows.Count, "D").End(xlUp).Row)
'INR Currency Conversion
Range("S2").Select
ActiveCell.Formula = "=IF(G2=""IN"",'Exchange Rates'!$B$11*I2,0)"
Range("S2").Select
Range("S2").AutoFill Destination:=Range("S2:S1000" & Cells(Rows.Count, "D").End(xlUp).Row)
'AUD Currency Conversion
Range("T2").Select
ActiveCell.Formula = "=IF(G2=""AU"",'Exchange Rates'!$B$12*I2,0)"
Range("T2").Select
Range("T2").AutoFill Destination:=Range("T2:T1000" & Cells(Rows.Count, "D").End(xlUp).Row)
'BRL Currency Conversion
Range("U2").Select
ActiveCell.Formula = "=IF(G2=""BR"",'Exchange Rates'!$B$13*I2,0)"
Range("U2").Select
Range("U2").AutoFill Destination:=Range("U2:U1000" & Cells(Rows.Count, "D").End(xlUp).Row)
'MXN Currency Conversion
Range("V2").Select
ActiveCell.Formula = "=IF(G2=""MX"",'Exchange Rates'!$B$14*I2,0)"
Range("V2").Select
Range("V2").AutoFill Destination:=Range("V2:V1000" & Cells(Rows.Count, "D").End(xlUp).Row)
'USD Currency Conversion
Range("W2").Select
ActiveCell.Formula = "=IF(G2=""US"",'Exchange Rates'!$B$2*I2,0)"
Range("W2").Select
Range("W2").AutoFill Destination:=Range("W2:W1000" & Cells(Rows.Count, "D").End(xlUp).Row)
'Find and Replace illegal characters
Dim sht As Worksheet
Dim fndList As Variant
Dim rplcList As Variant
Dim x As Long
fndList = Array("N/A", "Amazon.com.au", "Amazon.com.br", "Amazon.com.mx", "Amazon.com", "Amazon.co.uk", "Amazon.co.jp", "Amazon.ca", "Amazon.it", "Amazon.fr", "Amazon.es", "Amazon.nl", "Amazon.in", "Amazon.de")
rplcList = Array("0", "AU", "BR", "MX", "US", "UK", "JP", "CA", "IT", "FR", "ES", "NL", "IN", "DE")
'Loop through each item in Array lists
For x = LBound(fndList) To UBound(fndList)
'Loop through each worksheet in ActiveWorkbook
For Each sht In ActiveWorkbook.Worksheets
sht.Cells.Replace What:=fndList(x), Replacement:=rplcList(x), _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next sht
Next x
'Royalty Month autofill
'Get filename
Range("AH2") = "=MID(CELL(""filename""),SEARCH(""["",CELL(""filename""))+1, SEARCH(""]"",CELL(""filename""))-SEARCH(""["",CELL(""filename""))-1)"
Range("AH2").Select
Selection.Copy
Range("AI2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("AJ2").Select
ActiveCell.FormulaR1C1 = "=MID(RC[-1],27,4)"
Range("AJ2").Select
Selection.Copy
Range("C2:C1000").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'RoyaltyYear Autofill
Range("AK2").Select
ActiveCell.FormulaR1C1 = "=MID(RC[-2],32,2)"
Range("AK2").Select
Selection.Copy
Range("B2:B1000").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'Retailer Column Autofill
Range("A2").Select
ActiveCell.FormulaR1C1 = "Kindle Unlimited"
Range("A2").Select
Selection.AutoFill Destination:=Range("A2:A1000"), Type:=xlFillDefault
Range("A2").Select
'Delete unnecessary cells
Range("AH2:AK2").Select
Selection.ClearContents
'Final Cleanup work
Columns("K:K").Select
Selection.ColumnWidth = 22.57
Columns("L:W").Select
Selection.NumberFormat = "$#,##0.00"
Columns("K:K").Select
Selection.Style = "Currency"
Selection.NumberFormat = "$#,##0.00"
Range("W2").Select
Range("X2").Select
ActiveCell.FormulaR1C1 = "=SUM(RC[-13]:RC[-1])"
Range("X2").Select
Selection.AutoFill Destination:=Range("X2:X48"), Type:=xlFillDefault
Range("X2:X48").Select
Range("Y2").Select
ActiveCell.FormulaR1C1 = "USD"
Range("Y2").Select
Selection.AutoFill Destination:=Range("Y2:Y48"), Type:=xlFillDefault
Columns("K:W").Select
Selection.EntireColumn.Hidden = True
'Delete empty rows in Retailer Column if Title Column is blank
On Error Resume Next
Columns("D").SpecialCells(xlBlanks).EntireRow.Delete
'Delete Adjusted Currency Column as no longer needed
Columns("AG:AG").Select
Selection.Delete Shift:=xlToLeft
'Format KENP column as General text
Columns("H").Select
Selection.NumberFormat = "General"
'Save as CSV to directory
'ActiveWorkbook.SaveAs FileName:= _
'"C:\Royalties\KDP\KDP.csv", FileFormat:=xlCSV, CreateBackup:=False
Application.DisplayAlerts = False
Dim fn As String
Dim l As Long
Dim wb As Workbook
Set wb = ActiveWorkbook
fn = wb.FullName
l = InStrRev(fn, ".")
fn = Left(fn, l)
fn = fn & "csv"
wb.SaveAs fileName:=fn, FileFormat:=xlCSV
Application.DisplayAlerts = False
Range("A2").Select
End Sub
Here are two advices:
1: The comment from barvobot is a good approach:
Add the following code at the beginn of your sub to deactivate calculation and screen updating:
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
At the end of your sub activate the calculation and screen updating again:
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
This will make your code faster.
2: You are working a lot with .select. I think this is not a good approach. Here is my suggestion:
Use a Worksheet-variable for your new sheet. So replace your code:
'Add New sheet for marketplace and currency conversions
Sheets.Add After:=ActiveSheet
Sheets("Sheet1").Name = "Exchange Rates"
Range("A1").Select
with:
Dim ws As Worksheet
Set ws = Sheets.Add(After:=ActiveSheet)
ws.Name = "Exchange Rates"
Use the Worksheet-variable to set values and replace the .select. Here is an example:
replace:
Range("A2").Select
ActiveCell.FormulaR1C1 = "US"
Range("B2").Select
ActiveCell.FormulaR1C1 = "1"
Range("A3").Select
ActiveCell.FormulaR1C1 = "UK"
with:
ws.Range("A2").value = "US"
ws.Range("B2").value = "1"
ws.Range("A3").value = "UK"
This will reduce your code enormously.
Related
VBA changes date format
I have a table with data in it and run a macro to neaten things up and then adds a hyperlink to column G but the issue is when the macro has run, the date changes from: https://websitenamehere.com//agentView/agentname#company/2021-11-08 to https://websitenamehere.com//agentView/agentname#company/44508 In my table, I created in column H the column for "today" and then in column G is where it puts it all together but messing up the date part. Here is my code which i am using. Any help would be appreciated. Sub CleanFollowUps() Dim Lrow As Integer Dim lCol As Integer Dim C As Range Lrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row lCol = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column ActiveSheet.ListObjects.Add(xlSrcRange, Range(Cells(1, 1), Cells(Lrow, lCol)), , xlYes).Name = "FollowUps" Range("FollowUps[#All]").Select ActiveSheet.ListObjects("FollowUps").TableStyle = "" Range("F1").Select ActiveCell.FormulaR1C1 = "Helper" Range("F2").Select ActiveCell.FormulaR1C1 = "=IF(SUM([#[Due today]]+[#Late])>0,""Yes"","""")" Range("G1").Select ActiveCell.FormulaR1C1 = "Schedule" Range("H1").Select ActiveCell.FormulaR1C1 = "day" Range("H2").Select ActiveCell.FormulaR1C1 = "=TODAY()" Columns("H:H").Select Selection.NumberFormat = "yyyy-mm-dd" Range("H2").Select Range(Selection, Selection.End(xlDown)).Select Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Range("G2").Select Application.CutCopyMode = False ActiveCell.FormulaR1C1 = _ "=""https://websitenamehere.com/agentView/""&[#Username]&""#company/""&[#day]" Range("G2").Select Range(Selection, Selection.End(xlDown)).Select Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False With Sheets("FU") For Each C In .Range("G2:G" & .Range("G" & .Rows.Count).End(xlUp).Row) .Hyperlinks.Add Anchor:=C, Address:=C.Value, SubAddress:=C.Value Next C End With Application.DisplayAlerts = True End Sub
Setting the default value based on the adjacent cell in VBA
Sub Print_New() ' ' Print_New Macro ' ' ActiveSheet.Unprotect ActiveSheet.Range("$B$7:$G$24").AutoFilter Field:=1, Criteria1:="<>" ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _ IgnorePrintAreas:=False ActiveSheet.Range("$B$7:$G$24").AutoFilter Field:=1 ActiveSheet.Protect Sheets("Bill (1)").Copy Before:=Sheets(5) ActiveSheet.Unprotect Range("C8:C17,D20,E20:F20").Select Range("E20").Activate Selection.ClearContents Range("G20").Select ActiveCell.FormulaR1C1 = "=IF(RC[-2]="""","""",5%)" Range("F8").Select Range("F8").Select ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")" Range("F9").Select ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")" Range("F10").Select ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")" Range("F11").Select ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")" Range("F12").Select ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")" Range("F13").Select ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")" Range("F14").Select ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")" Range("F15").Select ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")" Range("F16").Select ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")" Range("F17").Select ActiveCell.FormulaR1C1 = "=IF(RC[-3]>0,1,"""")" Range("C8").Select ActiveSheet.Protect ActiveWorkbook.Save End Sub Need a proper code instead of any "IF" formula. When I write something in any cell in the range C8:C17, the default value 1 should be equal to the same cell in the range F8:F17. Which can be changed. And when C8:C17 is empty then F8:F17 should also be empty.
Please don't do the constant Select and ActiveCell: you might replace: Range("G20").Select ActiveCell.FormulaR1C1 = "=IF(RC[-2]="""","""",5%)" by: Range("G20").FormulaR1C1 = "=IF(RC[-2]="""","""",5%)" And, instead of using RC, you might do the following: Range("G20").Formula = "=IF(Offset(-2;0)="""","""",5%)" In top of this, you can use the whole range of F8:F17: Range("F8:F17").Formula = "IF(Offset(-3;0)>0,1,"""")" This is already a big decrease of obsolete code.
autofill cells when selecting item in dropdown list from another cell
I'm pretty new to VBA .Here is my problem: I have a dropdown list in A4 with ListItem1 to ListItem7.I want to autofill A6 t0 A11 when selecting ListItem1,ListItem2 ect...I've recorded the Macro: Range("A6").Select ActiveCell.FormulaR1C1 = "67" Range("A7").Select ActiveCell.FormulaR1C1 = "87" Range("A8").Select ActiveCell.FormulaR1C1 = "rty-u" Range("A9").Select ActiveCell.FormulaR1C1 = "kjty" Range("A10").Select ActiveCell.FormulaR1C1 = "erty" Range("A11").Select ActiveCell.FormulaR1C1 = "u" Range("A6:A11").Select Selection.ClearContents Range("A6").Select ActiveCell.FormulaR1C1 = "9867" Range("A7").Select ActiveCell.FormulaR1C1 = "4567" Range("A8").Select ActiveCell.FormulaR1C1 = "ghty" Range("A9").Select ActiveCell.FormulaR1C1 = "3454" Range("A10").Select ActiveCell.FormulaR1C1 = "klii" Range("A6:A10").Select Selection.ClearContents Range("A6").Select ActiveCell.FormulaR1C1 = "23567" Range("A7").Select ActiveCell.FormulaR1C1 = "9867" Range("A8").Select ActiveCell.FormulaR1C1 = "hjytrer" Range("A9").Select ActiveCell.FormulaR1C1 = "bnjg" Range("A10").Select ActiveCell.FormulaR1C1 = "987" Range("A6:A10").Select Selection.ClearContents Range("A6").Select ActiveCell.FormulaR1C1 = "56456" Range("A7").Select ActiveCell.FormulaR1C1 = "9876" Range("A8").Select ActiveCell.FormulaR1C1 = "45678" Range("A9").Select ActiveCell.FormulaR1C1 = "mjtyu" Range("A10").Select ActiveCell.FormulaR1C1 = "nbvc" Range("A11").Select ActiveCell.FormulaR1C1 = "fgtre" Range("A6:A11").Select Selection.ClearContents End Sub Any helps?
Excel VBA - Nested Do While Loop Not Incrementing
I have nested "Do While" loops near the bottom of the below code that are not incrementing. I have stepped through the code, and confirmed that once a non-zero value is found in cell E37 of the "Outages" tab, the code continuously finds a solution for that value instead of incrementing the company code. The company and trading partner numbers are in a matrix from B2:AE31. This is an accounting application to figure out which intercompany accounts do not balance by company and trading partner. Basically, this macro needs to loop through all combination of values for company code and trading partner (1:27 for each). Any help you can give would be appreciated. '4 - Identify outages in table (loop through) Dim i As Integer Dim j As Integer Dim CO As String Dim TP As String Dim MO As Integer Dim SolverValue As Double i = 1 'Company code j = 1 'Trading partner MO = Sheets("Inputs").Range("B1").Value2 Do While i < 28 Range("E34").Value2 = i j = 1 Do While j < 28 Range("E35").Value2 = j Sheets("Outages").Select If Range("E37").Value2 <> 0 Then CO = Range("E34").Value2 TP = Range("E35").Value2 '4a - Run solver for companies if an outage is found ThisWorkbook.Sheets.Add After:=Sheets(Sheets.Count) ActiveSheet.Name = "Solver" Sheets("Transactions").Select Cells.Select Selection.AutoFilter ActiveSheet.Range("$A$1:$R$10000").AutoFilter Field:=2, Criteria1:=MO ActiveSheet.Range("$A$1:$R$10000").AutoFilter Field:=9, Criteria1:=CO, _ Operator:=xlOr, Criteria2:=TP ActiveSheet.Range("$A$1:$R$10000").AutoFilter Field:=11, Criteria1:=CO, _ Operator:=xlOr, Criteria2:=TP ActiveSheet.Range("$A$1:$R$10000").AutoFilter Field:=18, Criteria1:="1" Sheets("Transactions").Select Rows("1:10000").Select Selection.Copy Sheets("Solver").Select Rows("1:1").Select ActiveSheet.Paste Columns("A:A").EntireColumn.AutoFit Cells.Select Cells.EntireColumn.AutoFit Range("Q1").Select Application.CutCopyMode = False ActiveCell.FormulaR1C1 = "=+SUM(R[1]C:R[201]C)" Range("Q2").Select ActiveWindow.SmallScroll Down:=-18 ActiveCell.FormulaR1C1 = "=+RC[-3]*RC[-1]" Range("Q2").Select Selection.Copy Range("Q3:Q203").Select ActiveSheet.Paste Range("P2").Select Application.CutCopyMode = False Selection.Copy Range("P3:P203").Select ActiveSheet.Paste Range("R1").Select ActiveWindow.SmallScroll ToRight:=4 Sheets("Outages").Select Range("E37").Select Selection.Copy Sheets("Solver").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Application.CutCopyMode = False Selection.Copy Selection.Style = "Comma" SolverReset SolverValue = Sheets("Outages").Range("E37") SolverOk SetCell:="$Q$1", MaxMinVal:=3, ValueOf:=SolverValue, ByChange:= _ "$P$2:$P$201", Engine:=2, EngineDesc:="Simplex LP" SolverAdd CellRef:="$P$2:$P$201", Relation:=5, FormulaText:="binary" SolverSolve True Columns("P:R").Select Columns("P:R").EntireColumn.AutoFit '4b - Copy entries causing outages to a list Cells.Select Selection.AutoFilter ActiveSheet.Range("$A$1:$W$201").AutoFilter Field:=16, Criteria1:="1.00" Range("A2:Q1000").Select Selection.Copy Sheets("Transactions Causing Outages").Select Range("A2").Select ActiveSheet.Paste Columns("N:Q").Select Application.CutCopyMode = False Selection.Delete Shift:=xlToLeft Cells.Select Cells.EntireColumn.AutoFit '4c - Delete Solver tab Application.DisplayAlerts = False Worksheets("Solver").Delete Application.DisplayAlerts = True Worksheets("Transactions").ShowAllData 'Unfilter the transactions tab End If j = j + 1 Loop i = i + 1 Loop
Sheets("Outages").Select was out of place.
How to use Vlookup inside VBA with a variable worksheet name
I need to use a vlookup inside vba but the worksheetname constantly changes but can always be referenced as ActiveWorkbook.Worksheet(1) and ActiveWorkbook.Worksheet(2). So I used dim so all selection can refer to ws1 and ws2 but of course inside a vlookup formula that kind of script doesn't work. Hope anyone can help rewrite those vlookup formula lines. It regards the last 5 lines with the ActiveCell.FormulaR1C1 lines where i need a solution for 'ws2'! Thanks for the help. Dim ws1 As Worksheet Dim ws2 As Worksheet Set ws1 = ActiveWorkbook.Worksheets(1) Set ws2 = ActiveWorkbook.Worksheets(2) ws1.Select Selection.AutoFilter Range("G2").Select ActiveCell.FormulaR1C1 = "Web sales" Range("H2").Select ActiveCell.FormulaR1C1 = "Web stock" Range("I2").Select ActiveCell.FormulaR1C1 = "Total Sales" Range("J2").Select ActiveCell.FormulaR1C1 = "Total Stock" Range("F2:F71").Select Selection.Copy ActiveWindow.SmallScroll Down:=-102 Range("G2:J71").Select ActiveWindow.SmallScroll Down:=-66 Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _ SkipBlanks:=False, Transpose:=False Columns("H:H").EntireColumn.AutoFit Range("I5").Select Application.CutCopyMode = False Range("D3:D150").Select ws2.Select Range("D3:D150").Select ws1.Select ActiveWindow.SmallScroll Down:=-66 Range("G3").Select ActiveCell.FormulaR1C1 = _ "=VLOOKUP(RC[-3],'ws2'!RC[-3]:R[42]C[-1],3,0)" ActiveWindow.SmallScroll Down:=-30 ActiveCell.FormulaR1C1 = _ "=VLOOKUP(RC[-3],ws2!R3C4:R45C6,3,0)"
Below are two examples from your original code showing how to include the name of worksheet into formula: ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-3]," & ws2.Name & "!RC[-3]:R[42]C[-1],3,0)" ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-3]," & ws2.Name & "!R3C4:R45C6,3,0)"