2014-10-08 68 views
0

我有一个列名称作为“验证”,但列号保持更改。我怎样才能找到这个名称的名称,并将其作为范围。通过选择列名作为范围来添加Excel公式的VBA

当前,下面是我正在使用的宏,它检查列M并为所有单元格添加公式,如果列M不为空。

我的新的期望是,

  1. 见M列,如果有细胞的值作为“BLM” &“CFG”,然后通过找到列名“验证”添加了Excel 式为那些具有 那单元格值为“BLM”&“CFG”,如果空白则跳过。
  2. 更改所有这些公式单元格值

Sub test_macro() 
    Dim sFormula As String 
    Dim rng As Range 
    Dim ws2 As Worksheet 

    sFormula = "=IF(IFERROR(VLOOKUP(RC[-11],'Service ID Master List'!C[-11],1,0),""Fail"")=""Fail"",""Check SESE_ID"","""")&IF(IFERROR(VLOOKUP(RC[-9],Rules!C[-13],1,0),""Fail"")=""Fail"","" | Check SESE_RULE"","""")&IF(TRIM(RC[-5])="""","""",IF(IFERROR(VLOOKUP(RC[-5],Rules!C[-13],1,0),""Fail"")=""Fail"","" | Check SESE_RULE_ALT"",""""))&IF(RC[-7]=""TBD"","" | Check SEPY_ACCT_CAT"","""")" 

    Set ws2 = ActiveSheet 

    With ws2 
     Set rng = .Range("M2") 
     Set rng = .Range(rng, .Cells(.Rows.Count, rng.Column).End(xlUp)) 
    End With 
    rng.SpecialCells(xlCellTypeConstants).Offset(0, 1).FormulaR1C1 = sFormula 
    'changing formulas in values 
    Columns("N:N").Select 
    Selection.Copy 
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ 
     :=False, Transpose:=False 
    Range("N1").Select 
    Application.CutCopyMode = False 
End Sub 

回答

0

您可以使用查找方法找到你的范围。
喜欢的东西:

EDIT1:

'~~> get the position of 'Validation' column and set rng variable 
With ws2 
    Dim valCol As Long 
    valCol = .Rows("1:1").Find("Validation").Column '~~> change to suit 
    Set rng = .Range("M2") 
    Set rng = .Range(rng, .Cells(.Rows.Count, rng.Column).End(xlUp)) 
End With 

然后检查M列条目:

Dim cel As Range 
For Each cel In Rng 
    If cel = "BLM" Or cel = "CFG" Then 
     With ws2.Cells(cel.Row, valCol) 
      .Formula = sFormula 
      .Value = .Value 
     End With 
    End If 
Next 

这是假设与验证一列名字始终存在,并且公式是正确的。还有check this out to see ways of avoiding select which will greatly improve coding

+0

不完全,但我可能能够做到这一点,可能是我没有提及的要求非常好,无论如何。 – Chito 2014-10-09 00:37:17