mmichaelx
mmichaelx

Reputation: 95

Excel VBA - Substring & Paste

I have a column that has U.S. state abbreviations (MI, NY, FL, etc.). I have an issue where there is an observation that is listed as "NJ NJ". This observation moves around within the same column each week.

I want to create a macro that substrings each observation to two characters and just drops everything afterwords.

Would I be able to use the Mid function to grab the first two characters, and then paste it overtop of the original value. Further, would it be appropriate to offset by one or is there a way to do it all at once?

Thanks!

Upvotes: 0

Views: 757

Answers (2)

If you want your result to be offset by one cell from the source cell, then the formula by Daniel Cook works fine.

On the other hand, if you want your result to overwrite the source cell, you would have to copy the cell with the result (using the same formula as above) and paste-special as value on top of the source cell (you can do this for many cells at once), or write a VBA sub.

I personally find it simpler the "copy and paste-special as value" way.

Upvotes: 1

Shiva
Shiva

Reputation: 20935

Assuming you have your List in the 1st Column, starting at Row 1, the following Macro will do it. Obviously you can make a lot of improvements and error checks to the code, but this should get you started.

Sub FixStates()

Dim lRow As Long
Dim lCol As Long
Dim strContent As String

    lRow = 1
    lCol = 1

    Do While Cells(lRow, lCol) <> ""
        strContent = Trim(Cells(lRow, lCol))
        If Len(strContent) > 2 Then Cells(lRow, lCol) = Left(strContent, 2)
        lRow = lRow + 1
    Loop

End Sub

Upvotes: 1

Related Questions