【问题标题】:VBA Passing Array values to a pre-defined StringVBA将数组值传递给预定义的字符串
【发布时间】:2018-04-15 10:48:15
【问题描述】:

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

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

我希望达到:

表 1 和表 2 是同一工作簿中的不同工作表

如果循环位于表 1(工作表索引 = 2),则 strFormulas(2) = "=IF('Table 1 S'!N1838="S","S","")"

如果循环落在表 2 上(工作表索引 = 3),则 strFormulas(2) = "=IF('Table 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

感谢任何帮助!

【问题讨论】:

  • 每张纸是否只有一张桌子?这些表格是不是实际的 Excel 表格不仅仅是范围?你把公式放在表的什么地方?在所有列中?
  • @QHarr 表 1 是一张表,表 2 是另一张表。此处的表格是工作表名称。我将公式放在已经为 strFormula(2) 定义的范围内,即从 AK 到 AR 的列。

标签: vba excel loops for-loop


【解决方案1】:

像这样?感谢@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

【讨论】:

  • 哦,哇,我稍后会测试它,但我想这就是我要找的。我对 VBA 太陌生了,有很多技巧。
  • 我没有测试代码有一个忙碌的周末,我会告诉你它是否有效.. 今天晚些时候。谢谢!
  • S 在那里被它的 Char() 引用。例如,如果您在“表 2”中输入 S!N1838,您会看到它出现。
  • 如何在表 1 和表 2 后添加“S”..?这是解决方案中的错字吗?我可以将它添加到数组中吗?我不是要获取循环所在的当前表的名称。对于表 1,它将引用公式中的表 1 S。抱歉,您之前的评论来得太快了,我现在正在尝试。
  • 插入的公式,例如表1表中为=IF('Table 1'!N1838=CHAR(83), CHAR(83), TEXT(,)) 与=相同IF('表 1'!N1838= "S", "S", "") 。您可以通过在 N1838 中输入“S”然后查看 AK2 来进行测试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
  • 1970-01-01
  • 2016-12-08
  • 2015-03-22
  • 2022-11-26
相关资源
最近更新 更多