VBA Excel用于在_下划线后提取##

时间:2017-10-26 14:21:24

标签: excel vba split underscore.js extract

我有一个9位数字的数据集,后跟一个下划线,然后是两位数的年份。

例如:

123456789_17
123456789_16
...

目前我有一个代码可以删除下划线之前的数字后面的任何内容"

Sub Trunc3()
  Range("AF1:AF10000") = Evaluate(Replace("IF(ROW(),LEFT(@,FIND("" "",SUBSTITUTE(SUBSTITUTE(" & _
                               "@,""_"","" ""),""_"","" "")&"" "")-1))", "@", "E1:E100000"))
End Sub

相反,我想将输出分为两列:
第一列应为9位数字:123456789 第二列应为两位数年份:17

提前致谢。

1 个答案:

答案 0 :(得分:2)

使用TextToColumns

Sub SplitText()
    Range("AF:AF").TextToColumns Destination:=Range("AF1"), _
                                 DataType:=xlDelimited, _
                                 Other:=True, _
                                 OtherChar:="_", _
                                 FieldInfo:=Array(Array(1, 1), Array(2, 1))
End Sub

使用Split()方法:

Sub SplitText1()

    Dim r As Range
    Set r = Range("AF:AF")

    Dim c As Range, v As Variant
    For Each c In r
        v = Split(c.Value, "_")
        c.Value = v(0)
        c.Offset(0, 1).Value = v(1)
    Next c
End Sub

修改

您可以循环每个单元格并相应地设置其值。

Dim r As Range
For Each r In Range("AG:AG")
    If IsEmpty(r.Offset(0, -1).Value) Then Exit For
    Select Case r.Value
        Case 16:   r.Value = 2016
        Case 17:   r.Value = 2017
        Case Else: r.Value = 2015
    End Select
Next r