将公式的一部分从相对引用更改为绝对引用

时间:2017-11-08 10:17:45

标签: excel vba excel-formula

我正在努力解决细胞参考问题。我在单元格B2中有以下公式:

=INDEX(Sheet2!C:C,MATCH(A2,Sheet2!A:A,0))

接下来,我使用自动填充功能确保直到最后一行的所有单元格都具有此公式。在C列中,我有静态/硬值,它们是"领先"。我需要将C列中的值从最大到最小排序。如果我这样做,公式会在电子表格中移动。 例如,单元格B2中的新公式为:

=INDEX(Sheet2!C:C,MATCH(A210,Sheet2!A:A,0))

所以,理想情况下,我想确保MATCH(A2)转换为MATCH($A$2),第3行中的公式为:

=INDEX(Sheet2!C:C,MATCH(A3,Sheet2!A:A,0))

但是,我使用以下VBA模块来创建公式:

Range("B2").Select
With Range("B2")
    .Formula = "=INDEX(Sheet2!C:C,MATCH(A2,Sheet2!A:A,0))"
    .AutoFill Destination:=Range("B2:B" & LastRow)
End With

这使得从一开始就无法使用锁定的$A$2

我知道以下功能:

Application.ConvertFormula(Formula:=oRange.Formula, fromreferencestyle:=Application.ReferenceStyle, toabsolute:=xlAbsolute)

但是,我正在努力解决如何将此功能插入到我的宏中。如果我使用以下宏:

Range("M2").Select
With Range("M2")
    .Formula = "=INDEX(Sheet2!C:C,MATCH(A2,Sheet2!A:A,0))"
    .AutoFill Destination:=Range("M2:M" & LastRow)
End With                                                         
Range("M2:M" & LastRow).Formula = Application.ConvertFormula(Formula:="=INDEX(Sheet2!C:C,MATCH(A2,Sheet2!A:A,0))", fromreferencestyle:=Application.ReferenceStyle, toabsolute:=xlAbsolute)

我在每行中都得到以下公式:

 =INDEX(Sheet2!$C:$C,MATCH($A$2,Sheet2!$A:$A,0))

我很感激帮助!

3 个答案:

答案 0 :(得分:0)

据我所知,你的问题是锁定MATCH函数的第一个参数并在填写时同时更新它,对吗?如果是这样,您可以填写未锁定版本的公式,然后使用替换添加美元符号。见下文:

Dim rng As Range
Dim cl As Range

Set rng = "define your range here"
For Each cl In rng
    cl.Formula = Replace(cl.Formula, "MATCH(A" & cl.Row, "MATCH($A$" & cl.Row)
Next cl 

这是你在找什么?

答案 1 :(得分:0)

Try assigning cells in your formula to variables. When you bring the variables into formulas use the .address or .addresslocal properties to freeze or keep relative references.

Dim MyMatch as range
Set MyMatch = range("a2")

range("m2").formula = “INDEX(Sheet2!C:C,MATCH(” & MyMatch.Address & “,Sheet2!A:A,0))”

答案 2 :(得分:0)

我想感谢你们的回答。 你的两种方法都有效,但是由于行数很多,宏需要很长时间才能运行。 最后,我缩短了这一点并使用以下宏实现了我想要的结果:

Range("A1").Select
ActiveWindow.DisplayFormulas = True
Cells.Select
Selection.Replace What:="Sheet1!B", Replacement:="Sheet1!$B", LookAt:=xlPart _
    , SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
ActiveWindow.DisplayFormulas = False

尽管如此,谢谢你的时间。