简体   繁体   English

如何使用VBA添加引用另一个单元格的公式?

[英]How do I add a formula with VBA that refers to another cell?

I searched but didn't found what I was looking for. 我搜索了但没有找到我想要的东西。 My goal is to have a big number of cells that shows the value of other cells in other sheets like a simple "=january!BP$43". 我的目标是要有大量的单元格来显示其他工作表中其他单元格的值,例如简单的“ = january!BP $ 43”。 But I want to add this with a loop, here a simplified example: 但是我想添加一个循环,这里是一个简化的例子:

  For sorte = 0 To 5
    For mois = 0 To 11
        Sheets(2).Range(4+k, 1 + mois + j).Formula = "=Sheets(3 + mois).Cells(40+i, 2 + sorte)"
    Next
    j = j + 13
    i=i+15
    k=k+1
Next

I tried it without the " " around "Sheets...)" and it works but just inserts the value and not the formula. 我尝试了在“ Sheets ...)周围没有“”的情况,但它可以工作,但只插入值而不是公式。 Any Idea? 任何想法? Thanks a lot 非常感谢

PS: j,i,k are just here to show that I have other variables coming there to change the position. PS:j,i,k只是在这里显示我还有其他变量可以更改位置。

Remember that everything in between quotation marks will be copied as a string. 请记住,引号之间的所有内容都将被复制为字符串。 You need to close the quotation marks whenever you want to use the value of the variable, not the variable name: 每当您要使用变量的值而不是变量名时,都需要关闭引号:

For mois = 0 To 11
    Sheets(2).Range(4+k, 1 + mois + j).Formula = "=Sheets(" & 3 + mois & ").Cells(" & 40+i & "," & 2 + sorte& ")"
Next

However, wouldn't it be easier to just use Excel and copy to the cells you need? 但是,仅使用Excel并复制到所需的单元格是否会更容易?

You will need to place the sheet name in using Sheets(3 + mois).Name , and it will be easiest to refer to the row and column using R1C1 notation: 您将需要使用Sheets(3 + mois).Name放置工作表名称,使用R1C1表示法最容易引用行和列:

For sorte = 0 To 5
    For mois = 0 To 11
        Sheets(2).Cells(4+k, 1 + mois + j).FormulaR1C1 = "='" & Sheets(3 + mois).Name & "'!R" & (40+i) & "C" & (2 + sorte)
    Next
    j = j + 13
    i=i+15
    k=k+1
Next

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM