PDA

View Full Version : Splitting Strings Every X Characters.



AdamAnt
11-11-2011, 04:20 PM
Hey Guys,
First off, I am a complete newbie when it comes to VBA, so any comments/explanations of how chunks of codes word would be appreciated!
Right, on to my issue. I am trying to write a chunk of code that inserts a space into a string every X character, with X defined from a variable. I have Googled about a bit and tried to use my very limited knowledge of VBA to implement this but to no success. So far the code removes any original spaces in the text, and writes the new string into a variable, to be processed by a bit of the Subroutine. This is the bit I have no idea how to code.
Any Help Anyone?
Many Thanks,
-Adam

Dave
11-12-2011, 12:09 AM
Here's some code that might get you started. Dave

Dim theinputstring As String
theinputstring = "abcdefghijklmnopqrstuvwxyz"
X = 2 'spacer
For i = 1 To Len(theinputstring)
Character = Mid(theinputstring, i, 1)
cnt = cnt + 1
If cnt Mod X = 0 Then
newstring = newstring & Character
newstring = newstring & " "
Else
newstring = newstring & Character
End If
Next i
MsgBox newstring

AdamAnt
11-12-2011, 06:58 AM
Thank You for your Help So far with this! I have got this far, which should do the job I described in my last post. However every time I run it the MsgBox at the end is blank. I have tried this with short and long sections of text, but neither work. Also, will any modifications have to be madeto get this to run with a larger amount of text? (Say, a page).
Many Thanks,
-Adam

Private Sub CommandButton1_Click()
Dim TempString
Dim SpaceRemover
Dim Line As Integer
Set SpaceRemover = Selection.Range
TempString = Replace(SpaceRemover, " ", "")
Line = 5 'spacer
For i = 1 To Len(TempString)
Character = Mid(TempString, i, 1)
cnt = cnt + 1
If cnt Mod Line = 0 Then
newstring = newstring & Character
newstring = newstring & " "
Else
newstring = newstring & Character
End If
Next i
MsgBox newstring
End Sub

Frosty
11-12-2011, 12:49 PM
Couple of pointers:

1. Use Option Explicit at the top of all modules... that's the first step.
2. Type all your variables (no "Dim TempString" ... use "Dim TempString As String").
3. Use F8 to step through your code... and hover over your variables to see what is working and what isn't. Bet you'll be able to solve from there. If you can't-- come back with the cleaned up code :)