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)

我有四个不同变量中所需列的索引:c1,c2,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 & ")"
谁能帮我一下吗?任何帮助总是非常感激!

试试这个:

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

最新更新