PDA

View Full Version : [SOLVED:] Word VBA Replace spaces between Chinese texts in an Anglo-Chinese document



j.cy
03-25-2015, 01:26 AM
Hi all, I've been searching and trying for 2 weeks and haven't had a clue, hope the experts here can help

what i'm doing is, firstly, to discern english and chinese texts by replacing english texts and the space after them to red in colour,
recorded macro as follow:

Sub ReplaceNonChineseToColorRed()
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Font.Color = wdColorRed
With Selection.Find
.Text = "[0-9a-zA-Z]{1,50} {1,50}"
.Replacement.Text = "^&"
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchByte = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
End With
Application.DisplayAlerts = False
Selection.Find.Execute Replace:=wdReplaceAll
Application.DisplayAlerts = True
End Sub


then, find and select whole story apart from the ones with other font colours
recorded macro cannot be used per my limited understanding, anyway, the code is now, somehow, like this:

Sub FindAndSelectOccurancesWithColorAuto()
Application.ScreenUpdating = False
Selection.HomeKey Unit:=wdStory
Selection.Find.ClearFormatting
Selection.Find.Font.Color = wdColorAutomatic
With Selection.Find
.Text = "^?"
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchByte = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
End With
Application.ScreenUpdating = True
End Sub


finally replace spaces occurred in the selection, they are supposed to be chinese spaces only

Sub ReplaceSpaces()
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = " "
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchByte = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Application.DisplayAlerts = False
Selection.Find.Execute Replace:=wdReplaceAll
Application.DisplayAlerts = True
End Sub


obviously i'm too green to discover what goes wrong, my vba experience is just 2 weeks...

please help and thanks in advance

cheers
Jo

gmayor
03-25-2015, 03:51 AM
I don't have any documents with mixed Chinese and English to test, but assuming your first macro works as you intended, then you can replace spaces with no spaces in text that is not red as follows. Using ranges there is no need to select the text in order to process it.



Sub ReplaceNonRedSpaces()
Dim orng As Range
Set orng = ActiveDocument.Range
With orng.Find
Do While .Execute(FindText:=" ")
If Not orng.Font.ColorIndex = wdRed Then
orng.Text = ""
orng.Collapse 0
End If
Loop
End With
lbl_Exit:
Exit Sub
End Sub

j.cy
03-25-2015, 04:26 AM
thanks Graham very much indeed
it works perfectly