gpt4 book ai didi

vba - 在单元格更改时循环遍历一系列单元格,以将序列中的下一个数字显示为单元格的新值

转载 作者:行者123 更新时间:2023-12-02 19:21:26 25 4
gpt4 key购买 nike

我了解如何循环范围,

For Each cell In Range("A1:A5")
If [condition] Then
End If
Next

我知道 OnChange 事件:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
Set KeyCells = Range("A6")

If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
Call Macro
End If
End Sub

但是我不确定如何实现以下效果:我有一个单元格 A6,它显示公式的“结果”,并且我有另一个单元格 A7,其中包含公式中使用的当前利率,我有多个利率需要执行,所以我'我们将它们声明为一个范围(Interest_Rates)。

我的问题是,一旦 A6 单元格的值发生更改,如何通过声明的范围转到下一个数字,并将其打印在单元格 A7 中以获得该范围内另一个利率的结果,以便我可以打印将其放在表中,然后找到最高的比率。

最佳答案

必须做出一些假设。例如,代码假设您的公式位于单元格 A6 中,并且它实际上如下所示:=SUM(B3/100*A7)。它还假设公式位于名为“Sheet1”的工作表上,并将结果放入工作表“公式结果”的 A 列中。

Sub tgr()

Dim wb As Workbook
Dim wsData As Worksheet
Dim wsDest As Worksheet
Dim rInterestCell As Range
Dim rDest As Range

Set wb = ActiveWorkbook
Set wsData = wb.Sheets("Sheet1")
Set wsDest = wb.Sheets("Formula Results")

For Each rInterestCell In Range("Interest_Range").Cells
wsData.Range("A7").Value = rInterestCell.Value 'Put the interest cell value in range A7, which is used by the formula in A6
wsData.Calculate 'Update the formula result based on the new value in A7
Set rDest = wsDest.Cells(wsDest.Rows.Count, "A").End(xlUp).Offset(1)
If rDest.Row < 6 Then Set rDest = wsDest.Range("A6") 'Guarantee that A6 is the starting cell for the results
rDest.Value = wsData.Range("A6").Value 'Put the value only in a new row in the destination sheet
Next rInterestCell

End Sub

关于vba - 在单元格更改时循环遍历一系列单元格,以将序列中的下一个数字显示为单元格的新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42233706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com