VBA将数组值传递给预定义的字符串

时间:2018-04-15 10:48:15

标签: vba excel-vba loops for-loop excel

这是过去问题的延续: VBA Fill cells on multiple sheets with formulas

作为我之前代码的改进版本,我很好奇如何将数组值分配给strFormulas(2)。我尝试使用以下循环将数组分配给循环所在的每个工作表。

我希望实现:

表1和表2是同一工作簿中的单独表格

如果循环落在表1(表索引= 2),则strFormulas(2)=“= IF('表1 S'!N1838 =”S“,”S“,”“)”

如果循环落在表2(表索引= 3),则strFormulas(2)=“= IF('表2 S'!N1838 =”S“,”S“,”“)”

但是,使用以下循环,nT不会被数组nTable中的值替换。它作为一个字符串继续生成公式 - > “= IF(NT!N1838 =” S “ ”S“, ”“)”

 Dim nT As Variant, nTable As Variant

 nTable = Array("'Table 1 S'", "'Table 2 S'")

 Dim w As Long
 Dim strFormulas(1 To 2) As Variant

  For w = 2 To ActiveWorkbook.Worksheets.Count
  With ActiveWorkbook.Worksheets(w)

    strFormulas(1) = "=IF(ISBLANK('Sheet 1'!A4),"""",'Sheet 1'!A4)"
    .Range("A2:AJ2").Formula = strFormulas(1)
    .Range("A2:AJ2000").FillDown
    'I believe here I need to define nT in terms of active sheet, but I can't think of an efficient way to do so...

    For Each nT In nTable
    strFormulas(2) = "=IF(nT!N1838=""S"",""S"","""")"
    .Range("AK2:AR2").Formula = strFormulas(2)
    .Range("AK2:AR2000").FillDown
    next nT

  End With
 Next w

感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

喜欢这个?使用char和text将@Jeeped归功于公式部分。

Public Sub AddFormulas()
    Dim nTable As Variant, w As Long
    Application.ScreenUpdating = False

    nTable = Array("Table 1", "Table 2") 'assumes these exist otherwise needs error handling

    For w = LBound(nTable) To UBound(nTable)
        With ActiveWorkbook.Worksheets(nTable(w))
                .Range("AK2:AR2000").Formula = "=IF('" & .Name & " S'!N1838=char(83), char(83), text(,))
        End With
    Next w
    Application.ScreenUpdating = True
End Sub
相关问题