我的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。
先谢谢。
答案 0 :(得分:2)
假设值为常量。我们将对 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
答案 1 :(得分:2)
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
答案 2 :(得分:1)
一个命题
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
答案 3 :(得分:1)
我的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