简体   繁体   English

Excel根据第三个单元格的值将一个单元格的值复制到另一个单元格

[英]Excel copying value of one cell into another based off value of third cell

I am trying to have one cell from a range (AG2:AG30) copy the value of another cell from a similar range (AB2:AB30) based on the value of a third cell (D2:D30) . 我试图让一个单元格(AG2:AG30)的范围基于第三单元格(D2:D30)的值,从相似范围(AB2:AB30)复制另一个单元格的值。

  • The value for column D is selected from a drop down box and the value of column AB is a formula. D列的值是从下拉框中选择的,而AB列的值是一个公式。
  • I don't need to copy the formula into column AG just the value. 我不需要仅将值复制到AG列中。 Values for column D would be "Surgery" , "OR" , "ER" , "PICU" , and "Other" . D列的值为"Surgery""OR""ER""PICU""Other"

If anyone could help with a vba code that could do this I would greatly appreciate it. 如果有人可以帮助执行此操作的VBA代码,我将不胜感激。 Thanks! 谢谢!

Try the following 请尝试以下方法

=IF(C2=1,B2,A2)

IF says that you will display the value of the second parameter if the first parameter is true. IF表示如果第一个参数为true,则将显示第二个参数的值。 Otherwise it will copy the third parameter. 否则它将复制第三个参数。

In my example, if C2 is equal to 1, then the function will return B2. 在我的示例中,如果C2等于1,则该函数将返回B2。 Otherwise A2. 否则为A2。

I think this is more of.... exactly what you want :) 我认为这更多....正是您想要的:)

Please please comment if you have any questions. 如有任何疑问,请发表评论。 I broke it apart for coding clarity and easy customization. 我将其分解为代码清晰和易于定制。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM