VBA for Excel中的自定义替换功能

时间:2014-06-30 08:41:15

标签: excel vba replace

我想为Excel创建一个自定义函数,在字符串中执行字符替换。

假设在excel单元格A1中我有字符串 [abc_123 | def_456]:示例 这个字符串中有一个由方括号给出的模式。 作为输出,我希望在单元格B1中有字符串 [abc | def] ,从而删除方括号内的所有数字和下划线。

如果单元格A1包含字符串 另一个例子 我想在B1中输出值 None

我编写了以下VBA行以插入新模块中。你能否检查一下它是否能完成任务?

Function Output(AdGroupName)
ClosingBracket = InStrRev(AdGroupName, "]")
Dim TMP As String
Dim Output As String
TMP = Left(AdGroupName, ClosingBracket)
TMP = Replace(TMP, "0", "")
TMP = Replace(TMP, "1", "")
TMP = Replace(TMP, "2", "")
TMP = Replace(TMP, "3", "")
TMP = Replace(TMP, "4", "")
TMP = Replace(TMP, "5", "")
TMP = Replace(TMP, "6", "")
TMP = Replace(TMP, "7", "")
TMP = Replace(TMP, "8", "")
TMP = Replace(TMP, "9", "")
Output = Replace(TMP, "_", "")
End Function

1 个答案:

答案 0 :(得分:0)

所以有了这个小小的你给我们看了你的代码,你就忘了让函数=输出。

试试这个

Public Function Tester(AGN) As String

ClosingBracket = InStrRev(AGN, "]")
TMP = Left(AGN, ClosingBracket)
TMP = Replace(TMP, "0", "")
TMP = Replace(TMP, "1", "")
TMP = Replace(TMP, "2", "")
TMP = Replace(TMP, "3", "")
TMP = Replace(TMP, "4", "")
TMP = Replace(TMP, "5", "")
TMP = Replace(TMP, "6", "")
TMP = Replace(TMP, "7", "")
TMP = Replace(TMP, "8", "")
TMP = Replace(TMP, "9", "")
Output = Replace(TMP, "_", "")

Tester = Output
End Function

我用你给我们的例子测试了这个,输出是[abc | def]