在Excel中重新排列名称

时间:2014-02-25 20:07:31

标签: excel-vba substring vba excel

在Excel 2010中,我有一列名称格式为:“Last,First MI”(< - edit,名字后没有逗号)

我想要一个从字符串中删除MI的宏。这是我到目前为止所尝试的内容:

Sub FirstNameFirst()
Dim theName, firstspot, secondspot, finalName As String
Dim oCell As Range

For Each oCell In Selection
    firstspot = InStr(theName, " ")
    secondspot = InStr(firstspot + 1, theName, " ")

    oCell = Mid(theName, 1, secondspot - 1)
Next oCell
End Sub

我已经知道你不能在Range数据类型上进行字符串操作。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您可以使用Split将名称部分分成数组,然后将其编入索引以获得所需的结果:

Sub FirstNameFirst()
Dim cl As Range, arr As Variant
    For Each cl In Selection
        arr = VBA.Split(cl, ",")
        cl = arr(0) & "," & arr(1)
    Next cl
End Sub

答案 1 :(得分:1)

另一种方法是使用InStrRev

Sub test()
    Dim oCell As Range, i as Integer

    For Each oCell In Selection
        i = InStrRev(oCell, " ")
        If i <> 0 Then
            oCell = Left(oCell, i - 1)
        End If
    Next oCell
End Sub

enter image description here

相关问题