EXCEL VBA for permutation and combinations calculations [closed] - excel

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am completely new to Excel VBA, and I'm trying to write code to do a simple task.
There are 3 Worksheets in an Excel: Summary, Discount, Price
Worksheet Summary contains data as below:
Dropdown (Data in B1 and B3):
Type: Supermarket,Hopcoms
Product:Dairy,Meat,Combo
Category:Chicken,Eggs,Eggs+Chicken
Worksheet Discount contains data as below:
Worksheet Price contains data as below:
Tasks:
User in Summary Sheet selects Data in B1:B3 through drop down list.
Based on the selection , Discount in % should be selected for corresponding combination from Discount Sheet
For Ex : If user selects Supermarket-Combo-Eggs+Chicken in Summary Sheet(from #1) , total discount availed should be 13%(as per Discount Sheet).
User navigates to Price sheet and enters data in Total Price column for each customer
When User clicks Calculate Discount button now 13% discount should be applied on Total Price for all customer and discount amount should be updated in Discount Availed column
Total Discount price provided to all customers should be updated next to T.Discount.
Apologies for any mistakes, could anyone please resolve this?
Please let me know for any questions

Test the next code, please. But before that, please insert another column in Price worksheet, between existing "Customer" (B:B) and "Total Price" (C:C) and name it "Price". There the user will fill the standard price (without any discount) and in "Total Price" the the price will be calculated applying the discount:
Sub TestApplyDiscount()
Dim shS As Worksheet, shD As Worksheet, shP As Worksheet, lastRowP As Long
Dim strType As String, strProd As String, strCat As String, i As Long, j As Long
Dim rowType As Long, rowProd As Long, rowCat As Long, disc As Double
Set shS = Worksheets("Summary")
Set shD = Worksheets("Discount")
Set shP = Worksheets("Price")
lastRowP = shP.Range("A" & Rows.count).End(xlUp).Row
strType = shS.Range("B1").value
strProd = shS.Range("B2").value
strCat = shS.Range("B3").value
With WorksheetFunction
rowType = .Match(strType, shD.Range("A1:A19"), 0)
rowProd = .Match(strProd, shD.Range("B" & rowType & ":B" & rowType + 8), 0)
rowProd = rowProd + rowType - 1
rowCat = .Match(strCat, shD.Range("C" & rowProd & ":C" & rowProd + 3), 0)
rowCat = rowCat + rowProd - 1
disc = shD.Range("D" & rowCat).value
End With
For i = 2 To lastRowP
shP.Range("E" & i).value = disc & "%"
shP.Range("D" & i).FormulaR1C1 = "=RC[-1]-(RC[-1]*RC[1])"
Next i
End Sub
I am waiting for some feedback...

Related

Cycle through a list of Investors and calculate the XIRR for each one to automate process

So I have been stuck on this problem for a few days. I have looked at some others codes but I am still coming up short. I am not the best at VBA either.
I have a list of investors with their attached payments and dates. I am trying to run a command button that will go through each Account, find their related payments and dates, run the XIRR function and then place the XIRR value at the bottom to the right of each account. This is simple enough to do by hand but when you have a spreadsheet of 15000 cells+ it becomes tedious and I am trying to automate this process. It becomes difficult because each investor has different payment amounts so to find the correct location to place the XIRR value has also stumped me.
Here is an example of my spreadsheet
Dim i As Integer
Dim x As Double
Dim dateArray() As Date
Dim dateStrings() As String
Dim valArray() As Double
ReDim dateArray(Dates.Count)
ReDim valArray(Trans.Count)
ReDim dateStrings(Dates.Count)
'Sheets("InvestorList").PivotTables.GetPivotData("Account", "x") = i
'Sheets("AccountPayments").Find ("i")
End Sub
Public Function MyXIRR(Dates As Range, Trans As Range, Balance As Double)
For i = 1 To Dates.Count
dateArray(i - 1) = Dates.Item(i).Value
Next i
For i = 1 To Trans.Count
valArray(i - 1) = Trans.Item(i).Value
Next i
'Set the date on the "Balance" line to one day after the last transaction date
dateArray(Dates.Count) = DateAdd("d", 1, Dates.Item(Dates.Count))
valArray(Trans.Count) = -1 * Balance
For i = 0 To Dates.Count
dateStrings(i) = Format(dateArray(i), "mm/dd/yyyy")
Next i
MyXIRR = Application.WorksheetFunction.Xirr(valArray, dateStrings)
End Function
So I counseled with a college and he helped reduce my code to something much simpler and cleaner. I ran this code with data and it worked great. Some spot checking may be needed if an XIRR value doesn't appear right but this helps automate the process.
Private Sub CommandButton1_Click()
Dim myrow As Integer
Dim startrow As Integer
Dim valuerange As String
Dim daterange As String
Dim investor As String
myrow = 2
startrow = 2
investor = Cells(myrow, 1)
Do Until Cells(myrow, 1) = ""
If Cells(myrow + 1, 1) <> investor Then
'We are at the end of the list for the current investor.
daterange = "R" & startrow & "C2:R" & myrow & "C2"
valuerange = "R" & startrow & "C3:R" & myrow & "C3"
Cells(myrow, 4) = "=XIRR(" & valuerange & ", " & daterange & ")"
startrow = myrow + 1
investor = Cells(myrow + 1, 1)
End If
myrow = myrow + 1
Loop
End Sub
I would recommend trying the macro recorder to just record your steps... If you are unsure how to do so, here are the steps!
In Excel:
File
Options
Customize ribbon (left panel)
Choose commands from: (dropbox) select "Main Tabs"
Select developer
Click add>>
Click ok
Click developer tab now on top ribbon
Click record macro (top left corner)
Name macro, set shortcut and description if desired
Do what you want the macro to do.
When you completed it for one investor click stop recording
Click Macros in top left
Select the macro you just made and click edit
Should have a skeleton routine to work into your loop

Macro VBA Excel sum by Group [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I know in Excel we can use pivot table, but I just want to make a button to sum a group by Vendor, this is the illustrate of my table in Excel:
I just want to sum Amount grouping by Vendor in new column and add 1 column to proof that column has a value bigger than 2,550,000.
Like this result when I hit a button "RUN":
I need using macro because we have dynamic data from pivot table (SSAS) and always change everyday, so I have to make sure the new column in this excel to provide the data
Following formula can be used to sum the D column group by A column.
=IF(A2=A1,"",SUMIF(A:A,A2,D:D))
Then you can put the condition in F column.
=IF(ISNUMBER(D2),IF(D2>255000,TRUE,FALSE),"")
And you can use the following VBA code to write the above formula:
Private Sub Test()
Dim i As Integer
Dim Condition As Variant
Dim AVal As Variant
For i = 1 To 10 'replace 10 with last row count
Condition = "A" & i & "=A" & i - 1
AVal = "A" & i
Worksheets("Sheet1").Range("E" & i).Formula = "=IF(" & Condition & ","""",SUMIF(A:A," & AVal & ",D:D))"
DVal = "D" & i
Worksheets("Sheet1").Range("F" & i).Formula = "=IF(ISNUMBER(" & DVal & "),IF(" & DVal & ">255000,TRUE,FALSE),"""")"
Next i
End Sub

Generate serial numbers and barcodes as per logic defined based on the count mention in certain cell

I need to generate lot numbers for my products and since my software doesn't auto generate them, I have defined a logic in Excel for the same. It is quite basic and combines data in 2 or more cells to create a unique code.
To be more specific, I shall introduce our operations to you. We have a few collection centers for our products and we require them to apply lot number labels onto their bags of coffee before transferring it to our main warehouse. I have created an excel sheet in which I enter the current date in one cell and select the name of the center in another which then generates a lot number for the same. For example, cell A1 has today's date and A2 has center 'MBR' selected. The formula in cell C2 =IF(A2="MBR","MB:"&TEXT(A1,"YYYYMMDD")&"-001",IF(A2="MAY","AY:"&TEXT(A1,"YYYYMMDD")&"-001",IF(A2="MZM","MM:"&TEXT(A1,"YYYYMMDD")&"-001",""))) shall give me a result as MB:20171010-001
Now comes the tricky part. I want to mention in cell A3 the number of lots to be generated. For example, if I say I want 10 labels, then the formula should give me 10 labels from "-001" to "-010." If possible, it could start with the number which I would define in possibly cell A4 and then give me the sequence as required.
Lastly, I use this info to generate barcodes using an add-on in excel which I downloaded from the internet which converts the text into barcodes and then I can print them. I have tried barcode fonts but they don't work at all. If you have another alternative to this where I could generate sequential lot numbers based on the logic defined and create barcodes for the same, please share it with me. If not, please give me a formula which will work with excel.
Enter your data in columns A - C, run the bit of sample code below, result is in column D. You can modify the code to suit your needs but here is a start for you:
Public Sub RunTags()
Dim oWS As Worksheet
Dim lRow As Long
Dim lNextTagRow As Long
Set oWS = Worksheets("Sheet1")
lRow = 2
lNextTagRow = 2
Do Until oWS.Range("A" & lRow) = ""
Select Case oWS.Range("A" & lRow)
Case "MBR"
PrintTags oWS, lNextTagRow, "MB:", oWS.Range("B" & lRow), oWS.Range("C" & lRow)
Case "MAY"
PrintTags oWS, lNextTagRow, "MA:", oWS.Range("B" & lRow), oWS.Range("C" & lRow)
Case "MZM"
PrintTags oWS, lNextTagRow, "MZ:", oWS.Range("B" & lRow), oWS.Range("C" & lRow)
End Select
lRow = lRow + 1
Loop
End Sub
.
Private Sub PrintTags(ByRef oWS As Worksheet, ByRef lTagRowStart As Long, sPrefix As String, lQty As Long, lStart As Long)
Dim x As Long
Dim dtNow As Date
dtNow = Now()
For x = lStart To lStart + lQty - 1
oWS.Range("D" & lTagRowStart) = sPrefix & Format(dtNow, "YYYYMMDD") & "-" & Format(x, "000")
lTagRowStart = lTagRowStart + 1
Next x
End Sub

Subtraction in the Excel

I would like to create an excel template for warehouse. In this template are integrated warehouse, sellings and invoices.
I already wrote a code that transfers data to sellings every time I create an invoice and click a button. I would like to integrate in my code function that can do corrections in my warehouse i.e. when I fill an invoice I put items ID, description, amount and a price. After I click a button I want the items amount in the warehouse sheet to decreased by the same amount as in invoice.
The biggest issue for me was how to write a code that takes information from invoice sheet (ID and items amount), look for exact matches in the warehouse sheet and in the warehouse sheet column "I"(stock) decrease stock with the same amount.
sheet1 - name sheet "warehouse". ID in the column "C"; stock - column "I"; data starts from row "4"
sheet3 - name sheet "invoice". ID in the merged column "A""B"(column 1); amount that I sell in the merged column "S""T""U" (column 4); data starts from row 15 as you can see in the code below.
My code that transfers data to sellings (sheet2). I need to integrate function into this code without creating another button.
Sub Button4_Click()
Dim x As Long
Dim erow As Long
'Calculate starting rows
x = 15
With Worksheets("Sellings")
erow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Row
End With
With Worksheets("Invoice")
Do While .Cells(x, 1) <> ""
'The next line copies values to Sheet2
Worksheets("Sellings").Range("A" & erow & ":Z" & erow).Value = .Range("A" & x & ":Z" & x).Value
'increment row counters
x = x + 1
erow = erow + 1
Loop
End With
End Sub

VBA: Loop to map figures from 2 different workbooks

I have 2 different excel workbooks, one is called DATA and one is called ReportTemplate. So now i need to insert data from DATA to corresponding row/column in ReportTemplate.
How I am doing now is, for example:
'Others ( this is for other currencies)
DATA_FILE.activate
Sheets("SA_FX_2").select
SRC_SA_FX_2_D25 = Range("D25").Value
SRC_SA_FX_2_E25 = Range("E25").Value
SRC_SA_FX_2_F25 = Range("F25").Value
SRC_SA_FX_2_G25 = Range("G25").Value
SRC_SA_FX_2_H25 = Range("H25").Value
REPORTTEMPLATE_FILE.activate
Sheets("SA_FX_2").select
Range("D36").Value = SRC_SA_FX_2_D25
Range("E36").Value = SRC_SA_FX_2_E25
Range("F36").Value = SRC_SA_FX_2_F25
Range("G36").Value = SRC_SA_FX_2_G25
Range("H36").Value = SRC_SA_FX_2_H25
The SRC_SA_FX_2_X25 is to store the values for that particular cells in DATA, then insert it into Range("X36").Value in REPORTTEMPLATE. So currently I am doing the "mapping" in a hard-coded way.
This is how my DATA looks like:
DATA TEMPLATE
And this is how my REPORTTEMPLATE looks like:REPORTTEMPLATE
For the "Others" and above currencies, they are all fixed, so I can just hard code the cells.
However, if there is any new currency, my macro should detect that, then choose the currency in the drop down list, and do the mapping.
How can I actually parameterize my codes above in order to the mapping for the rest of the currencies?
Thank you for your advice.
A simple way would be to MATCH them like:
'we look for rows 3 to 5 of DATA_FILE in REPORTTEMPLATE_FILE
Dim i As Long, OutRow As Variant, wsIn As Worksheet, wsOut As Worksheet
Set wsIn = DATA_FILE.Sheets("SA_FX_2")
Set wsOut = REPORTTEMPLATE_FILE.Sheets("SA_FX_2")
For i = 3 To 5
'get the row of the active item in REPORTTEMPLATE_FILE
OutRow = Application.Match(wsIn.Cells(i, 3).Value2, wsOut.Columns(3), 0)
If Not IsNumeric(OutRow) Then OutRow = Application.Match("-- Please Select Currency --", wsOut.Columns(3), 0) 'not there -> new line
wsOut.Range("C" & OutRow & ":H" & OutRow).Value2 = wsIn.Range("C" & i & ":H" & i).Value2
Next
Just change the For i = 3 To 5 to fit your needs and check, if the "-- Please Select Currency --" does match.
If you have any questions or problems, just ask ;)

Resources