[英]Excel VBA insert formula
i am trying to insert a formula in a cell using vba using a dynamic column reference like this: 我正在尝试使用vba使用像这样的动态列引用在单元格中插入公式:
Fred = ConvertToLetter(ActiveCell.Column)
Bob = "=DATE(LEFT(" + Fred + "2,4),MID(" + Fred + "2,5,2),MID(" + Fred + "2,7,2))"
ActiveCell.FormulaR1C1 = Bob
Function ConvertToLetter(iCol As Integer) As String
Dim iAlpha As Integer
Dim iRemainder As Integer
iAlpha = Int(iCol / 27)
iRemainder = iCol - (iAlpha * 26)
If iAlpha > 0 Then
ConvertToLetter = Chr(iAlpha + 64)
End If
If iRemainder > 0 Then
ConvertToLetter = ConvertToLetter & Chr(iRemainder + 64)
End If
End Function
but when it runs the formula ends up with single quotes around the cell and the formula does not work like this: 但是在运行时,该公式以单元格周围的单引号结尾,并且该公式无法像下面这样工作:
=DATE(LEFT('AY2',4),MID('AY2',5,2),MID('AY2',7,2))
how do i stop the single quotes being added to allow the formula to work correctly? 如何停止添加单引号以使公式正常工作?
Thanks 谢谢
It's the FormulaR1C1
property causing the problem. 这是导致问题的
FormulaR1C1
属性。
Do this instead: 改为这样做:
ActiveCell.Formula = Bob
By the way, instead of the ConvertToLetter() function, you can use this: 顺便说一句,您可以使用以下方法来代替ConvertToLetter()函数:
Fred = Split(ActiveCell.Address, "$")(1)
您可以改为使用此''(两个单撇号)。
To use R1C1 formula you'd use: 要使用R1C1公式,请使用:
ActiveCell.FormulaR1C1 = "=DATE(LEFT(R2C,4),MID(R2C,5,2),MID(R2C,7,2))"
R2 in the formula means Row 2. C in the formula means the column the formula is in. 公式中的R2表示第2行。公式中的C表示公式所在的列。
Looking at R1C1 notation: 查看R1C1表示法:
R[-1] means this row minus 1. R [-1]表示此行减1。
C[1] means this column plus 1. C [1]表示此列加1。
R1 means row 1 R1表示第1行
C1 means column 1 C1表示第1列
R means this row. R表示此行。
C means this column. C表示此列。
So, in cell B2 - R1C1 means cell A1. 因此,在单元格B2中-R1C1表示单元格A1。
R1C[-1] means cell A1 R1C [-1]表示单元格A1
RC1 means cell A2. RC1表示单元格A2。
RC means cell B2. RC表示单元格B2。
Hope that's clear. 希望很清楚。 :)
:)
or you can just use ActiveCell.Formula = Bob as Excel Hero said. 或者您可以像Excel Hero所说的那样使用ActiveCell.Formula = Bob。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.