I have 2 sheets sheet1 and sheet2 in an excel 2007 file.
In sheet2 I have a column that is managed by a form/macro(with a tree view control). When an element has been selected, the cell is filled with an "x", when it has been unselected, the cell is filled with "" (nothing).
In sheet1 I want to create a column equal to the sheet2 column.
So for example: if sheet2!C24 = "x" then sheet1!c24 should also be "x"
I also would like it to work both ways. If the user changes sheet1!c24 to "x", then I want sheet2!c24 to take the same value.
Problems:
- in Sheet1, I tried sheet1!c24 = sheet2!c24, but then when sheet2!c24 = "", sheet1!c24 displays 0 instead of nothing
- in Sheet2, I tried sheet2!c24 = sheet1!c24, but then the cells display the formula (='sheet1!c24') instead of the value...
So basically, what I want is that whatever change you do, in sheet1 or in sheet2, both columns in sheet1 and sheet2 are updated...
How can I achieve this?
What I think you need to do is use the Worksheet_Change events for both sheets and if a change is made in the column you are interested in, then you update the same cell in the other sheet.
Something like this would go in the worksheet code module:
Private Sub worksheet_change(ByVal target As Range)
Dim c As Range
'Test to see if the cell just changed is
'in the column we are interested in
Set c = Application.Intersect(target, Range("A:A"))
If Not c Is Nothing Then
'Copy across to other sheet
If Not beingEdited Then
beingEdited = True
Sheet1.Range(target.Address) = target.Value
beingEdited = False
End If
End If
End Sub
You'd need a beingEdited variable to be declared somewhere else with larger scope so that you could avoid the events triggering themselves and Excel getting stuck in a loop.
In the other sheet you'd basically have the same procedure, except that it would reference the first worksheet, e.g. Sheet1.Range(target.Address) = target.Value.
Obviously, you'd have to tweak this to your ranges/sheets.
You've got the right idea, but you probably need to turn off events before making the change, otherwise you'll end up in a loop
Private Sub worksheet_change(ByVal target As Range)
application.enableevents = false
sheet1.range("c24").value = sheet2.("c24").value
application.enableevents = true
end sub
Just make sure you enable events again at the end.
i did something like this where i had a summary sheet and a tests sheet. When I added a new value in tests sheet and it passed (P) a cell in summary sheet will keep increment. This is to keep a count of how many tests passed. here it is:
COUNTIF(tests!$C$5:$C$1017, "P");
hope this helps.
Related
I have 2 in-cell data validation lists in Excel. Both cells contain dropdown arrows pointing to 2 columns of a table. What I would like is for when 1 cell contains a value, the other cell contains the value from the corresponding row in the table, but its own column, and vice-versa.
So if I select a value from the dropdown in cell1 it overwrites cell2, if I select a value from the dropdown in cell2 it overwrites cell1
i.e. for a table GoalTbl with columns cl and d; a cell named cl_val contains a data validation list pointing to GoalTbl[cl]. Another cell called d_val points to GoalTbl[d]
And so to get a d_val based on cl_val I use a formula like =INDEX(GoalTbl[d],MATCH(cl_val,GoalTbl[cl],0))
Similarly to get a value for cl_val based on d_val, =INDEX(GoalTbl[cl],MATCH(d_val,GoalTbl[d],0))
I can't put these formulae in their respective cells for 2 reasons:
Since each formula refers to the other cell, I would get a circular reference
If I use the drop-down arrow to select a value, it overwrites the formula in that cell
So can I get this linked functionality by changing the lists that the data validation points to - or with a VBA approach?
I suppose this is a combination of a dynamic default formula for a validation, and an overwriting mechanism for 1 cell based on the other - 2 areas I'm not sure how to tackle simultaneously with formulae.
Thanks for the pointer towards Worksheet_Change, I have a VBA approach;
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, [cl_val]) Is Nothing Then
With Application.WorksheetFunction
UI False
[d_val] = .Index([Goaltbl[d]], .Match([cl_val], [Goaltbl[cl]], 0))
UI True
End With
ElseIf Not Intersect(Target, [d_val]) Is Nothing Then
With Application.WorksheetFunction
UI False
[cl_val] = .Index([Goaltbl[cl]], .Match([d_val], [Goaltbl[d]], 0))
UI True
End With
End If
End Sub
Where UI is simply a Sub* to turn on/off screen updating and events (I have a Worksheet_Calculate macro elsewhere which I don't want triggered)
Still, a function approach would be nice to know about - I'm sure something can be done by changing the list input
*UI code for reference
Public Sub UI(t As Boolean)
Application.EnableEvents = t
Application.ScreenUpdating = t
End Sub
im looking for some basic help with VBA. I have created a userform for fellow members to fill out information when we go on a call. When ok is pressed, the data is sent to sheet2 and laid in the next open row. In sheet 3 i have the printable form of the userform that i made out. I am trying to write the vba code in the printable form, so when the call # changes in cell b2, it will automatically change all other cells in that form, with the corresponding data in the same row from sheet 2.
Im new to the forum so im not sure how to upload etc. but i will try and give an example below.
Sheet2 looks something like this, for the example each cell seperated by "."
18-170001.01/02/17.Accident."current address"."call info"
18-170002.01/02/17.Training."current address"."call info"
in sheet4 this is the code i am using and it is not working
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Long
For i = 5 To Row.Count
If sheet4 .cells(b2).value=sheet2.Cells(i,1).value then
sheet4.cells(e2).value=sheet2.cells(i,1).value
End If
Next i
End Sub
I would add additional if then statments for each cell in sheet 4 to match each cell in sheet 2.
Please any help is appreciated
You can't use Cells(b2), it needs to be Range("B2") or Cells(2, "B") or Cells(2, 2).
So your code could be:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Long
For i = 5 To Row.Count
If sheet4.cells(2, "B").value=sheet2.Cells(i,1).value then
sheet4.cells(2, "E").value=sheet2.cells(i,1).value
End If
Next i
End Sub
But you would be better off just using a formula for this purpose instead. For example, the above code could be replaced by having the following formula in cell E2 of sheet4:
=VLOOKUP(B2,Sheet2!A:A,1,FALSE)
(That assumes that sheet2 has a sheet name of "Sheet2".)
I am trying to detect if there are changes in a cell value, not particularly the cell contents. I have found multiple solutions to find out if a cell contents has changed, but it does not work when a cell is equal to another cell.
For example, I have cell A1 set to equal B1 and then B1 has a formula that calls in multiple other cells, so I am not able to go back to the beginning and determine whether the cell has changed from that. It needs to come directly from A1.
This is one of the examples I found on this site, but does not determine if the value of A1 has changed, just whether the contents has changed.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 1 Then
Cells(Target.Row, 3).Value = Date
End If
End Sub
The function application.volatile TRUE at the top of your sub will make your sub calculate each time any value in Excel changes. So then you need a global variable which stores the last-known value of your specified range, and any time the sub runs, start with an
If new_cell_value <> stored_global_variable then...
and close with
stored_global_variable = new_cell value'
End If
See here for further info [h/t to vzczc for the original answer and method]: Refresh Excel VBA Function Results
I have a two (very long) TO-DO lists- one going across and the other going down.
What i want to achieve is for a blank cell to appear at the start of the list instead of having to scroll to the end of the lists to enter a new item.
So then when i have entered an item in a cell and hit enter, i want the cell just populated to move down the list (or across if i hit tab) and a new empty cell to appear at the start of the list.
It would be useful for the new blank cell to be pre-populated with the current date but that is not essential.
Thanks for your help.
NOT FOR POINTS.
Piggy-backing on Gary's answer, the mistake is that you set A to Range("C4:C6"). What happens is, when you enter data into any of C4, C5, and C6, they are all moved to the right because of A.Insert, which refers to all the cells assigned to A.
The trick here is to fully qualify your requirements for Target. Let's say you have a table from B1:E3, like below:
Now, let's say you want to move row 1 if you enter something into A1, row 2 if A2, etc. The following macro should do it (notice the difference with Gary's macro):
Private Sub Worksheet_Change(ByVal Target As Range)
Dim QualifyingRange As Range
'Dim OrigRng As String
Set QualifyingRange = Range("A1:A3")
If Intersect(Target, QualifyingRange) Is Nothing Then Exit Sub
Application.EnableEvents = False
'OrigRng = Target.Address
Target.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
'Range(OrigRng).Value = Date
Application.EnableEvents = True
End Sub
What is the difference in the above? Very simple but very important. When a Worksheet_Change is in a sheet's code, every time you do a valid change to the sheet, the macro fires. The range you just edited will be known to the macro as Target. Now, usually, if you don't declare what the qualifications for Target are, the Worksheet_Change macro just fires indiscriminately. How do we qualify Target properly then?
We use Intersect. First, we declare a range of cells that we want to track. These cells, when changed, should fire the macro. Otherwise, macro is kaput. This line: If Intersect(Target, QualifyingRange) Is Nothing Then Exit Sub basically reads: If Target is not inside my desired range, then nothing happens.
This is the reason why I declared A1:A3 as my QualifyingRange. This way, if my change is to any of the cells above, the macro will fire. HOWEVER, .Insert should not be applied to the whole range but to Target alone. This is because if we do QualifyingRange.Insert, every time a change is detected in any cells in A1:A3, all three rows will move. This is what happened when you set A to three cells and kept A.Insert.
Hopefully, this clears up the confusion. Let us know if this helps.
Here is a partial solution. The following event macro monitors entry to cell A1 . Once you have entered a value in A1, the macro "pushed" the values in column A down by one. This means that value you just entered has been pushed down to A2 and A1 is empty:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim A As Range
Set A = Range("A1")
If Intersect(A, Target) Is Nothing Then Exit Sub
Application.EnableEvents = False
A.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Application.EnableEvents = True
End Sub
Because it is worksheet code, it is very easy to install and automatic to use:
right-click the tab name near the bottom of the Excel window
select View Code - this brings up a VBE window
paste the stuff in and close the VBE window
If you have any concerns, first try it on a trial worksheet.
If you save the workbook, the macro will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx
To remove the macro:
bring up the VBE windows as above
clear the code out
close the VBE window
To learn more about macros in general, see:
http://www.mvps.org/dmcritchie/excel/getstarted.htm
and
http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx
To learn more about Event Macros (worksheet code), see:
http://www.mvps.org/dmcritchie/excel/event.htm
Macros must be enabled for this to work!
EDIT#1
To push across rather than down:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim A As Range
Set A = Range("A1")
If Intersect(A, Target) Is Nothing Then Exit Sub
Application.EnableEvents = False
A.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Application.EnableEvents = True
End Sub
To handle multiple cells, you must specify which cells get pushed across and which cells get pushed down.
Objective: If any values in A1:A2 on sheet 1 change, then the values in A1:A2 on sheet 2 should automatically update with these values. The following sheet 1 event handler fails to work:
Private Sub Worksheet_Calculate()
Application.EnableEvents = False
Dim target As Range
Set target = Range("A1:A2")
If Not Intersect(target, Sheets(2).Range("A1:A2")) Is Nothing Then
Range("A1:A2").Value = Sheets(2).Range("A1:A2").Value
End If
Application.EnableEvents = True
End sub
As usual, VBA's mind-numbingly opaque syntax is my downfall. Any advice in implementing the above simple task would be appreciated, as would referral to a VBA reference guide that is actually useful in explaining the hidden minutia of VBA.
As others have said, you need to put the event handler in the sheet to be monitored.
Worksheet_Change will respond to changes made by the user. If a cell changes for other reasons, eg a formula calculating, then this event is not called.
Worksheet_Calculate will respond the the sheet recalculating. It has no concept of which cells on the sheet changed. To use it in your use case, either copy the cells regardless and accept it will do some unnecassary copies, or track the values of A1:A2 yourself to copy on change
Notes on your code:
Unqualified references to Range refer to the worksheet your code is in. So does Me.
You can reference a sheets CodeName to to refer to a specific sheet regardless of what the user calls it or moves it.
Trying to do an Intersect of ranges on different sheets makes no sence and will error
Sheets(1) and Sheet1 may not be the same worksheet. The Sheets collection index is in the order the sheets are displayed in Excel, and can be changed by the user.
Here's a refactor of your code (put this in Sheets 1 module to copy changes on sheet 1 to sheet 2)
Private Sub Worksheet_Calculate()
If Sheet2.Cells(1, 1).Value <> Me.Cells(1, 1).Value Or _
Sheet2.Cells(1, 2).Value <> Me.Cells(1, 2).Value Then
Application.EnableEvents = False
Sheet2.Range("A1:A2").Value = Me.Range("A1:A2").Value
Application.EnableEvents = True
End If
End Sub