简体   繁体   English

Excel VBA:如何从单元格中的公式访问(参考)范围

[英]Excel VBA : How to access (Referenced) Ranges from Formula in a Cell

I have a cell (such as B2 in 'Sheet-1') containing a formula like: 我有一个单元格(例如“ Sheet-1”中的B2),其中包含以下公式:

='Sheet-2'!B2+'Sheet-3'!B3-'Sheet-4'!B4

Now I want VBA code that can access the references contained in the formula entered in that cell (ie B2 in Sheet-1) and then go to those references and make a change in those referred cells. 现在,我想要VBA代码,该代码可以访问该单元格中输入的公式中包含的引用(即,Sheet-1中的B2),然后转到这些引用并在这些引用的单元格中进行更改。

Expanding on z's comment somewhat. 在某种程度上扩展z的注释。

Range(<cell>).Precedents returns a VBA Range representing all cells referred to by <cell> eg if cell A1 had the formula =B1+D1 then Range("A1").Precedents = Range("B1,D1") Range(<cell>).Precedents返回一个VBA范围,表示<cell>引用的所有单元<cell>例如,如果单元格A1的公式为=B1+D1Range("A1").Precedents = Range("B1,D1")

Expanding this to further fulfil the requirements of your question we can then iterate over the cells within this range using a For Each loop as shown in the example below: 扩展此范围以进一步满足您的问题要求,然后我们可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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