Add value entered in cell to another cell in the same column - excel

I want to add the value entered in a cell in a certain row to another cell in that same column
Example:
If I enter a value in cell B12, add that value to the value in B17.
If I enter a value in cell D12, add that value to the value in D17 and so on.
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Target.Row = 12 Then
Range(Target.Column & 17).Value = Range(Target.Column & 17).Value + Target.Value
End If
Application.EnableEvents = True
End Sub
Problem is, that Target.Column is a integer and not a Character. So the Code will not run, since Range expects a char as column and not an integer (at least that is what I think the debugger wants to tell me).
Greetings,
Maverick

The presumption that Column must be a letter is mistaken. To the contrary, Column is a number which, for users' convenience (not Excel's) is displayed as a letter in some usages. Therefore this code will work.
Private Sub Worksheet_Change(ByVal Target As Range)
With Target
If .Row = 12 Then
Application.EnableEvents = False
Cells(17, .Column).Value = .Value
Application.EnableEvents = True
End If
End With
End Sub
A rule you might go by is to address individual cells using the syntax for addressing cells, which is Cells([Row], [Column]) and use range names only when addressing ranges comprising more than one cell. For this rule you need to understand that ...
When addressing cells, you can use their number or designation. Cells(3, 2) may also be written as Cells(3, "B") but the letter is more complicated and can't be used in calculations.
All ranges have names. But in the absence of a given name VBA will concatenate a name from its first and last cells, like Range("A1:D4"). You can further complicate this concatenation by interjecting other numbers into the name creation (such as you tried).
VBA defines a range by its first and last cells. Therefore VBA's preferred way to address Range("A1:D4") is Range(Cells(1, 1), Cells(4, 4)). That looks effusive but if you are in a position where you have to calculate any of the coordinates you will find that it's the simplest method.

Related

VBA Excel: Write timestamp to cell on change of another cell

I want to insert a timestamp (E3) when the status (B3) changes. This should happen for at least 30 more such examples in the worksheet. The code currently works only for one example (Country1). Do you have an idea how this can be implemented?
I already tried different types but it just worked for example "Country 1" not for "Country 1", "Country 2", "Country 3" etc.
When I adjust the code for the range "B3:I3" then I received an adjustment in every 3rd column, example: I add a comment in D3 then a timestamp will be created in H3. That is not what I want. :(
Is there a way to adjust the code so that as soon as a change is made in the Status column (B3;F3;J3etc.), the Timestamp column (E3;I3 etc.) will reflect the time stamp?
Code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("B3:B5"))
Is Nothing Then Exit Sub
Application.EnableEvents = False
Target.Offset(0,3).Value = Now
Application.EnableEvents = True
Please, try the next adapted event. It will calculate how many groups of four columns exists and set a range of their first column intersected with rows 3 to 5. Only for this range the event will be triggered:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim lastCol As Long, rngCols As Range
lastCol = Me.cells(2, Me.Columns.count).End(xlToLeft).column 'last column on the second row
Set rngCols = Me.Range(trigData(Me.Range("B2", Me.cells(2, lastCol)))) 'create the range of the columns for what the event to be triggered
Set rngCols = Intersect(Me.rows("3:5"), rngCols) 'create the range inside which the change to trigger the event
If Not Intersect(rngCols, Target) Is Nothing Then
Application.EnableEvents = False
Target.Offset(0, 3).Value = Now
Application.EnableEvents = True
End If
End Sub
Function trigData(rngCols As Range) As String
Dim i As Long, strCols As String
For i = 1 To rngCols.Columns.count Step 4 'iterate from four to four and create the necessary columns string address
strCols = strCols & "," & rngCols.cells(i).EntireColumn.address
Next i
trigData = Mid(strCols, 2) 'Mid eliminates the first (unnecessary) comma...
End Function
The code will be confused if you place on the second row data after the necessary groups of four columns. If necessary, one or two such columns, the code can be adapted to work for a fix number extracting the divided integer (without decimals).
The code assumes that you need to be triggered for the mentioned rows (3 to 5). If you need something different in terms of rows to be affected, you should change Me.rows("3:5") according to your need.
Please, send some feedback after testing it.
Your request is a little unclear, and your table format may not have come across correctly in your post. Your code is written to add the current time to a cell 3 columns away from the target cell. It is dynamic, so if you set
If Intersect(Target, Range("B2:I3"))
You are going to get the value in cell 3 columns offset from the changed cell. If you always want it to update column E, then you can use the target.row property...
Cells(Target.Row,5).Value = Now
...to make the row dynamic, and the column static. Clarify your question if this is not what you're looking for. If country2 is in cell F2, where do you want to write the timestamp?
You can use this simple function:
Public Function TimeStamp(Status As Range) As Double
TimeStamp = Now
End Function
So, in Cell E3 will be the formula =TimeStamp(B3). (Format cell E3 appropriately as Time Format)

