Excel 2007中的VBAmacros。我想在Excel VBA中使用正则expression式来将“他”replace为“她”,“他”replace为“她”,“他”replace为“她”

Sub Test() Dim strTest As String Dim strTemp As String strTest = Sheet1.Cells(1, 1).Value MsgBox RE6(strTest) Sheet1.Cells(2, 1).Value = RE6(strTest) End Sub Function RE6(strData As String) Dim RE As Object 'REMatches As Object Dim P As String, A As String Dim Q As String, B As String Dim R As String, C As String Dim S As String, D As String Dim T As String, E As String Dim U As String, F As String Dim V As String, G As String Dim W As String, H As String Dim N As Integer Set RE = CreateObject("vbscript.regexp") P = "(?:^|\b)He" A = "She" Q = "(?:^|\b)he" B = "she" R = "(?:^|\b)Him" C = "Her" S = "(?:^|\b)him" D = "her" T = "(?:^|\b)Himself" E = "Herself" U = "(?:^|\b)himself" F = "herself" V = "(?:^|\b)His" G = "Her" W = "(?:^|\b)his" H = "her" 'This section replaces "He" with"She" With RE .MultiLine = True .Global = True .IgnoreCase = False .Pattern = P End With RE6 = RE.Replace(strData, A) 'This section replaces "he" with "she" With RE .MultiLine = True .Global = True .IgnoreCase = False .Pattern = Q End With RE6 = RE.Replace(strData, B) ' 'This section replaces "Him" with "Her" With RE .MultiLine = True .Global = True .IgnoreCase = False .Pattern = R End With RE6 = RE.Replace(strData, C) 'This section replaces "him" with "her" With RE .MultiLine = True .Global = True .IgnoreCase = False .Pattern = S End With RE6 = RE.Replace(strData, D) 'This section replaces "Himself" with "Herself" With RE .MultiLine = True .Global = True .IgnoreCase = False .Pattern = T End With RE6 = RE.Replace(strData, E) 'This section replaces "himself" with "herself" With RE .MultiLine = True .Global = True .IgnoreCase = False .Pattern = U End With RE6 = RE.Replace(strData, F) 'This section replaces "His" with "Her" With RE .MultiLine = True .Global = True .IgnoreCase = False .Pattern = V End With RE6 = RE.Replace(strData, G) 'This section replaces "his" with "her" With RE .MultiLine = True .Global = True .IgnoreCase = False .Pattern = W ' RE6 = RE.Replace(strData, H) End With End Function 

当我在这段文字上运行这段代码时:

James has settled effortlessly in his new class. He has shown seriousness and demonstrated traits of a serious student in the first half of the term. I am very optimistic that his positive attitude towards work, if he does not relent, will yield positive dividends. However, James needs to respond positively to prompts on getting himself better organised in school. I wish Him, him the best in the second half of the term.

我只把“他”换成“她”。 如果我最后一点发表意见,那么我只会把“他”换成“她”。 任何帮助将是非常受欢迎的。

问题是你反复做strData的replace,而不是每个replace的结果; 也就是说,你把你原来的string,用“她”replace“他”,然后将其存储在RE6中。 然后再次取出原来的string,用“她”replace“he”,然后将其存储在RE6中,覆盖第一个replace,等等。这就是为什么你只能看到最后replace的结果。

要解决这个问题,请先把你的第一个replace件留下

 RE6 = RE.Replace(strData, A) 

但改变你的所有其他替代品

 RE6 = RE.Replace(RE6, B) <-- do this for BH 

这会给你你想要的输出。