如果更改了单元格A值,我想将值从单元格B移动到单元格C.

时间:2013-07-27 13:38:43

标签: excel-vba vba excel

我在A栏和B栏中都有值。 列A值应为通过/失败。 如果A列值从Fail to Pass更改,则B列值应移至C列。

我的意思是说如果值从A变为B,那么B应该移动到另一个单元格。

E.g:

变更前:

Column A   Column B  Column C 

 Fail         123       -

 Pass          -        456

变更后:

Column A   Column B  Column C 

 Pass        -          123

 Fail        456         -

一旦值改变,它应该自动发生。我不想每次都运行这个宏。

感谢Adavance!

2 个答案:

答案 0 :(得分:1)

Private Sub Worksheet_Change(ByVal Target As Range)
CR = Target.Address
SplitCR = Split(CR, "$")
CC = SplitCR(1)
CR = SplitCR(2)
If CC = "A" Then
    CellBValue = Range("B" & CR)
    CellCValue = Range("C" & CR)
    Range("B" & CR).Value = CellCValue
    Range("C" & CR).Value = CellBValue
End If
End Sub

将上述代码粘贴到工作表中。

答案 1 :(得分:0)

尝试将其放入Sheet1的VBA代码

' Requirement: Let's say the data before change looks like this:
' Column A -- Column B -- Column C
' Fail           123          -
' Pass            -          456
'
' After change of column A, data should look like this:
' Column A -- Column B -- Column C
' Pass            -          123
' Fail           456          -
'
Private Sub Worksheet_Change(ByVal Target As Range)

    ' Do calculations only if the target of change is 1st column (i.e. column A)
    If Target.Column = 1 Then

        ' Let's remember the data that's already in Column B and Column C
        Dim DataInColumnB, DataInColumnC As String
        DataInColumnB = Range(Replace(Target.Address, "A", "B")).Value
        DataInColumnC = Range(Replace(Target.Address, "A", "C")).Value

        ' We assume that if A has Pass, dash will be in column B
        ' and if A has Fail, dash will be in column C
        ' If we find that A has Pass but B is not a dash, we must swap information in B and C
        ' Similarly if A has Fail but C is not a dash, we must also swap information in B and C
        If (LCase(Target) = "pass" And DataInColumnB <> "-") Or _
        (LCase(Target) = "fail" And DataInColumnC <> "-") Then

            Range(Replace(Target.Address, "A", "B")).Value = DataInColumnC
            Range(Replace(Target.Address, "A", "C")).Value = DataInColumnB

        End If

    End If

End Sub