Excel VBA:将字符串中的数字和文本拆分为列

时间:2018-01-30 04:02:09

标签: excel vba excel-vba

我的excel中有一个列,格式如下:

Column A
1.2kg
100ml
2m
200

我需要运行VBA将数字和文本分成两列:

Column A | Column B
1.2      |  kg
100      |  ml
2        |  m
200      |

我也在这个网站上发现了一个类似的问题,但它对我的VBA不起作用。谁可以帮我这个事?

PS。我使用excel 2007

1 个答案:

答案 0 :(得分:0)

在手机上未经测试。它能做你想做的吗?

Option Explicit

Sub SplitValuesUnits()

' Code assumes values are on Sheet1. Change sheet name as needed.'

With thisworkbook.worksheets("Sheet1")

Dim LastRow as long
LastRow = .cells(.rows.count,"A").end(xlup).row

With .range("A1:B" & LastRow)

Dim ArrayOfValues() as variant
ArrayOfValues = .value2

Dim CharacterIndex as long
Dim RowIndex as long
For RowIndex = lbound(ArrayOfValues,1) to ubound(ArrayOfValues,1)
' Skip zero-length strings, as well as values which are already numbers and do not need splitting '
If len(ArrayOfValues(RowIndex,1)) <> 0 then
If not isnumeric(ArrayOfValues(RowIndex,1)) then

Dim CurrentValue as string
CurrentValue = ArrayOfValues(RowIndex,1)

' Loop through string backwards until we find a numeric value, at which point we assume there are no further non-numeric characters. '
For CharacterIndex = Len(CurrentValue) to 1 Step -1
If isnumeric(mid$(CurrentValue),CharacterIndex,1)) then exit for
Next CharacterIndex

If CharacterIndex >= 1 then
ArrayOfValues(RowIndex,1) = cdbl(left$(CurrentValue,CharacterIndex))
ArrayOfValues(RowIndex,2) = mid$(CurrentValue,CharacterIndex + 1)
End if

End if
End if

Next RowIndex

' Overwrite two columns with values. '
.value2 = arrayofvalues

End with

End with

End sub