简体   繁体   中英

Using VBA to output a value in a column given a certain input

Here's what I would like to do:

I have a list of values in a column. I would like VBA to read that column, and than output values into a new column based on conditions I give it. For example, if the value in column A is between 1 and 2, I would like the value in column b to be 6, if the value is between 2 and 3, I would like the value in column b to be 20.

Thanks!

In B1 put the formulae:

=Test(A1)

then replicate it down to as far as you need it.

The put the following function.

Function Test(v)
    Test = "Default"
    If v >= 1 And v <= 2 Then Test = 6
    If v >= 3 And v <= 4 Then Test = 20
    'Add more conditions here...
End Function

Rename the function to whatever you want it to be if needed.

Hope this helps

Try this:

Dim r as Range, i as Integer, N as Integer
N = 20 'number of values
Set r = Range("A2").Resize(N,1) 'A2 is top left of column
Dim values() as Variant
values = r.Value   'Read all values from worksheet to array
For i=1 to N
    'Step through the values and transform according to your rules
    If values(i,1)>=1 And values(i,1)<2 then 
        values(i,1) = 6
    ElseIf values(i,1)>=2 And values(i,1)<3 then 
        values(i,1) = -3
    Else If
        ...
    End If
Next i
'Go to columns on the *right* and output transformed array there
r.Offset(0,1).Value = values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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