根据特定条件将数据从一列偏移到另一列

时间:2015-09-22 21:22:59

标签: excel excel-vba vba

我想将一些数据偏移到另一列。数据存在于A列和B列中。我使用的代码是:

Sub data_shifter()
Dim A As Range, r As Range
Set A = Intersect(ActiveSheet.UsedRange, Range("A:A"))

For Each r In A

    If Mid(r, 4, 1) = "-" Then
        r.Copy r.Offset(0, 15)
        r.Clear
    End If
Next r

ActiveWorkbook.Save

End Sub

此代码正在查找A列中的所有字符串,其中-是第四个字符。我想要的是前三个字符应该是数字,第四个字符是-。此外,如果上述情况属实,则列B中的数据也应该偏移。

例如,如果列A2有333-m1233232,它应该偏移到p2,列B2中的数据应该偏移到Q2

2 个答案:

答案 0 :(得分:0)

Sub data_shifter()
    Dim r As Range
    For Each r In ActiveSheet.UsedRange.Columns(1).Cells
      If IsNumeric(Left(r, 3)) And Mid(r, 4, 1) = "-" Then
        r.Resize(1, 2).Copy r.Offset(0, 15)
        r.Clear
      End If
    Next r
    ActiveWorkbook.Save
End Sub

答案 1 :(得分:0)

我的两分钱,

Sub Button1_Click()

    Dim rng As Range, c As Range    
    Set rng = Range("A:A").SpecialCells(xlCellTypeConstants, 23)
    For Each c In rng.Cells
        If IsNumeric(Mid(c, 1, 3)) Then

            MsgBox " Do your thing"    'what ever you want after that
        End If
    Next c

End Sub