Excel基于第三个单元格的值将一个单元格的值复制到另一个单元格

时间:2016-02-27 13:51:59

标签: excel vba excel-vba

我正在尝试让范围(AG2:AG30)中的一个单元格根据第三个单元格(AB2:AB30)的值从类似范围(D2:D30)复制另一个单元格的值。

  • 从下拉框中选择列D的值,列AB的值是公式。
  • 我不需要将公式复制到AG列中。 D列的值为"Surgery""OR""ER""PICU""Other"

如果有人可以提供可以做到这一点的vba代码,我将非常感激。谢谢!

2 个答案:

答案 0 :(得分:0)

尝试以下

=IF(C2=1,B2,A2)

IF表示如果第一个参数为true,您将显示第二个参数的值。否则它将复制第三个参数。

在我的例子中,如果C2等于1,则该函数将返回B2。否则A2。

答案 1 :(得分:0)

我认为这更像是你想要的......

如果您有任何疑问,请发表评论。为了清晰度和易于定制,我把它拆开了。

Option Explicit

'module-scope variables
Dim range1 As Range
Dim range2 As Range
Dim range3 As Range
Dim i As Long
Dim string1 As String

Dim address1 As String
Dim address2 As String


Sub derp()

'set your sheet here or just let it work on active sheet

Set range1 = Range("AG2:AG30")
Set range2 = Range("AB2:AB30")
Set range3 = Range("D2:D30")

For i = 0 To range3.Rows.Count

    string1 = range3(i).Value
    address1 = range1(i).Address
    address2 = range2(i).Address

    Select Case string1

        Case string1 = "Surgery"
            'do stuff here
            Call Valueswap(address1, address2)

        Case string1 = "OR"


        Case string1 = "ER"

        Case string1 = "PICU"

        Case string1 = "Other"

        Case Else
            'value in column D yields error, put a message here

    End Select

Next







End Sub

Function Valueswap(address1 As String, address2 As String)
    'puts second address value into the first address
    Range(address2).Value = Range(address1).Value

End Function