Excel可以更改选择的内容

时间:2015-06-21 08:07:37

标签: excel vba excel-vba

我希望有人可以帮助我使用宏来进行Excel中的一些文本操作。

问题:

如何使用宏更改所选单元格(甚至整列/行)的内​​容?这个宏应该怎么样?

我希望在此过程中遵循一些规则:

  • 让我们假设我们在单元格A1-A5中有以下内容:

    A1:一些文字,aZx

    A2:一些OtHer文字,Kvfr

    A3:Random TEXT,mot

    A4:文字文字,文字,LPK

    A5:任何其他随机文本,KKj

- >选择单元格A1-A5甚至整列A然后运行宏后,结果应为:

A1: Azx some text

A2: Kvfr Some OtHer text

A3: Mot Random TEXT

A4: Lpk Text text, text

A5: Kkj Any other random text

基本上我必须选择像", aZx"这样的群体; ", Kvfr"; ",mot"; ", LPK"; ",KKj",将它们转换为"Azx"; "Kvfr"; "Mot"; "Lpk"; "Kkj"然后将它们移动到该单元格中的整个文本前面。

这些字母组可以在宏中进行硬编码。

我的第一个想法是将所有我感兴趣的表达式放在数组中,如下所示:

Dim basicExpr(1 To 5) As String
basicExpr(1) = ", aZx"
basicExpr(2) = ", Kvfr"
basicExpr(3) = ",mot"
basicExpr(4) = ", LPK"
basicExpr(5) = ",KKj"

Dim replaceExpr(1 To 5) As String
replaceExpr(1) = "Azx "
replaceExpr(2) = "Kvfr "
replaceExpr(3) = "Mot "
replaceExpr(4) = "Lpk "
replaceExpr(5) = "Kkj "

然后我想遍历所有选定的单元格并检查来自basicExpr的值(同时检查值是否在字符串的末尾)并相应地处理单元格。

Set cellRange = Application.Selection
For Each Cell In cellRange

此时我陷入困境,因为我不知道如何从最后一个逗号到字符串结尾选择instrrev,然后将标题大小写并将其移动到字符串的前面。

2 个答案:

答案 0 :(得分:0)

怎么样:

 =PROPER(RIGHT(A1,3))&" "&LEFT(A1,LEN(A1)-5)

5基于您的示例,最后带有“,aZx” - 如果此更改,则必须对其进行编辑。没有宏,只是单元格中的一个函数。

答案 1 :(得分:0)

如果你总想移动逗号后面的文字,那么这段代码就可以了。

Option Explicit

Public Sub rearrangeTheText()

Dim cellRange As Range
Dim cell As Range
Dim positionFound As Integer
Dim theWholeText As String
Dim theSmallPart As String

Const TEXT_TO_FIND As String = ","

    Set cellRange = Application.Selection

    For Each cell In cellRange
        theWholeText = CStr(cell.Value)
        ' Look for last TEXT_TO_FIND
        positionFound = InStrRev(theWholeText, TEXT_TO_FIND, , vbTextCompare)
        If positionFound > 0 Then
            ' Get the text that is after TEXT_TO_FIND
            theSmallPart = Trim$(StrConv(Mid$(theWholeText, positionFound + Len(TEXT_TO_FIND)), vbProperCase))
            ' Delete the text and TEXT_TO_FIND from the end
            theWholeText = Trim$(Mid$(theWholeText, 1, positionFound - 1))
            ' Add the text to the front, separated by a space
            theWholeText = theSmallPart & Space(1) & theWholeText
            ' Update the cell
            cell.Value = theWholeText
        End If
    Next cell

End Sub