Home > front end >  Selection of non-white characters with VBA
Selection of non-white characters with VBA

Time:11-17

In MS-Word I have text like this: hif.imp. ינעימשת od שמע When I double click on the on the hebrew word the range is selected with the space after the word. I wanted to create macro, that will reduce the white space characters.

Dim r1 As Range
Dim str1 As String
Set r1 = Selection.Range
r1.SetRange Start:=0, End:=Len(Trim(r1.Text))

However when I run this, nothing happens, the selection still includes the space. How to fix this?

CodePudding user response:

Trim should works as expected. Issue somewhere else.

Minimal working code

Dim sht As Worksheet

Set sht = Sheets("Sheet1")

Dim value1, value2 As String

value1 = sht.Cells(1, 1)

value2 = RTrim(LTrim(value1))
value3 = Trim(Trim(value1))

MsgBox ("'"   value1   "'"   vbCrLf   "'"   value2   "'"   vbCrLf   "'"   value3   "'")

Result from value2 is equal to result from value3

enter image description here

CodePudding user response:

Code for the Word:

Double click on the word, then run the macro. This should select text only.

Sub Makro2()
Dim r1 As Range
Dim str1 As String
Dim a As Integer
Dim b As Integer
Set r1 = Selection.Range
str1 = Trim(r1.Text)
a = r1.Start
b = Len(Trim(r1.Text))
r1.SetRange Start:=a, End:=a   b
r1.Select
End Sub
  • Related