Trying to Split Selection.Text

S

Spotty Boy

Hi,

I'm trying to swap two parts of a string separated by a tab. The text
lines also have a tab at the begining and look like this:

Text 1
Text 2

I need them to look this this:

1 Text
2 Text

I have tried different Dim statements as shown below and get the
following errors:

Error for Dim MyArray() As String
"Subscript out of range"
highlights Selection.Find.Replacement.Text = MyArray(1)

Error for Dim MyArray(1 To 5) As String
"Compile error: Can't assign to array"
highlights MyArray = Split(Selection.Text, "^9")

Error for Dim MyArray As Variant
"Subscript out of range"
highlights Selection.Find.Replacement.Text = MyArray(1)

Virtually all examples I see for Split manually assign strings to the
array cells. Then everything works fine.

I'm lost, any help is more than welcome ...


CODE
---------------------------------------------
Sub test0()
'
Dim MyArray() As String
'Dim MyArray(1 To 5) As String
'Dim MyArray As Variant
'
Selection.Find.MatchWildcards = True
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
'
With Selection.Find
.Text = "^9*^9*"
.Forward = True
.Wrap = wdFindContinue
End With
'
MyArray = Split(Selection.Text, "^9")
Selection.Find.Replacement.Text = MyArray(1)
Selection.Find.Execute Replace:=wdReplaceAll
'
End Sub
 
K

Klaus Linke

Hi,

As to your code:
-- I'd define myArray as a Variant.
-- Use Split(Selection.Text, vbTab) instead of Split(Selection.Text, "^9")
-- You can't build the replacement text out of the matched text before
you've actually matched it.

Instead of fixing the code, it would be easier to set up a wildcard
replacement:
{tab}Text{tab}1
{tab}Text{tab}2

The lines end in paragraph marks ¶?

Find what: (^t)([!^13^t]@)(^t)([0-9]@)(^13)
Replace with: \1\4\3\2\5
Check "Match wildcards", and click "Replace all".

The macro recorder should give you something to work with...

Regards,
Klaus
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top