Search code examples
vbaexcellarge-data

Code either overloads memory or wont compile VBA


Trying to write a macro to insert a hyphen at specific points in a text string depending on how long the string is or delete all text after said point.

i.e - if 6 characters, insert a hyphen between char 4+5 or delete all text after char 4 - if 7 characters, insert a hyphen between char 5+6 or delete all text after char 5

Ideally i would love to be able to truncate the string at that point rather than hyphenate the text but i couldn't get my head around how to make it work so i decided to hyphen and then just run a find and replace '-*' to remove the unwanted characters. Can get this working on small sample sets 100-300 cells but i need the code to be able to go through workbooks with 70,000+ cells. I've tried tweaking the code to stop the memory issue but now i can't seem to get it to work.

Sub Postcodesplitter()
Dim b As Range, w As Long, c As Range, x As Long, d As Range, y As Long

For Each b In Selection
w = Len(b)
If w = 8 And InStr(b, "-") = 0 Then b = Application.WorksheetFunction.Replace(b, 15 - w, 0, "-")

For Each c In Selection
x = Len(c)
If x = 7 And InStr(c, "-") = 0 Then c = Application.WorksheetFunction.Replace(c, 13 - x, 0, "-")

For Each d In Selection
y = Len(d)
If y = 6 And InStr(d, "-") = 0 Then d = Application.WorksheetFunction.Replace(d, 11 - y, 0, "-")

Next
Next
Next
End Sub    

That's the original code i put together, but it caused memory issues over 300 target cells. I'm a pretty bad coder even at the best of times but with some advice from a friend i tried this instead.

Sub Postcodesplitter()
Dim b As Range, x As Long

If (Len(x) = 6) Then
b = Application.WorksheetFunction.Replace(b, 11 - x, 0, "-")
Else
If (Len(x) = 7) Then
b = Application.WorksheetFunction.Replace(b, 13 - x, 0, "-")
Else
If (Len(x) = 8) Then b = Application.WorksheetFunction.Replace(b, 15 - x, 0, "-")

End Sub

But this just throws out errors when compiling. I feel like im missing something really simple.

Any tips?


Solution

  • It looks as though you want to truncate to two less than the existing number of characters, if that number is 6-8? If so, something like this:

    Sub Postcodesplitter()
    Dim data
    Dim x as Long
    Dim y as Long
    
    data = Selection.Value
    For x = 1 to ubound(data,1)
    for y = 1 to ubound(data, 2)
    Select Case Len(data(x, y))
    Case 6 to 8
    data(x, y) = left(data(x, y), len(data(x, y)) - 2)
    end select
    next y
    next x
    selection.value = data
    
    End Sub