VBA Excel 查找范围内的单词并替换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44297686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA Excel find words in a range and replace
提问by Eugene Foo
I want to replace words in a column with another word, however my code does not seem to be working, I'm still trying to get a grip on the coding language, but it's just not intuitive to me.
我想用另一个词替换列中的词,但是我的代码似乎不起作用,我仍在尝试掌握编码语言,但这对我来说并不直观。
Situation:
情况:
Global Macro - Equities
Global Macro - Bonds
Global Macro - FX
.
.
.
And so on...
Desired outcome:
期望的结果:
GM - Equities
GM - Bonds
GM - FX
.
.
.
My code
我的代码
Sub ReplaceFundNames()
Dim FundName As String
Dim CorrectedName As String
Dim ws As Worksheet
Dim LastRow As Long
Set ws = ActiveSheet
LastRow = Range("B" & Rows.Count).End(xlDown).Row
FundName = Range(LastRow)
CorrectedName = Replace(FundName, "Global Macro", "GM")
Range("B" & LastRow).Value = CorrectedName
End Sub
Thank you!
谢谢!
回答by ThunderFrame
The Replace
function in VBA is designed to work on a single string, whereas the Range.Replace
method is designed to work on a Range
.
Replace
VBA 中的函数旨在处理单个字符串,而该Range.Replace
方法旨在处理Range
.
As such, you can perform your replacements in a single statement:
因此,您可以在单个语句中执行替换:
ActiveSheet.Range("B:B").Replace "Global Macro", "GM"
ActiveSheet.Range("B:B").Replace "Global Macro", "GM"