Excel宏将匹配表达式的单元格移动到右侧的一个单元格

时间:2011-01-27 06:26:53

标签: excel excel-vba vba

我想在Excel 2011中将所有与特定搜索字符串匹配的单元格向右移动一个单元格,但我是一个完整的Excel菜鸟。

例如,使用搜索字符串“A”:

A A A _ _ B A A _

成:

_ A A A _ B _ A A

NOT:

_ A _ A _ B _ A

谢谢!

1 个答案:

答案 0 :(得分:2)

Sub MoveRight()

    Dim rFound As Range
    Dim lFirstCol As Long
    Dim rSearch As Range

    Const sSEARCH As String = "A"

    Set rSearch = Sheet1.Cells
    'Find the first instance in the right most column
    Set rFound = rSearch.Find(sSEARCH, rSearch.Cells(1), xlValues, xlWhole, xlByColumns, xlPrevious, True)

    'If a cell was found
    If Not rFound Is Nothing Then
        'Record the column so we know when to stop
        lFirstCol = rFound.Column

        'loop through all the found cells
        Do
            rFound.Offset(0, 1).Value = rFound.Value
            rFound.ClearContents
            Set rFound = rSearch.FindPrevious(rFound)
        'stop when it wraps back around and finds the first
        'instance that you moved one cell to the right
        Loop Until rFound.Column > lFirstCol
    End If

End Sub

确保在运行此宏之前保存文件的备份。如果它没有做你想要的,就没有撤消。