在Excel中如果条件交换值
我有像下面的数据,并希望交换价值
我的VBA脚本是,
Private Sub CommandButton2_Click() Dim temp As Double temp = Range("A1").Value Range("A1").Value = Range("B1").Value Range("B1").Value = temp End Sub
它工作正常,但如果我有多个数据,
我想换个C列中的1,
那么如何修改我的vba脚本来工作多个数据交换的地方1。
提前致谢。
我们假设这些值是常数 。 我们将循环播放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
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
命题
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
我的0.02美分
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