0

Lets keep it simple and avoid computer talk

Here's my data

Source location is Column D = "USA, TX"
Destination Location is Column E.

I need to get the country "USA" into Column E from Column D. In simple basic formula it would be

=Left(D,3)

But what is this in VBA?

Scott Craner
  • 148,073
  • 10
  • 49
  • 81
Jundu
  • 19
  • 4

2 Answers2

0

Maybe something like this. Code is untested (written on mobile).

Option Explicit

Sub extractCountries()
    Dim arrayOfValues() as variant
    Dim lastRow as long
    Dim rowIndex as long
    'Change these four lines as needed ' 
    Const SOURCE_COLUMN as string = "D"
    Const DESTINATION_COLUMN as string = "E"
    Const ROW_TO_START_FROM as long = 1
    With thisworkbook.worksheets("Sheet1")
        lastRow = .cells(.rows.count, SOURCE_COLUMN).end(xlup).row
        arrayOfValues = .range(SOURCE_COLUMN & ROW_TO_START_FROM ":" & SOURCE_COLUMN & lastRow).value2
        For rowIndex = lbound(arrayOfValues,1) to ubound(arrayOfValues,1)
            arrayOfValues(rowIndex,1) = vba.strings.left$(arrayOfValues(rowIndex,1),3)
            'If the logic should be "everything before the comma", use instr() function above.'
        Next rowIndex
        .range(DESTINATION_COLUMN & ROW_TO_START_FROM ":" & DESTINATION_COLUMN & lastRow).value2 = arrayOfValues
    End with
End sub
AJD
  • 2,400
  • 2
  • 12
  • 22
chillin
  • 4,391
  • 1
  • 8
  • 8
0

Use like this

Dim s As String = "USA, TX"
s = Strings.Left(s, 3)
ARN
  • 173
  • 2
  • 9