sheet cell linking?

K

KisH \(Tihomir\)

Hello,
I have sheet1 and sheet2.
In sheet1 (A1) I need to write number 5.
In sheet2 (A2) I need to write number 3.
Then, when I enter number 3 in sheet2 (A2) it automaticly needs to correct
number 5 from sheet1
to number 2 ( so it does 5-3=2).
How can I do this?
Thanks in advance.
 
G

Gary''s Student

Insert the following worksheet event macro in the Sheet2 code area:

Private Sub Worksheet_Change(ByVal Target As Range)
Set ws1 = Sheets("Sheet1")
Set s1a1 = ws1.Range("A1")
Set ws2 = Sheets("Sheet2")
Set s2a2 = ws2.Range("A2")
If Intersect(Target, s2a2) Is Nothing Then Exit Sub
Application.EnableEvents = False
s1a1.Value = s1a1.Value - s2a2.Value
Application.EnableEvents = True
End Sub


Because it is worksheet code, it is very easy to install and use:

1. right-click the tab name near the bottom of the window
2. select View Code - this brings up a VBE window
3. paste the stuff in and close the VBE window

If you save the workbook, the macro will be saved with it.

To remove the macro:

1. bring up the VBE windows as above
2. clear the code out
3. close the VBE window

To learn more about macros in general, see:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

To learn more about Event Macros (worksheet code), see:

http://www.mvps.org/dmcritchie/excel/event.htm
 
K

KisH \(Tihomir\)

Gary''s Student said:
Insert the following worksheet event macro in the Sheet2 code area:

Private Sub Worksheet_Change(ByVal Target As Range)
Set ws1 = Sheets("Sheet1")
Set s1a1 = ws1.Range("A1")
Set ws2 = Sheets("Sheet2")
Set s2a2 = ws2.Range("A2")
If Intersect(Target, s2a2) Is Nothing Then Exit Sub
Application.EnableEvents = False
s1a1.Value = s1a1.Value - s2a2.Value
Application.EnableEvents = True
End Sub


Script is not working good..
When I enter in sheet2 number 3 I get number 2 in sheet1,and thats ok.
but when I delete number 3 in sheet2 and enter it again, I got number -1 in
sheet1 , then enter again ,and I get -4 , and so on...
Where is the problem?
Thanks.
 
G

Gary''s Student

The first time you run the script, it subtracts the 3 from the 5 and puts 2
in the cell.
The second time you run the macro, it subtracts 3 again, so now the result
is -1:

5-3-3 => -1


The third time you run the macro, it subtracts 3 again, so now the result is
-4:

5-3-3-3 => -4
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top