Difference between two cells in third cell [closed]

女生的网名这么多〃 提交于 2019-12-13 08:48:52

问题


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:

  1. Three cells are selected. Two of them have values, the third one is blank.
  2. The VBA script is run.
  3. The VBA script calculates the difference between cells with values.
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!