根据条件在单元格中翻转名称

时间:2018-03-16 18:04:14

标签: excel vba excel-vba

我在列R个人姓名中有一个姓名列表&组织名称。个人姓名采用格式(名字姓氏)。在列Q中,提到了类型名称(个人或组织)。仅对于个人姓名,我想在列U中以格式(姓氏名字)翻转个人姓名。我为此做了一个代码。但在某个地方我错过了一个逻辑。有人可以帮忙吗?谢谢

    Sub Nameflip()
'
' Nameflip Macro
'

'
    Dim sht As Worksheet
    Dim LR As Long
    Dim i As Long
    Dim myformula As String

    Set sht = ActiveWorkbook.Worksheets("ORD_CS")

    With sht
        LR = .Cells(.Rows.Count, "N").End(xlUp).Row
        myformula = "=Right(R2, Len(R2) - Find("" "", R2)) & "" "" & Left(R2, Find("" "", R2) - 1)"

        For i = 2 To LR
            If .Range("Q" & i).Value = "P" Then
               .Range("U" & i) = Application.Evaluate(myformula)
            End If
        Next i
    End With
End Sub

1 个答案:

答案 0 :(得分:0)

我会使用split函数,因为它比你的公式更容易阅读:

Sub Nameflip()
    Dim sht As Worksheet
    Dim LR As Long
    Dim i As Long
    Dim vSplit As Variant

    Set sht = ActiveWorkbook.Worksheets("ORD_CS")
    With sht
        LR = .Cells(.Rows.Count, "N").End(xlUp).Row
        For i = 2 To LR
            If CStr(.Range("Q" & i).Value) = "P" Then
               .Range("U" & i) = Split(CStr(.Range("R" & i)))(1) & ", " & Split(CStr(.Range("R" & i)))(0)
            End If
        Next i
    End With
End Sub

我假设全名来源在R栏中,所以你可能需要调整一下列字母。