Runs once, then never again

I posted a question to Stack Overflow about creating a Excel Macro to add/subtract a value in a column from the previous column, then clear the current column.
Excel cell value update macro
The code worked find for years in office 2007, but no longer works in office 365 (2016/2019).
If F1 has a value of £100.00, and I type -50 into G1, F1 changes to £50.00 and G1 is empty.
Each cell in column F is changed by an amount entered into the row in column G.
In Office 365 versions of Excel this macro executes once then won't run again until I close an re-open the document. Has something changed about the way macros work that would cause this?
Edit:
Here is the code (attached to sheet 1), slightly modified from my previous question to work on column G.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim FirstNum As Currency 'Long is for number currency should help keep format
Dim SecNum As Currency
If Target.Column = 7 Then 'Only Runs if Cel l being changed is in column C, Might need to be Columns
FirstNum = Target.Offset(0, -1).Value ' Value in Column B
SecNum = Target.Value ' Value being typed in C
Target.Offset(0, -1).Value = FirstNum + SecNum ' Makes Cell B equal to difference of previous value and value typed in C
'MsgBox ("Difference Found") ' Just to display code worked Remove when confirm code works
Target.Clear ' Clears Value you typed
End If
End Sub
I don't have enough rep to do a comment...
Without seeing your full code it's hard to know. But if your code has
application.enableEvents = false
You will need to to set it back to True eventually. Or worksheet change events won't fire off until the workbook is closed and opened again
I think it is nothing wrong with Office 365...
In order to work as you explain, the code must look like:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim FirstNum As Currency
Dim SecNum As Currency
If Target.Column = 3 Then 'Only Runs if Cell being changed is in column C, Might need to be Columns
FirstNum = Target.Offset(0, -1).Value ' Value in Column B
SecNum = Target.Value ' Value being typed in C
Target.Offset(0, -1).Value = FirstNum - SecNum ' Makes Cell B equal to difference of previous value and value typed in C
Target.Clear
End If
End Sub
But, you must understand that this code works only for changing cells in column C:C.
The variant you received six years before worked only in the same column, but on vertical. I mean, changing of C2, it used to modify C1. But it had a bug. If you try modifying of C1 it will try to set an Offset of -1, row zero does not exist in Excel and returns an error...
I cannot understand how the event functioned at least once for ranges G1, F1. It could work only if some links exists in the sheet, or you adapted the code and in such a case the real used code will give us the possibility to analize and tell you, not supposing, where the problem is. I do not think it is a matter of Office version, but who knows...
It sounds like a formula would suffice. However a cell cannot refer to itself, you could try,
E1: =F1+G1
Where E1 is a new cell with the sum of F1 and G1, because you are entering its sign operator i.e. - or + the you can leave it as addition in cell E1. To use this for a column just drag from the lower left square on the cell E1 all the way down to the row number you want. This will refresh every time a value changes.
excel image

SUMIF returning zero

Here are snippets of two worksheets
This is the code that I have on the first sheet meant for change in selection of the dropdown. There will be more Cases, but my issue is with the SUMIF. Anytime column B on Sheet2 matches the corresponding column A item on Sheet2, sum column C on Sheet2.
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("D1")) Is Nothing Then
Select Case Range("D1")
Case "2014-2015": Cells(2, "B") = WorksheetFunction.SumIf(Worksheets("2014-2015").Range("B2:B22"), A2, Worksheets("2014-2015").Range("C2:C22"))
Case Else: Cells(2, "B") = 8
End Select
End If
End Sub
The problem is that it is always returning 0. Hoping for help as to an edit to the code to make it display the proper total.
Thanks,
It looks like the problem is with the value it is trying to match, specified only as A2 in your Sumif formula. It isn't recognizing that you want to match the value in cell A2. It would need to be referenced with something similar to Worksheets("SummarySheet").Range("A2").Value like you did for the other parameters of that function.

How do I get the current cell number whilst looping through a range of cells (Excel VBA)

I'm trying to get the current cell number whilst looping through a range of cells.
For Each i In Sheet3.Range("A3:A213")
msgbox(Sheet3.Range("B"&currentcellnumberinloop).Value)
Next
The purpose of this is to retrieve a value from another cell in the same row e.g. A1 and B1.
The i is probably declared as Range object(or Variant). Therefore to get the row number and retrieve the value in neighboring B column you have to call the .Row method of the i object
Sub ForEachAndFor()
Dim i As Range
For Each i In Sheet3.Range("A3:A213")
MsgBox Sheet3.Range("B" & i.Row).Value
Next
End Sub
You could also use the Offset(how_many_rows_up_or_down, how_many_columns_left_or_right)
you indicate rows down with a positive number an rows up with a negative number
same applies to the columns, use - to navigate to the left of the current cell, and positive number to the right of the current cell.
Sub ForEachSub()
Dim i as Range
For Each i in Sheet3.Range("A3:A213")
MsgBox i.Offset(0, 1).Value
next i
End Sub
Try this
Dim i as Integer
For Each i In Sheet3.Range("A3:D213").Rows.Count
msgbox(Sheet3.Range("B" & i).Value)
Next i
In your code variable i is of a Range type, thus you have to treat it that way. You can use Offset to get to what is in relation to your i address, like that:
For Each i In Sheet3.Range("A3:A213")
MsgBox (i.Offset(0, 1).Value)
Next i

