用VBA中的其他单元格引用替换依赖项

Man*_*eng 6 vba replace cut-and-paste

我编写了一些VBA代码,它接受单个单元格并在工作簿中识别其所有依赖项(通过NavigateArrow分析)并将其范围位置添加到数组中.从这里开始,我希望能够更新每个依赖项,并将对原始单个单元格的引用更改为另一个指定单元格.

我在这里遇到的特殊困难是,虽然我知道每个依赖的位置,但对原始单元格的引用可能位于公式的开头,中间或末尾,并且可能是未锚定的,行/列/两者都锚定,可能在一个不同的工作表,因此在它之前有一个工作表参考,等等.因此,我不能在每个依赖单元格中轻松找到和替换,因为这些潜在的差异,加上我想保持原始锚定在每个细胞参考.

是否有一个优雅 - 甚至不优雅 - VBA解决这个问题的方法?

Jul*_*rec 1

我认为正则表达式或 Regexp 就是您正在寻找的。

以下模式

([A-Z0-9]*)!(\${0,1})([A-Z]{1,3})(\${0,1})([0-9]*)
Run Code Online (Sandbox Code Playgroud)

将匹配诸如“Sheet1!A1”、“Sheet1!$A$1”、“Sheet1!$A1”、“Sheet1!A$1”之类的内容

解释:

([A-Z0-9]*)!  =  Find anything that is before "!"
(\${0,1}) = $ or nothing
([A-Z]{1,3})  = between one and three letters
([0-9]*)  = Any number
Run Code Online (Sandbox Code Playgroud)

您应该能够轻松修改该模式以仅匹配您想要的内容。特别是, ([A-Z0-9]*)!(\${0,1})B(\${0,1})1 只会匹配其中包含 B($)1 的内容...使用字符串操作构建正则表达式模式,应该很好。

您需要引用(工具>参考)“Microsoft VBScript Regular Expressions 5.5”

尝试以下代码,这应该为您提供实现目标的所有工具

Sub ReplaceReference()
' Reference: Microsoft VBScript Regular Expressions 5.5

Dim RegEx As Object
Set RegEx = New RegExp

Dim s As String

' Here I have hardcoded the reference to the original cell for demonstration purposes
s = "Sheet1!$AB$2"


' Replacement: New sheetname, New Column, new row number
Dim NewCol As String, NewRow As String
NewCol = "C"
NewRow = "10"

Dim NewSheet As String
NewSheet = "Sheet2"


With RegEx
    .Pattern = "([A-Z0-9]*)!(\${0,1})([A-Z]{1,3})(\${0,1})([1-9]*)"
    .IgnoreCase = True
    .Global = True
End With


Debug.Print RegEx.Replace(s, NewSheet & "!" & "$2" & NewCol & "$4" & NewRow)


End Sub
Run Code Online (Sandbox Code Playgroud)

干杯,朱利安