Add total to column where row header meets criteria - excel

Apologies beforehand for this, I'm very new to VBA and I'm sure this is simple coding that I'm struggling with.
Based on a user defined number of months (just entered into the ssheet) I have a row of column headings giving the month number and the heading "Total" after the last month.
i.e. User says 12 months, cell A2 = "Jan-15" and M2 = "Total".
Underneath the headings the user then adds some sales data.
What I need to do is use VBA to add a total to the end of each of the rows of data where the header = "total".
I was thinking an If Then makes sense but I'm struggling with how to get the macro to put the formula in the correct cell and then have the formula look at the variable range. This is the best I've come up with so far (please don't laugh!)
Sub Add_total()
Dim criteria As String
criteria = Range("A:A").Value
If criteria = "Total" Then
Range("12:12").Select
ActiveCell.Formula = "=sum($c12:c12)"
End If
End Sub
What I'd like is, for example, where M2 = "Total", then C12 = sum(c1:L12)
I realise the easiest way would be to just get the user to add the total themselves or have a total column far away to the left of the sheet but this is going across the business and needs to restrict manual input/guarantee accuracy of the calcs.
Any help much appreciated.

Why not simply put in cell M3 the function =sum(A3:L3) and copy downwards?
If you need it in VBA anyway should this work:
Sub testsum()
i = 3 'start in cell3
While Not IsEmpty(Cells(i, 1))
Cells(i, 13) = WorksheetFunction.Sum(Range((Cells(i, 1)), (Cells(i, 12))))
i = i + 1
Wend
End Sub

Thanks very much for that - not quite what I needed but you pointed me in the direction. Went for the following in the end:
Sub Total() Set Find_total = Range("6:6").Find("Total",_
LookIn:=xlValues,searchorder:=xlByColumns)
Set Revenue_total = Find_total.Offset(rowoffset:=3, columnoffset:=-1)
Set Revenue_cell = Find_total.Offset(rowoffset:=3, columnoffset:=0)
Revenue_cell = WorksheetFunction.Sum(Range((Cells(9, 2)), Revenue_total))
End Sub
Thanks again

Related

How to copy the number if contains certain number (first 4 digit) to another column - EXCEL VBA

I'm trying to search on the specific column(E), and if matched with the first 4 digit, I would like to copy the number to a different column.
Column E is where i would like to paste all the random number(dynamic)
Column A/B/C is static where i would add 4 digits from time to time.
Column I/J/K is where is would like to paste the result.
PS:
I'm doing it manually and would really appreciate if someone can help me out with the automation hence no code is provided. :(
Having ExcelO365 means you may use FILTER(). Therefor try the below:
Formula in I2:
=FILTER($E:$E,ISNUMBER(MATCH(--LEFT($E:$E,4),A:A,0)))
Drag right to K2. Now, this is dynamic and will change accordingly upon data entry in column E:E, or changing values in A:C.
this is the code to execute on sheet 1, it goes through the entire column E and validates through the formula of counting if in each of the first three columns and assigns the value found in the corresponding columns.
Sub macro()
Dim Static_Data As String
Dim Sht As Worksheet
Set Sht = ThisWorkbook.Sheets("Hoja1")
Active_row = 2
Do While Sht.Range("E" & Active_row).Value <> ""
Static_Data = Sht.Range("E" & Active_row).Value
For i = 1 To 3
If Application.WorksheetFunction.CountIf(Sht.Columns(i), Mid(Static_Data, 1, 4)) > 0 Then
Sht.Cells(Sht.Cells(Rows.Count, i + 8).End(xlUp).Row + 1, i + 8).Value = Static_Data
End If
Next i
Active_row = Active_row + 1
Loop
End Sub
For Excel versions that don't support FILTER or as an alternative you can use standard formulas for this.
If you use columns F-H as helper columns (and these columns can be hidden) then the formula in F2 will be:
=IF(NOT(ISERROR(VLOOKUP(VALUE(LEFT($E2,4)),A$2:A$100,1,FALSE)))=TRUE,$E2,"")
The formula can then be copied across and down. This will find your matches.
In order to then remove the blanks from the data you can use the following formula in I2 and again copy across and down. Depending on how many numbers you want to add in, you may want to extend the range A$2:A$100 in the top formula and F$2:F$100 in the bottom formula
=IFERROR(INDEX(F$2:F$100,AGGREGATE(15,6,(ROW(F$2:F$100)-ROW(F$2)+1)/(F$2:F$100<>""),ROWS(I$2:I2))),"")

Getting Excel to Copy Data From One Cell to Another Depending on Date

Apologies in advance as this is my first time posting something on this site and am not the best at explain issues.
I have a spread sheet, this has production data such as meters daily, meters monthly etc. These values are updated by adding TAGS from a PLC using Rockwell VantagePoint Excel add-in (if your unfamiliar with this it shouldn't matter this part is not what I am struggling with)
I need I way to copy data from one cell to another cell on the same sheet at month end. Basically the Meters monthly field needs to copied into another cell at the end of the month to record meters run for that month. The monthly meters run resets back to 0 at the end of the month.
Basically I need to copy the value in J7 into the corresponding month in W column at the end of that month. If it could ignore the year that would be advantageous as I don't need it to keep the old values and would mean I just need one column.
I have some experience at MS-Excel, also VBA but mainly in MS-Access never in MS-Excel. If answers could be explained as simply and hands on as possible it would be appreciated.
After Googling the issue I came across this formula and changed the ranges to fit my sheet but Excel doesn't like it saying it contains an error
=QUERY( A1:B6; "select B where A =date """&TEXT(TODAY();"yyyy-mm-dd")&""" "; 0
Sorry again if I haven't explained myself properly.
If your workbook isn't guaranteed to be open at the end of each month I would update the value every time it gets opened, like(Should be placed in ThisWorkbook):
'Runs when you open the workbook
Private Sub Workbook_Open()
'Loops through U3 to the last used cell in that column
For Each c In Range(Cells(3, 21), Cells(Rows.Count, 21).End(xlUp))
'Applies the J7 value to the current month and exits the sub
If Month(c) = Month(Now) Then c.Offset(, 2).Value = [J7]: Exit Sub
Next c
End Sub
Also, not that it matters but, I would apply the following formula in U3:U14 to always get the correct dates:
=EOMONTH(DATE(YEAR(TODAY()),ROW()-2,15),0)
Okay, I'm still not super sure what the question is and I know more Access VBA than Excel VBA, but here's something that might help to find a solution.
You can make a check date function that returns a Boolean value:
Public Function EoMonthCheck() As Boolean
Dim eo_month As Date, today As Date
eo_month = Format(WorksheetFunction.EoMonth(Now(), 0), "yyyy-MM-dd")
today = Format(Now(), "yyyy-MM-dd")
If today = eo_month Then
EoMonthCheck = True
Else
EoMonthCheck = False
End If
End Function
And the,, to add a value to the "W" column, we might use something like this:
Public Function AppendValue(Optional target_cell As String = "J7")
''' This could be a subroutine, too, I guess, since we're not returning anything.
Dim i As Integer
''' Activate whatever sheet you want to work with
Worksheets("Sheet1").Activate
If EoMonthCheck() = True Then
''' Look up the bottom of the 'W' column and find the first non-empty cell
''' Add 1 to that cell to get you to the next cell (the first empty one).
i = Cells(Rows.Count, "W").End(xlUp).Row + 1
''' Set the value of that empty cell in the 'W' column to the value of 'J7'
''' which will happen after we evaluate whether it is the end of the month.
Cells(i, "W").Value = Range(target_cell).Value
End If
Then, you could maybe trigger that each time the workbook opens.

How can I calculate the sum of the numbers of two columns for only a portion of the rows?

Say I have an Excel sheet with 10,000 rows and two columns. All 20,000 cells are filled with numbers and there is no missing data. I want to have a third column, the values of which are the sum of Column A and Column B. For example, C70 = A70 + B70, and C82 = A82 + 82, and the like.
The only problem is I want to do it for only a portion of the rows, say from row 125 to row 8954. I don't care about the rest of the values. And I don't want to do it by dragging the grid using the mouse. Is that possible?
If you have access to SEQUENCE() (Currently only available to Office 365 Insiders) then yes it is possible:
=INDEX(A:A,SEQUENCE(1000,,ROW(),1))+INDEX(B:B,SEQUENCE(1000,,ROW(),1))
Where 1000 is the number of rows desired. Place the formula in the first cell desired and it will automatically fill the rest.
I believe you need some logic about what is going on, related to the start and end row.
You can use an if-statement or sumifs() for this... will do an if-statement so i can specify not meeting the requirements as null.
With Start row as 2 and end row as 4 (see image), you can use this formula, and drag it down to the bottom of all columns:
=IF(AND(ROW(A2)<=F$2,ROW(A2)>=E$2),SUM(A2:B2),"")
Notice in the image that C5 has no value; this is due to the conditions of the if-statement being false.
Another idea, a simple macro that will do what you want by asking the user what the starting and end row is.
Sub test()
Dim startrow As Integer 'variable to hold first row
Dim endrow As Integer 'variable to hold last row
startrow = InputBox("Enter the start row")
endrow = InputBox("Enter the end row")
'loops through you desired range calculating what you want
Dim i As Integer
For i = startrow To endrow
Cells(i, 4).Value = Cells(i, 1).Value + Cells(i, 2).Value
Next
End Sub
Just change the values to suit your needs in what cells you want to add up and where you want the sum to go.

Copy cell range and paste in another worksheet based on the date?

I've scoured the interwebs for any kind of solution and I keep coming up empty so hopefully someone can help me out. I have two sheets, Sheet1 and Inventory. In Sheet1, the user enters the date in B1. In range C4:C200 I have a list of supplies and in range D4:D200 a user enters the number of each of the supplies on hand. In Inventory, the list of supplies is in range A1:A200, and b1:z1 list dates.
I'm trying to create a macro that will look in Sheet1 for the date entered in B1, let's say 4/1/19, copy D4:D200, then look in Inventory, find 4/1/19 in rows b1:z1 and paste the copied data beneath the correct date. So if 4/1/19 is in cell E1, the values would be pasted in E2.
While I'm decent with cell formulas and functions, I'm new to macros, so I'm not sure what to do.. Any help is greatly appreciated!
I tried to write some very basic code in such way you can easily read it. It is not the most sophisticated code but it will do the job. Just a few things i noticed: The number of supplies are in a list 197 long, the sheet Inventory states lists of 200 items...well, you can easily adjust the macro below. Copy past the code in a new module and run it. If you encounter any problems please post the complete workbook and i will have a look. Make sure that cell a1 on inventory is not empty.
Sub DoYourThing()
Dim c As Integer
c = findHorizontal("Inventory", 1, Sheets("Sheet1").Cells(1, 2).Value)
'now we know what column the date is in
For i = 2 To 200
Sheets("Inventory").Cells(i, c) = Sheets("Sheet1").Cells(i + 2, 5)
Next i
End Sub
Function findHorizontal(Sheet As String, row As Integer, Value As Variant) As Integer
'searches a row from left to right until the cells are empty
Dim i As Integer
i = 1
Do While Not IsEmpty(Sheets(Sheet).Cells(row, i))
If Sheets(Sheet).Cells(row, i) = Value Then
findHorizontal = i
Exit Function
End If
i = i + 1
Loop
findHorizontal = -1
End Function

VBA - Enter a formula into all active rows of the current column (when you don't know the column letter, or if the column changes)

Hi guys this is my first post, I'm wondering if you can possibly assist me.
I'd like to write a macro / script that will allow me to put a formula into the column to the right of the currently selected one (for all active rows of the current column) based on what column I've selected. The issue I'm having is that I don't always know the current column letter (as my selection changes from worksheet to worksheet).
To give you an example:
One of my columns currently contains dates, that dates are entered in different formats though, some are separated with ".", some with "-", some with spaces and so on. I have a formula that will deal with this so I need to put this formula in the column to the right of the selected column (which has the dates).
I have been able to do this when I specify the column letter, but not if it changes.
Please can you help?
Give this a go,
Sub SomethingNeat()
Dim rng As Range, x
x = Selection.Column
On Error Resume Next
Set rng = Columns(x).SpecialCells(xlCellTypeConstants, 23)
If Not rng Is Nothing Then rng.Offset(, 1) = "'=MyFormula"
End Sub
You can use ActiveCell.Offset(0,1).Value = Variable
That means that whetever your current cell is you can move and "select" to put a value to the right cell of the one you have activated. You can move the selection using a loop.
Do
Workbooks("Yur workbook name").Worksheets(1).Range(Adress you want to start adding).Offset(0, 1).formula = "=FORMULA"
i = i + 1
ActiveCell.Offset(1, 0).Activate
Loop While i <= max_row
Edit: 2nd
Put the formula in a cell lets say C1
'Select a range
Set take = Worksheets(1).Range("C1")
take.Copy 'copy the formula
Worksheets(1).Paste Destination:=Worksheets(1).Range("B1:B10")
That will copy your function whenever you want it to

Resources