如何动态更改此公式

问题描述 投票:0回答:1

我想改变这个:

='D:\Documents\Financial\[m1.xlsm]main'!B$4

对于这样的事情:

="'D:\Documents\Financial\[m" & A1 & ".xlsm]main'!B$4"

A1 的值为 1,A2 的值为 2 并且......

可以吗?

excel vba excel-2010
1个回答
0
投票

工作表更改:在不同文件中引用相同单元格

工作表模块

Sheet1

Private Sub Worksheet_Change(ByVal Target As Range)
    
    Const RETURN_FORMULA As String _
        = "='D:\Documents\Financial\[m<PLACE_HOLDER>.xlsm]main'!B$4"
    
    Const FIRST_CELL As String = "A1"
    Const RETURN_COLUMN As String = "B"
    
    Dim ws As Worksheet: Set ws = Target.Worksheet
    
    Dim trg As Range:
    With ws.Range(FIRST_CELL)
        Set trg = .Resize(ws.Rows.Count - .Row + 1)
    End With
    
    Dim irg As Range: Set irg = Intersect(trg, Target)
    If irg Is Nothing Then Exit Sub
    
    Application.EnableEvents = False
    
    Dim icell As Range
    
    For Each icell In irg.Cells
        ws.Cells(icell.Row, RETURN_COLUMN).Value _
            = Replace(RETURN_FORMULA, "<PLACE_HOLDER>", CStr(icell.Value))
    Next icell
    
    Application.EnableEvents = True

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.