Swap values with if conditions in Excel

2019-09-05 13:24发布

I have data like below and want to swap value enter image description here

My VBA script is ,

Private Sub CommandButton2_Click()
Dim temp As Double
temp = Range("A1").Value
Range("A1").Value = Range("B1").Value
Range("B1").Value = temp
End Sub

It works fine, but If i have multiple data like,

enter image description here

I want to swap value where 1 in C column like,

enter image description here

So How do I modify my vba script to work multiple data swap where 1.

Thanks in Advance.

4条回答
Fickle 薄情
2楼-- · 2019-09-05 13:24

my 0.02 cents

Option Explicit

Sub main()
    Dim vals As Variant
    Dim iRow As Long

    With Range("C1", Cells(Rows.count, 1).End(xlUp))
        vals = .Value
        For iRow = 1 To .Rows.count
            If vals(iRow, 3) = 1 Then
                .Cells(iRow, 1) = vals(iRow, 2)
                .Cells(iRow, 2) = vals(iRow, 1)
            End If
        Next
    End With
End Sub
查看更多
Juvenile、少年°
3楼-- · 2019-09-05 13:25

a proposition

for each c in range("C1:C" & cells(rows.count,1).end(xlup).row)
 if c=1 then
  temp=c.offset(,-2)
  c.offset(,-2)=c.offset(,-1)
  c.offset(,-1)=temp
 end if
next
查看更多
做个烂人
4楼-- · 2019-09-05 13:28
Sub Main()
    Dim cl as Range, temp as Range

    For each cl in Range("A1:A" & Range("A1").End(xlDown).Row)
        If cl.offset(0, 2) = 1 Then
           temp = cl
           cl = cl.offset(0, 1)
           cl.offset(0, 1) = temp
        End if
    Next cl
End Sub
查看更多
太酷不给撩
5楼-- · 2019-09-05 13:37

Let's assume the values are constants. We will make a loop over the stuff in column C:

Sub MultiSwap()
    Dim C As Range, r As Range, v As Variant
    Set C = Range("C:C").Cells.SpecialCells(xlCellTypeConstants)
    For Each r In C
        If r.Value = 1 Then
            v = r.Offset(0, -2).Value
            r.Offset(0, -2).Value = r.Offset(0, -1).Value
            r.Offset(0, -1).Value = v
        End If
    Next r
End Sub
查看更多
登录 后发表回答