使用VBA

时间:2018-10-18 16:51:17

标签: excel vba excel-vba

我有如下所示的Excel公式

示例1

=SUMIF('TRx Wkly NT'!$A:$A,"AdderAKl* XR*",'TRx Wkly NT'!BS:BS)/10^3

示例2

=SUMIF('TRx Wkly NT'!$A:$A,"amphe* ER* prasco*",'TRx Wkly NT'!BS:BS)/10^3+SUMIF('TRx Wkly NT'!$A:$A,"amphe* ER* teva*",'TRx Wkly NT'!BS:BS)/10^3

示例3

=SUM('Baseline Trx Wkly NT'!BS:BS)/1000-SUM(PX29,PX73,PX108)/1000

在这些公式中,“ BS:BS”是指整个列。我需要一个将VBA的“ BS:BS”替换为“ ColumnLetterVariable:ColumnLetterVariable”的子

我该如何实现?我什至不知道从哪里开始。我使用正则表达式吗?

问题1 :我不知道我要替换什么。 “ BS:BS”不是恒定的;它一直在变化。可能是一天的AA:AA,或者是第二天的单个字母,例如Z:Z。 VBA需要一种方法来识别字符串的Column:Column

问题2 :“ BS:BS”可能出现在公式中的多个位置,例如在示例2中。所有这些都需要用我的VBA变量替换。

编辑:无需替换示例公式中的$A:$A部分。只是BS:BS部分一直在变化。

1 个答案:

答案 0 :(得分:1)

尝试以下代码-我认为您可以使用正则表达式解决您的问题(所有注释和模式说明均在代码中):

Sub RegexTest()
    Dim regex As Object, result As String, pattern As String, replacement As String
    Set regex = CreateObject("VBScript.RegExp")
    ' Define inputs: pattern and replacement value
    pattern = "!([A-Z]+):(\1)"
    ' Pattern explanation: match exclamation mark (!) literally, then match one or more capital letters: [A-Z]+,
    ' those captured letters will  be in capturing group defined with brackets (),
    ' then match semicolon (:), then match exact same text that was captured in first group
    replacement = "Column:Column"
    ' Test function
    result = RegExReplace("TRx Wkly NT'!$A:$A,""AdderAKl* XR*"",'TRx Wkly NT'!BS:BS)/10^3", pattern, replacement)
    MsgBox result
    result = RegExReplace("TRx Wkly NT'!$A:$A,""amphe* ER* prasco*"",'TRx Wkly NT'!BS:BS)/10^3+SUMIF('TRx Wkly NT'!$A:$A,""amphe* ER* teva*"",'TRx Wkly NT'!BS:BS)/10^3", pattern, replacement)
    MsgBox result
    result = RegExReplace("Baseline Trx Wkly NT'!BS:BS)/1000-SUM(PX29,PX73,PX108)/1000", pattern, replacement)
    MsgBox result
End Sub
Function RegExReplace(inputString As String, pattern As String, replacement As String) As String
    ' We need to create RegExp object to use regular expressions
    Dim regex As Object
    Set regex = CreateObject("VBScript.RegExp")
    regex.pattern = pattern
    RegExReplace = inputString
    ' Since Replace method replaces one value at a time, you need to replace it until no more matches are found
    Do
        RegExReplace = regex.Replace(RegExReplace, "Column:Column)")
    Loop While regex.Test(RegExReplace)
End Function