我想编写一个宏,它会遍历所选单元格公式中的所有单元格引用,并将它们更改为绝对或相对。
是否有一个格式变量可以更改此设置或一个已经执行此操作的函数(类似于按
F4
所做的操作)但作为宏。
赏金编辑:想知道这是否仍然是最新的和/或是否有更多更新可以单独选择字段,使它们单独相对或绝对,而不需要诉诸模式匹配字符串。
您可以使用
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 个范围,如下所示
所以我可以按照
Here的建议使用
RegEx
来提取个人地址并找到它是什么样的公式,然后按照@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
在立即窗口中