简体   繁体   中英

In Excel/VBA, how to apply a formula to a range based on cell value?

I have a column of data (S8:S999) that contains various units of measure (PC, CTN, EA, etc). The column to the right (T8:T999) contains a location.

I'd like to apply a formula to cells in the adjacent cells (T8:T999), but only where the value in (S8:S999) contains the "PC" value. We have items with multiple UOM, and for example the CTN and PC variations have different locations. Our report is limited, and only generates the primary/CTN location. This button/script will change the locations of any items listed as PC (but not CTN, etc)

So if "S8" is "PC", apply formula to "T8"

if "S27" is "PC", apply formula to "T27" etc

Updated code (thanks BigBen)

Private Sub CommandButton1_Click()

Dim UomRange As Range

  Set UomRange = Worksheets("START").Range("S8:S999")
  
  For Each cell In UomRange
    If cell.Value Like "PC" Then
    cell.Offset(, 1).Formula = "=VLOOKUP(J8,LocRef!$A$1:$C$9999,3,FALSE)"
        
    Else
  
  
  End If
  Next

End Sub

What you are trying to do looks very weird, but anyways...

Private Sub CommandButton1_Click()

Dim UomRange As Range

Dim Dummy As Integer
Set UomRange = Worksheets("START").Range("S8:S999")

For Each cell In UomRange
    if cell.HasFormula = False then  'Has  no formula, so could be "PC"
        If cell.Value Like "PC" Then
            Range("S8:S999").Formula = "=MyFormulaHere"
        end if
    'else 'If it has a formula, it by definition won't look like the text "PC" (unless you've if logic in your formula?) so we can bypass
    end if  
Next

End Sub

But I suspect you are not looking to do what you have presented so far...

edit:

If UoMRange is supposed to represent the item number which can drive the change in location - which occurs via formula then the definition of UoMRange in your original isn't right.

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