如何让Range.Replace的What和Replacement参数引用指定单元格内容?
How to Reference Cell Values in Range.Replace Parameters (VBA)
Hey there! Let's sort out this VBA Replace question you have. The core fix here is directly pulling the content from cells G7 and H7 to feed into the Replace method's What and Replacement parameters. Here's exactly how to do it:
Working Code Example
Instead of hardcoding or using placeholder text, reference the cell's value directly:
' Replace within the currently selected range Selection.Replace _ What:=Range("G7").Value, _ Replacement:=Range("H7").Value, _ LookAt:=xlPart, _ SearchOrder:=xlByRows, _ MatchCase:=False, _ SearchFormat:=False, _ ReplaceFormat:=False
Key Details to Note
Range("G7").Valueextracts the exact content (text, number, etc.) from cell G7 and passes it to theWhatparameter — this is what Excel will search for in your target range.- You can actually skip the
.Valuepart if you want (since it's the default property of a Range object), soRange("G7")works too. But adding.Valuemakes your code clearer for anyone reading it (including future you!). - If you want to target a specific range instead of the selected cells, just swap
Selectionwith your desired range. For example:' Replace in range A1:D100 instead of selected cells Range("A1:D100").Replace _ What:=Range("G7").Value, _ Replacement:=Range("H7").Value, _ LookAt:=xlPart, _ SearchOrder:=xlByRows, _ MatchCase:=False, _ SearchFormat:=False, _ ReplaceFormat:=False
Quick Heads-Up
If cell G7 is empty when you run this code, it will replace all empty cells in your target range with H7's content. Double-check that G7 has the specific value you want to search for before executing!
内容的提问来源于stack exchange,提问作者Juliano Silva
相关产品推荐
相关产品推荐

