首页 > 解决方案 > Excel VBA:公式 R1C1 绝对引用变量中的多列

问题描述

我有以下问题:

我得到了各种具有或多或少相同标题的 Excel 工作表(它们并不总是相同),但几乎总是以不同的顺序。但是,我可以通过搜索标题名称来获取列的索引。我现在要做的是创建一个新列,它基本上是我拥有索引的列中每一行的串联。我试图通过使用 R1C1 公式来做到这一点,但我无法让它正常工作。

示例表:

Name | Surname | Nationality | Destination
------------------------------------------
Sue  | Ohara   | American    | Spain
Jon  | Miller  | British     | Italy

现在我想要一个新专栏Information

Name | Surname | Nationality | Destination | Information
-------------------------------------------------------------------------
Sue  | Ohara   | American    | Spain       | Sue, Ohara, American (Spain)
Jon  | Miller  | British     | Italy       | Jon, Miller, British (Italy)

我在四个不同的变量中有所需列的索引:c1c2和。c3c4

我在这篇文章中读到,可以使用变量来引用 R1C1 公式中的绝对列,但是,当我尝试执行以下操作时,我不断收到错误:

Range(Cells(2, lastCol).Address, Cells(lastRow, lastCol).Address.FormulaR1C1 = "=C"&c1 & C & c2

为什么这不起作用?

但是,这有效

Range(Cells(2, lastCol).Address, Cells(lastRow, lastCol).Address.FormulaR1C1 = "=C"&c1

为什么我不能简单地写一些类似的东西:

Range(Cells(2, lastCol).Address, Cells(lastRow, lastCol).Address.FormulaR1C1 = "=C" & c1 & "," & C & c2 & " - (" & C & c3 & ")"

任何人都可以在这里帮助我吗?一如既往地非常感谢任何帮助!

标签: excelvbaexcel-formulaexcel-r1c1-notation

解决方案


尝试这个:

Sub test1()
    Dim c1, c2, c3, c4, lastCol, lastRow
    c1 = 5: c2 = 7: c3 = 12: c4 = 17: lastCol = 20: lastRow = 10 ' dummy values
    
    
    Range(Cells(2, lastCol), Cells(lastRow, lastCol)).FormulaR1C1 = _
        "=RC" & c1 & "&RC" & c2 & "&RC" & c3 & "&RC" & c4
End Sub

推荐阅读