使用vba在excel中的不同列中应用各种公式

时间:2014-06-08 13:51:57

标签: excel vba excel-vba formula copy-paste

我有多个公式,我想在工作表的不同列中填充。我试图使用此代码...

Dim strFormula(1 To 2) As Variant
Dim LastRow As Integer   'This is the LAST Non Empty Row

LastRow = ActiveWorkbook.Worksheets("FinalDetails").UsedRange.Row - 1 _
    + ActiveSheet.UsedRange.Rows.Count

With ThisWorkbook.Sheets("FinalDetails")
    strFormula(1) = "=IF(V2='Green','Preferred',IF(V2='LightGreen','Satisfactory',IF(V2='Yellow','Mediocre',IF(V2='Orange','Low',IF(V2='Red','Very Low',IF(V2='Black','HighRisk', 'No Analysis'))))))"
    strFormula(2) = "=IF(AB2<>"", CONCATENATE(AA2,' ','Band',' ',AB2),"")"
'   strFormula(3) = "=A2/B2"

    .Range("BH2:BI2").Formula = strFormula --'im having error on this Application defined or onject defined error
    .Range("BH2:BI" & LastRow).FillDown
End With

End Sub

遗憾的是,我在这里看到了这段代码,没有人回答是否正常工作。

2 个答案:

答案 0 :(得分:0)

使用 VBA 在公寓中放置公式时要记住的重要事项是双引号加倍:

Sub qwerty()
    Range("A1").Formula = "=IF(Z1=""Happy"",1,2)"
End Sub

导致在 A1

单元格中使用此公式
=IF(Z1="Happy",1,2)

答案 1 :(得分:0)

ActiveWorkbook.Worksheets(“FinalDetails”)。UsedRange.Row将始终= 1,因此这里是多余的。

我认为ActiveSheet是“FinalDetails”

有更好的方法。

我会做这样的事情:

Dim vFormula(1 To 2) As Variant
Dim ra As String ' range address
Dim ur As Range  ' used range
Dim pr As Range  ' paste range

Dim rc As Integer ' row count
Dim cc As Integer ' column count
Dim hr As Integer ' header rows

Set ur = Worksheets("FinalDetails").UsedRange

hr = 1 ' number of header rows

ra = ur.Cells(1 + hr, 1).Address(False, False)

rc = ur.Rows.Count
cc = ur.Columns.Count

Set pr = ur.Offset(hr, cc).Resize(rc - hr, UBound(vFormula))

vFormula(1) = "=GetSatisfied(" & ra & ")"
vFormula(2) = "=IF(A$1<>""" & """, A1 & "" Band "" & B1, """ & """)"

pr.FormulaArray = vFormula

在这里,我使用“最终详细信息”的使用范围,并在右侧创建一个新的范围cc列,并重新调整大小,使其与原始列的行数相同,列的宽度与vFormulas列的列相同。 / p>

我还在处理了使用范围内的标题行。

我的示例中usedrange的第一列具有第V列中的颜色满意度

对于strFormula(1)我写了一个简单的函数GetSatisfied;

Function GetSatisfied(sColor As String) As String
  Select Case sColor
      Case "Green"
          GetSatisfied = "Preferred"
      Case "LightGreen"
          GetSatisfied = "Satisfactory"
      Case "Yellow"
          GetSatisfied = "Mediocre"
      Case "Orange"
          GetSatisfied = "Low"
      Case "Red"
          GetSatisfied = "Very Low"
      Case "Black"
          GetSatisfied = "High Risk"
      Case Else
          GetSatisfied = "Not Analysed"
  End Select
End Function

对于strFormula(2),你不需要连接 - “&amp;”或者“+”是连接 - 但你必须弄清楚如何写字符串。

使用即时窗口:

?“= IF(A $ 12&lt;&gt;”“”&amp;“”“,A1&amp;”“Band”“&amp; B1,”“”&amp;“”“”)

输出应与您希望单元格公式读取的内容相匹配