简体   繁体   中英

How to output the result on different cell? (VBA Excel 2007)

I have calculated some values and there should be two results. I want to display these result in two different cell.

When I have changed A1 or A2 value, excel is stopped. Is there anyway I can display the values?

Sheet1 
Private Sub Worksheet_Change(ByVal Target As Range)
   Call DisplayResult 
End Sub

Module1 
Sub DisplayResult() 
     Range("A3").Value = Range("A1").Select.Value + Range("A2").Select.Value     
     Range("B3").Value = Range("B1").Select.Value + Range("B2").Select.Value 
End Sub

you don't need to use .select at all here -

Worksheet Code:

Private Sub Worksheet_Change(ByVal Target As Range)

If Not Intersect(Sheet1.Range("A1:B2"), Target) Is Nothing Then
    MsgBox "Hello"
End If

End Sub

Module Code:

Sub DisplayResult()

Sheet1.Range("A3").Value = Sheet1.Range("A1").Value + Sheet1.Range("A2").Value
Sheet1.Range("B3").Value = Sheet1.Range("B1").Value + Sheet1.Range("B2").Value

End Sub

If you put the Call DisplayResult line in your Worksheet_Change sub routine without limiting what range it should be triggered on, then it will end up going into an infinite loop (DisplayResult triggers the Worksheet_Change sub). When should the DisplayResult code be triggered? Only when you have changed Range A1:B2 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM