更改绝对和相对之间的单元格引用

时间:2016-08-08 05:02:45

标签: excel vba excel-vba excel-2010

我想编写一个宏来遍历选择单元格公式中的所有单元格引用,并将它们更改为绝对相对。< / p>

是否有可以更改此格式的格式变量或已经执行此操作的函数(类似于按F4的内容)但是作为宏。

2 个答案:

答案 0 :(得分:6)

您可以使用ConvertFormula方法。

第4个参数确定其是否绝对。 1将其设置为绝对值,4将其设置为相对值。根据对这个答案的一个评论,如果你正在寻找混合引用,那么它有点复杂。但是阅读你的问题和评论,我认为这不是你所追求的。

Examples:
'/ Set it to absolute
ActiveCell.Formula = Application.ConvertFormula(ActiveCell.Formula, xlA1, xlA1, 1)

'/ Set it to relative
ActiveCell.Formula = Application.ConvertFormula(ActiveCell.Formula, xlA1, xlA1, 4)

答案 1 :(得分:2)

我看到你编辑了这个问题,但由于我已经开始研究这个问题,我正在发布一个答案。

如果您不知道该公式包含哪些内容,并希望将Relative更改为Absolute而将Absolute/Mixed更改为Relative,请尝试使用

假设我的Selection中有4个范围,如下所示

![enter image description here

因此我可以使用RegEx建议Here来提取个别地址并找出它的公式,然后根据@cyboashu

的建议进行更改
Const sPattern As String = _
"(['].*?['!])?([[A-Z0-9_]+[!])?(\$?[A-Z]+\$?(\d)+(:\$?[A-Z]+\$?(\d)+)?|\$?[A-Z]+:\$?[A-Z]+|(\$?[A-Z]+\$?(\d)+))"

Sub Sample()
    Dim sMatches As Object, objRex As Object
    Dim rng As Range, aCell As Range
    Dim sFormula As String
    Dim bAbsMix As Boolean, bRel As Boolean

    Set rng = Selection

    Set objRex = CreateObject("VBScript.RegExp")

    With objRex
        .IgnoreCase = True
        .Global = True
    End With

    For Each aCell In rng
        objRex.Pattern = """.*?"""
        sFormula = aCell.Formula
        sFormula = objRex.Replace(sFormula, "")

        objRex.Pattern = "(([A-Z])+(\d)+)"
        objRex.Pattern = sPattern

        If objRex.test(sFormula) Then
            Set sMatches = objRex.Execute(sFormula)
            If sMatches.Count > 0 Then
                For Each Match In sMatches
                    If Len(Match) = Len(Replace(Match, "$", "")) Then
                        bRel = True
                    Else
                        bAbsMix = True
                    End If
                Next Match
            End If
        End If

        If bAbsMix = True Then  '<~~ It is Absolute/Mixed
            Debug.Print sFormula & " in " & aCell.Address & " is Absolute/Mixed"
            aCell.Formula = Application.ConvertFormula(aCell.Formula, xlA1, xlA1, 4)
        Else '<~ It is Relative
            Debug.Print sFormula & " in " & aCell.Address & " is Relative"
            aCell.Formula = Application.ConvertFormula(aCell.Formula, xlA1, xlA1, 1)
        End If

        bRel = False: bAbsMix = False
    Next aCell
End Sub

在即时窗口中

enter image description here