EXCEL vba - 从单元格中提取数字并粘贴到两个不同的列中?

时间:2016-12-20 15:57:39

标签: excel vba

我有一个电子表格,在A栏中加载了随机文字和数字,如下所示:

Column A

    Row 1 = 471806121601 5205569 - 0007 Standard White Toilet Tissue 27 
    Row 2 = 471814121601 5206177 - 0014 Premium White Toilet Tissue 6 
    Row 3 = 471814121601 5206178 - 0007 Premium White Toilet Tissue 27
    Row 4 = 471806121601 5206180 - 0014 Premium Kitchen Towel 2x75l 6 

我总共约有2000行。在每个单元格中,是一个采购订单编号(12位数)和旁边的项目编号(7位数)。

我正在尝试提取po编号并将其放入B列并提取项目编号并将其放入C列

Column B        Column C
471806121601    5205569 
471814121601    5206177 
471814121601    5206178 
471806121601    5206180 

这是我的代码:

Option Explicit

Sub main()
Dim cell As Range
Dim arr As Variant, arrElem As Variant

With Worksheets("Orders") '<--| change "Strings" to your actual worksheet name
    For Each cell In .Range("A1", .Cells(.Rows.Count, "A").End(xlUp))
        arr = Split(Replace(cell.Value, "  ", " "), " ") '<--| change "A"'s to your actual relevant column index
        For Each arrElem In arr
          If IsNumeric(arrElem) Then
            If Len(arrElem) = 12 Then cell.Offset(0, 1).Value = arrElem
          End If
        Next arrElem
    Next cell
End With

Dim cell2 As Range
Dim arr2 As Variant, arrElem2 As Variant

With Worksheets("Orders") '<--| change "Strings" to your actual worksheet name
    For Each cell2 In .Range("A1", .Cells(.Rows.Count, "A").End(xlUp))
        arr2 = Split(Replace(cell2.Value, "  ", " "), " ") '<--| change "A"'s to your actual relevant column index
        For Each arrElem2 In arr2
          If IsNumeric(arrElem2) Then
            If Len(arrElem2) = 7 Then cell2.Offset(0, 3).Value = arrElem2
          End If
        Next arrElem2
    Next cell2
End With

End Sub

此代码确实有效。然而,它需要绝对年龄,并且一次只能做一行......慢慢地。

有更快的方法吗?感谢

2 个答案:

答案 0 :(得分:0)

如果您的PO和IN在col B put中的长度始终相同

=MID(A2, 1, 12)

在col C

=MID(A2, 14, 7)

但是,如果你的号码改变但总是前两个交换上面的,

=MID(A2,1,FIND(" ",A2,1)-1)

=MID(A2, FIND(" ", A2, 1)+1, 7)

分别

答案 1 :(得分:0)

只需使用split(string,delimiter)(0)(1)为什么要替换空格,只需使用它作为delim。如果Row#在,则使用(1)和(2),或者您可以考虑split(split(input,"-")," ")可能更快一点,但不确定。此外,一旦你完成了没有必要完成循环,所以考虑,直到有标志而不是下一个,尽管exit for可用

公式明智,可以使用类似的东西来完成

=MID(D1,FIND("é",SUBSTITUTE(D1," ","é",3)),FIND("é",SUBSTITUTE(D1," ","é",4))-FIND("é",SUBSTITUTE(D1," ","é",3)))

=MID(D1,FIND("é",SUBSTITUTE(D1," ","é",4)),FIND("é",SUBSTITUTE(D1," ","é",5))-FIND("é",SUBSTITUTE(D1," ","é",4)))