[英]Replace part of text in a cell case sensitive
This seems easy but I couldn't find an answer.这似乎很容易,但我找不到答案。
Each solution either replaced part of the cell, or replaced case sensitive but then the replace text had to equal the value in the cell每个解决方案要么替换单元格的一部分,要么替换区分大小写,但替换文本必须等于单元格中的值
If InStr(1, CurColumnName, ReplaceFrom, vbTextCompare) <> 0 Then
'wksC.Range(CurColumnLetter & "1").Value = Replace(CurColumnName, ReplaceFrom, ReplaceTo)
wksC.Range(CurColumnLetter & "1").Replace what:=ReplaceFrom, replacement:=ReplaceTo, MatchCase:=True
End If
Let's say my CurColumnName
is Mp3npi
, my ReplaceFrom
is npi
, my ReplaceTo
is NPI
.假设我的
CurColumnName
是Mp3npi
,我的ReplaceFrom
是npi
,我的ReplaceTo
是NPI
。
The code goes into the loop, goes through the range.replace
, but the cell isn't replaced, it remains as is.代码进入循环,通过
range.replace
,但单元格没有被替换,它保持原样。
If you check out the official documentation of the Range.Replace method it says:如果您查看Range.Replace 方法的官方文档,它会说:
The settings for
LookAt
,SearchOrder
,MatchCase
, andMatchByte
are saved each time you use this method.每次使用此方法时,都会保存
LookAt
、SearchOrder
、MatchCase
和MatchByte
的设置。 If you don't specify values for these arguments the next time you call the method, the saved values are used.如果下次调用该方法时没有为这些 arguments 指定值,则使用保存的值。
So that means if you don't specify all of them, Excel uses what ever was used before (either by VBA or by the user interface Find/Replace ).这意味着如果您不指定所有这些, Excel 将使用以前使用过的内容(通过 VBA 或用户界面Find/Replace )。 There is no default value for the parameters you can rely on.
您可以依赖的参数没有默认值。 Therefore you get random results depending on what your user selected before.
因此,您会根据用户之前选择的内容获得随机结果。 So you always have to specify at least those mentioned parameters or your code is not reliable.
所以你总是必须至少指定那些提到的参数,否则你的代码不可靠。
wksC.Columns(CurColumnLetter).Replace What:=ReplaceFrom, Replacement:=ReplaceTo, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=True, MatchByte:=True
This would replace npi
into NPI
in the entire column CurColumnLetter
at once where npi
doesn't need to be the entire cell value but a part ( xlPart
) of it.这将立即将整个列
CurColumnLetter
中的npi
替换为NPI
,其中npi
不需要是整个单元格值,而是它的一部分( xlPart
)。
Actually the same issue applies to the Find
method as well, where parameters need to be specified to make it reliable.实际上同样的问题也适用于
Find
方法,需要指定参数以使其可靠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.