VBA for Excel - 使用包含引号的内容构建.Formula

时间:2014-09-18 06:59:21

标签: excel vba excel-vba

我在VBA for Excel中编写一个项目,它循环到一个文件,匹配每个数量的“代码”,然后将该代码的所有匹配项提供给用户定义的函数,该函数进入Excel表格。

我可以读取信息,对其进行排序,以便postdata(nr_of_datafield,nr_of_item)返回源列表中列出值的行。基于此,我需要创建(通过.Formula)这样的语法:

= formul(raming!J104)(如果只有一次出现) = formul(raming!J104;“+”; raming!J108)(等等,如果有多次出现,总是添加相同的额外内容) = formul(raming!J104;“+”; raming!J108;“+”; raming!312;“+”; raming!J403)etcetera,总是需要从Cells.Formula中已经存在的值中获取先前的值。 / p>

基于此检查:

代码:

Right(Workbooks(meetstaatfile).Sheets("HOR_raming").Cells(lusteller12, 9 + CInt(postdata(3, eerstepositie)) * 3).Formula, 2) = "()"

我可以检测到这里是否已添加任何内容。如果不是(意味着检查()结束是肯定的,我替换为:

代码:

Workbooks(meetstaatfile).Sheets("HOR_raming").Cells(lusteller12, 9 + postdata(3, eerstepositie) * 3).Formula = "=formul('raming'!J" & postdata(2, eerstepositie) & ")"

创建一个看起来像这样的公式:= formul(raming!J104)

(此示例中的'104'是postdata(2,eerstepositie)的输出

但是,如果它没有触发()结束,那么已经存在一个值,我需要将公式扩展为类似的东西:= formul(raming!J104;“+”; raming!J108)

我一直试图通过将')'替换为我想要添加的块来弄清楚如何做到这一点,但我无法让它工作来输入引号。 ('formul'与连接文本非常相似)。

如何更改上面的代码行,让我改变单元格输入?要么像我尝试的那样使用Replace(),要么读取formul()括号之间的内容并重建公式?

1 个答案:

答案 0 :(得分:0)

如果您需要在VBA中的字符串文字中使用引号作为内容,则必须将它们加倍。请参阅:http://msdn.microsoft.com/en-us/library/ms234766.aspx

.Formula = "=formul('raming'!J" & 104 & ",""+""," & "'raming'!J" & 108 & ")"

或者使用你的postdata:

.Formula = "=formul('raming'!J" & postdata(2, eerstepositie) & ",""+""," & "'raming'!J" & postdata(2, whatevergets108)  & ")"

我不知道,我是否理解正确,但如果你需要根据数组的内容连接公式,那么可以这样实现:

Sub test()
 'one occurrence
 postdata = [{0;104}]
 sFormulaString = getFormulaString(postdata, 2)
 MsgBox sFormulaString
 'two occurrences
 postdata = [{0,0;104,108}]
 sFormulaString = getFormulaString(postdata, 2)
 MsgBox sFormulaString
 'three occurrences
 postdata = [{0,0,0;104,108,312}]
 sFormulaString = getFormulaString(postdata, 2)
 MsgBox sFormulaString
End Sub

Function getFormulaString(postdata As Variant, nr_of_datafield As Long) As String
 sFormula = "=formul("
 For i = LBound(postdata, 2) To UBound(postdata, 2)
  sFormula = sFormula & "'raming'!J" & postdata(nr_of_datafield, i) & ",""+"","
 Next
 sFormula = Left(sFormula, Len(sFormula) - 5) & ")"
 getFormulaString = sFormula
End Function

嗯,或者真正需要将新的配方部分添加到现有配方中?如果是这样,以下代码将在每次运行时将新部件附加到A1中的公式中。

Sub test2()

 postdata = [{0;104}]

 sFormula = Range("A1").Formula
 If sFormula = "" Then sFormula = "=formul("
 If Right(sFormula, 1) = ")" Then sFormula = Left(sFormula, Len(sFormula) - 1) & ",""+"","
 sFormula = sFormula & "'raming'!J" & postdata(2, 1) & ")"
 Range("A1").Formula = sFormula

End Sub

问候

阿克塞尔