Excel formula in VBA code

So, in Sheet1 I have base of some names and it looks like this:
In Sheet2 I'm working with these names from Sheet1. I'm doing that in a way that I'm entering Code value in column A and in column B I get the Name, in column C I get the Last Name. That looks like this:
I've done this with formulas, entering it in the formula bar. For column A(or Name) I've used this formula: =IFERROR(VLOOKUP(A2;Sheet1!A:C;2;FALSE);"") and for column B(or Last Name) I've used this one: =IFERROR(VLOOKUP(A2;Sheet1!A:C;3;FALSE);""). I've dragged these formulas to row 20 and it works great.
Now, what I'd like to do is to put these formulas into Excel VBA code and them to work for noted range. I've just started to use VBA and I don't know how to do it in it, tried something but doesn't work, ..., I've done this so far. I'm new to this Excel/Macro/VBA thing so any help would be appreciated.
The below code will work if you type in your Code values in sheet2 and highlight them, and run this macro:
Selection.Offset(0, 1).FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-1],Sheet1!C[-1]:C,2,FALSE),"""")"
Selection.Offset(0, 2).FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-2],Sheet1!C[-2]:C,3,FALSE),"""")"
Selection.Offset(0, 1).Value = Selection.Offset(0, 1).Value
Selection.Offset(0, 2).Value = Selection.Offset(0, 2).Value
Edit: If you are wanting to update values as you type use (thank you #PeterAlbert for added optimisation!):
Private Sub Worksheet_Change(ByVal Target As Range)
'end if the user made a change to more than one cell at once?
If Target.Count > 1 Then End
'stop system activating worksheet_change event while changing the sheet
Application.EnableEvents = False
'continue if column 1(A) was updated
'and
'dont continue if header or row 1 was changed
If Target.Column = 1 And Target.Row <> 1 Then
With Target.Offset(0, 1) 'alter the next cell, current column +1 (column B)
'RC1 = current row and column 1(A) e.g. if A2 was edited, RC1 = $B2
'C1:C2 = $A:$B
.FormulaR1C1 = "=IFERROR(VLOOKUP(RC1,Sheet1!C1:C2,2,FALSE),"""")"
.Value = .Value 'store value
End With
With Target.Offset(0, 2) 'alter the next cell, current column +2 (column C)
'C1:C3 = $A:$C
.FormulaR1C1 = "=IFERROR(VLOOKUP(RC1,Sheet1!C1:C3,3,FALSE),"""")"
.Value = .Value 'store value
End With
End If
Application.EnableEvents = True 'reset system events
End Sub
Explinatioin of RC:
The FormulaR1C1 formula types are good to use when referencing a cell with respect to the current cell. There a few rules to remember:
The R stands for Row and C is for Column and the integer after it, if any, defines the row or column;
As a basis the RC formula references itself;
Any number following the R or C wraped in [] is an offset to itself, e.g. if you are in cell A1 and use R[1]C[1] you would be referencing cell B2;
Also any number following the R and C is an exact, e.g. if you reference R2C2 no matter the cell you are in would also point to B2; and
To complicate things if you were in cell C5, e.g. using Range("C5").FormulaR1C1 = and coded the follwing:
"=RC[-1]" references cell B5
"=RC1" references cell A5, more rightly $A5
"=R[1]C[-2]" references cell A6
"=Sum(C[-1]:C5)" is =Sum(B:E), more rightly =Sum(B:$E)
If I understand your question and comments correctly, you want to ensure that columns B&C always show you the right values based on your formula, but also want to protect (and maybe even hide the formula) from the users.
I'd suggest you use sheet protection instead: all you need to do is to unlock the cells you want the users to edit, i.e. select column A and in the _ Format cells_ dialog uncheck "Locked" in the Protection tab. Similarly for columns B&C, check "Hidden". Now right click the sheet name and select Protect Sheet. Once this is done, the user can edit column A - but will not see the formula in B&C and cannot edit those cells.
If for some reasons you need to ensure this in VBA, use the following code:
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False 'to prevent endless loop
With Target.Offset(, 2 - Target.Column).Resize(, 2)
.FormulaR1C1 = "=IFERROR(VLOOKUP(RC1,Sheet1!C1:C3,COLUMN(RC),0),"""")"
.Value = .Value
End With
Application.EnableEvents = True
End Sub
You need to place this in the module of the worksheet.

Resources