如何使用 VBA 修改字符串的一部分
How to modify part of a string with VBA
例如(Then 语句不正确,我正在尝试弄清楚要放在那里的内容):
For i = 1 to 20
If Instr(1, Cells(i, "A"), "@goggle.com") > 0 Then
"@goggle.com" = "@google.com"
Next i
假设电子邮件 "somebody@goggle.com" 在单元格 A2 中,因此 Instr 在 A2 中找到“@goggle.com”。如果我想将 @goggle.com 更改为 @google.com,我该怎么做?
我的目标是找到电子邮件域的常见拼写错误并修复它们。
查看 Replace
声明。
在这种情况下:
Replace(Cells(i, "A"), "@google.com", "@gmail.com")
基本上公式是说,在这个字符串`Cells(i,"A") 中找到“@google.com”并将其替换为“@gmail.com”
有了这个,您将不需要 if 语句,因为替换函数不会替换它找不到的任何内容。换句话说,如果在它继续移动的字符串中找不到“@google.com”,那么 returns 什么都没有。
如前所述,要修复您的代码,您可以使用替换功能
For i = 1 To 20
If InStr(1, Cells(i, "A"), "@goggle.com") > 0 Then
Cells(i, "A") = Replace(Cells(i, "A"), "@goggle.com", "@google.com")
End If
Next
但要更有效地进行所有替换,请使用 Range().Replace 方法获取值和替换列表:
Option Explicit
Public Sub fixColumnSpelling()
Const FIND_LIST As String = "@goggle.com @yahho.com @test1.com"
Const REPL_LIST As String = "@google.com @yahoo.com @test2.com"
Dim totalItems As Long, i As Long, findItems As Variant, replItems As Variant
findItems = Split(FIND_LIST)
replItems = Split(REPL_LIST)
totalItems = UBound(findItems)
For i = 0 To totalItems 'bulk replecements in col A
ActiveSheet.UsedRange.Columns(1).Replace _
What:=findItems(i), _
Replacement:=replItems(i), _
LookAt:=xlPart, _
SearchOrder:=xlByColumns, _
MatchCase:=False
Next
End Sub
例如(Then 语句不正确,我正在尝试弄清楚要放在那里的内容):
For i = 1 to 20
If Instr(1, Cells(i, "A"), "@goggle.com") > 0 Then
"@goggle.com" = "@google.com"
Next i
假设电子邮件 "somebody@goggle.com" 在单元格 A2 中,因此 Instr 在 A2 中找到“@goggle.com”。如果我想将 @goggle.com 更改为 @google.com,我该怎么做?
我的目标是找到电子邮件域的常见拼写错误并修复它们。
查看 Replace
声明。
在这种情况下:
Replace(Cells(i, "A"), "@google.com", "@gmail.com")
基本上公式是说,在这个字符串`Cells(i,"A") 中找到“@google.com”并将其替换为“@gmail.com”
有了这个,您将不需要 if 语句,因为替换函数不会替换它找不到的任何内容。换句话说,如果在它继续移动的字符串中找不到“@google.com”,那么 returns 什么都没有。
如前所述,要修复您的代码,您可以使用替换功能
For i = 1 To 20
If InStr(1, Cells(i, "A"), "@goggle.com") > 0 Then
Cells(i, "A") = Replace(Cells(i, "A"), "@goggle.com", "@google.com")
End If
Next
但要更有效地进行所有替换,请使用 Range().Replace 方法获取值和替换列表:
Option Explicit
Public Sub fixColumnSpelling()
Const FIND_LIST As String = "@goggle.com @yahho.com @test1.com"
Const REPL_LIST As String = "@google.com @yahoo.com @test2.com"
Dim totalItems As Long, i As Long, findItems As Variant, replItems As Variant
findItems = Split(FIND_LIST)
replItems = Split(REPL_LIST)
totalItems = UBound(findItems)
For i = 0 To totalItems 'bulk replecements in col A
ActiveSheet.UsedRange.Columns(1).Replace _
What:=findItems(i), _
Replacement:=replItems(i), _
LookAt:=xlPart, _
SearchOrder:=xlByColumns, _
MatchCase:=False
Next
End Sub