问题
I was trying to make a VBA script that would calculate the differene between two cells and place it in the third cell. It should work in the following situation:
- Three cells are selected. Two of them have values, the third one is blank.
- The VBA script is run.
- The VBA script calculates the difference between cells with values.
- The difference is recorded in the third (blank) cell.
As you could understand such a VBA script should be able to record the difference in a cell on the right from the values, below, on the left or above.
I'm a newbie in vba so my vba coding depends a lot on the forums were similar issues are discussed. But this time I could not find a solution.
回答1:
Try this:
Dim rng As Range, cel As Range
Set rng = Selection
If rng.Cells.Count <> 3 Then Exit Sub
With Application.WorksheetFunction
If .CountA(rng) <> 2 Then Exit Sub
For Each cel In rng
If cel.Value = "" Then
Select Case True
Case cel.Address = rng(1).Address
cel.Value = rng(2)-rng(3)
Case cel.Address = rng(2).Address
cel.Value = rng(1)-rng(3)
Case cel.Address = rng(3).Address
cel.Value = rng(1)-rng(2)
End Select
Exit For
End If
Next
End With
not tested soi leave it to you.
Edited for simoco
来源:https://stackoverflow.com/questions/21799728/difference-between-two-cells-in-third-cell