如何在不同的单元格上输出结果?(VBA Excel 2007)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14379055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 19:13:22  来源:igfitidea点击:

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

excel-vbavbaexcel

提问by jeeunit02

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?

当我更改 A1 或 A2 值时,excel 停止。无论如何我可以显示这些值吗?

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

采纳答案by MattCrum

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

你根本不需要在这里使用 .select -

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 DisplayResultline 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 ?

如果您将该Call DisplayResult行放入 Worksheet_Change 子例程中,而没有限制应该触发的范围,那么它将最终进入无限循环(DisplayResult 触发 Worksheet_Change 子程序)。什么时候应该触发 DisplayResult 代码?仅当您更改 Range A1:B2 时?