View Single Post
 
Old 09-08-2014, 06:43 PM
excelledsoftware excelledsoftware is offline Windows 7 64bit Office 2003
IT Specialist
 
Join Date: Jan 2012
Location: Utah
Posts: 455
excelledsoftware will become famous soon enough
Default

Sorry I re-read your post. Make sure that when you run this code that the worksheet is the first in the workbook. If this is an issue let me know the exact worksheet name and I will update the code to look for this. Also to be sure it is or is not doing anything I will add one more thing to the code that after you validate it is working you can remove.

Code:
Option Explicit

Sub FormatNumberString()
  'Looks through a list of numbers on the first worksheet and formats them
  'with leading zeroes.
  
  Dim CheckRow As Long, LastRow As Long, CheckString() As String
  Dim x As Integer, arr As Long, ArrayString As Variant
  Dim NewString As String, TempString As String
  Dim wb As Workbook, ws As Worksheet
  
    Set wb = ThisWorkbook
    Set ws = wb.Worksheets(1)
    LastRow = ws.Range("T50000").End(xlUp).Row
    ReDim CheckString(0 To LastRow - 1)
    
    ws.Activate
    'Grab the values
    arr = 0
    For CheckRow = 2 To LastRow
      ws.Range("T" & CheckRow).Select 'REMOVE THIS LINE ONCE CODE WORKS
      CheckString(arr) = ws.Range("T" & CheckRow).Value
      arr = arr + 1
    Next CheckRow
    
    'Insert values back in with new format
    arr = 0
    For CheckRow = 2 To LastRow
      ws.Range("T" & CheckRow).Select 'REMOVE THIS LINE ONCE CODE WORKS
      If CheckString(arr) <> "" Then
        'Convert each number to have leading zeroes
        ArrayString = Split(CheckString(arr), ",")
        For x = 0 To UBound(ArrayString)
          Select Case Len(ArrayString(x))
            Case 1:
              TempString = "00" & ArrayString(x)
            Case 2:
              TempString = "0" & ArrayString(x)
            End Select
            NewString = CStr(NewString & TempString & ",")
          Next x
          'Remove last comma
          NewString = Mid(NewString, 1, Len(NewString) - 1)
        ws.Range("T" & CheckRow).NumberFormat = "@"
        ws.Range("T" & CheckRow).Value = NewString
        NewString = ""
      End If
      arr = arr + 1
    Next CheckRow

End Sub
Now you can press F8 to see the code in action. After you see it works remove the 2 lines that say REMOVE
Reply With Quote