我有一个包含以下公式的单元格(例如,在' Sheet-1'中的B2):
='Sheet-2'!B2+'Sheet-3'!B3-'Sheet-4'!B4
现在我想要VBA代码可以访问在该单元格中输入的公式中包含的引用(即Sheet-1中的B2),然后转到这些引用并对这些引用的单元格进行更改。
答案 0 :(得分:1)
稍微扩展z的评论。
Range(<cell>).Precedents
返回表示<cell>
引用的所有单元格的VBA范围,例如如果单元格A1具有公式=B1+D1
,则Range("A1").Precedents = Range("B1,D1")
扩展此项以进一步满足您的问题要求,然后我们可以使用For Each
循环遍历此范围内的单元格,如下例所示:
Public Sub AmendPrecedents(fromCell As Range)
Dim rngReferredTo As Range
Dim cell As Range
Set rngReferredTo = fromCell.Precedents
For Each cell In rngReferredTo
'Do something with this cell, in this case we're just coloring the background red
cell.Interior.Color = RGB(255, 0, 0)
Next cell
End Sub