简体   繁体   中英

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-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.

Expanding on z's comment somewhat.

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")

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:

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

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