让它保持简单并避免计算机交谈
这是我的数据
Source location is Column D = "USA, TX"
Destination Location is Column E.
我需要将国家(美国)从D列添加到E列。在简单的基本公式中,应该是
=Left(D,3)
但这在VBA中是什么?
答案 0 :(得分:0)
也许是这样的。代码未经测试(在移动设备上编写)。
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
答案 1 :(得分:0)
像这样使用
Dim s As String = "USA, TX"
s = Strings.Left(s, 3)