简体   繁体   English

在 Excel/VBA 中,如何根据单元格值将公式应用于范围?

[英]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).我有一列数据(S8:S999),其中包含各种计量单位(PC、CTN、EA 等)。 The column to the right (T8:T999) contains a location.右侧的列 (T8:T999) 包含一个位置。

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.我想将公式应用于相邻单元格(T8:T999)中的单元格,但仅限于(S8:S999)中的值包含“PC”值的地方。 We have items with multiple UOM, and for example the CTN and PC variations have different locations.我们有具有多个 UOM 的项目,例如 CTN 和 PC 变体有不同的位置。 Our report is limited, and only generates the primary/CTN location.我们的报告是有限的,并且只生成主要/CTN 位置。 This button/script will change the locations of any items listed as PC (but not CTN, etc)此按钮/脚本将更改列为 PC 的任何项目的位置(但不是 CTN 等)

So if "S8" is "PC", apply formula to "T8"因此,如果“S8”是“PC”,则将公式应用于“T8”

if "S27" is "PC", apply formula to "T27" etc如果“S27”是“PC”,则将公式应用于“T27”等

Updated code (thanks BigBen)更新代码(感谢 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.如果 UoMRange 应该代表可以驱动位置变化的项目编号 - 通过公式发生,那么原始中 UoMRange 的定义是不正确的。

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

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