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

我想写一个macros,通过select单元格公式中的所有单元格引用,并将其更改为绝对相对

有没有一个格式化variables,可以改变这个或已经这样做的function(类似于什么按F4 ),但作为一个macros。

您可以使用ConvertFormula方法。

第四个参数决定它是否是绝对的。 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) 

我看到你已经编辑了这个问题,但由于我已经在这方面做了工作,所以我发布了一个答案。

如果您不知道公式包含的内容,并且希望将“ Relative对于Absolute和“ Absolute/Mixed更改为“ Relative尝试此操作

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

![在这里输入图片描述

所以我可以使用正则RegEx 这里提取个别地址,并找出它是什么样的公式,然后按@cyboashu

 Const sPattern As String = _ "(['].*?['!])?([[A-Z0-9_]+[!])?(\$?[AZ]+\$?(\d)+(:\$?[AZ]+\$?(\d)+)?|\$?[AZ]+:\$?[AZ]+|(\$?[AZ]+\$?(\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 = "(([AZ])+(\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 

在即时窗口中

在这里输入图像描述