简体   繁体   English

将具有串联部分的公式写入单元格

[英]Writing a formula with concatenated parts into a cell

Scenario: I have a code that should write a formula to a worksheet cells. 场景:我有一个代码,应该将公式写入工作表单元格。 This formula is for an API to retrieve some value. 此公式用于API检索某些值。 My formula is inside a loop (this is done for multiple columns) and references the first row for an identifier. 我的公式在循环内(此操作针对多列完成),并引用第一行作为标识符。

The original formula: 原始公式:

=FS(B1;"FI(DATE,,DATE)")

The modified formula with the floating reference (inside the loop): 带有浮动引用的修改公式(在循环内部):

For i = 1 To lColumn
    If wb.Worksheets("Dates").Cells(i, 1).Value <> "" Then
        wb.Worksheets("Dates").Cells(i,2).value = "=FS(" & i & "1;"FI(DATE,,DATE)")"
    End If
Next i

Where lColumn is some pre-defined number. 其中lColumn是一些预定义的数字。

Issue: I keep getting the "Unexpected end of statement" error in the formula part of the loop. 问题:我在循环的公式部分中不断收到“意外的语句结尾”错误。

What I already tried: I tried different variations, repositioning the "s and 's, for example: 我已经尝试过的内容:我尝试了不同的变体,例如,重新定位了“ s”和“ s”

wb.Worksheets("Dates").Cells(i,2).value = "'"=FS(" & i & "1;"FI(DATE,,DATE)")""

or 要么

wb.Worksheets("Dates").Cells(i,2).value = "'=FS(" & i & "1;"FI(DATE,,DATE)")"

or 要么

wb.Worksheets("Dates").Cells(i,2).value = "'""=FS(" & i & "1;"FI(DATE,,DATE)")"

and so on. 等等。 But the error still persists. 但是错误仍然存​​在。

Question: What is the proper way to do this operation? 问题:执行此操作的正确方法是什么?

Working with formulas in VBA is a little bit tricky: 在VBA中使用公式有点棘手:

  • To write a formula, use the range.formula property, not the .value . 要编写公式,请使用range.formula属性,而不要使用.value

  • You have to write the formula as if you are using an english Excel. 您必须像使用英文Excel一样编写公式。 Parameter-separator is comma (not semicolon). 参数分隔符是逗号(不是分号)。

  • If a formula needs a quote, double it so that the VBA compiler understands that you want a quote within a string. 如果公式需要引号,请将其加倍,以便VBA编译器理解您要在字符串中使用引号。
  • I find it helpfull to write a formula into a variable before assigning it - you can check in the debugger if it is exactly how it should before assigning it. 我发现在分配公式之前将公式写入变量是有帮助的-您可以在分配给调试器之前检查调试器是否恰如其分。
  • To check how the formula should look like, write it into a cell, change to the VBA-editor, open the immediate window and write ? activecell.formula 要检查公式的外观,请将其写入单元格,更改为VBA编辑器,打开立即窗口,然后输入? activecell.formula ? activecell.formula

Try (untested as the formula you need is not valid to us): 试试(未经测试,因为您需要的公式对我们无效):

with wb.Worksheets("Dates")
  dim f as string, adr as string
  adr = cells(i, 1).address(false, false)   ' get rid of Dollar signs
  f = "=FS(" & adr & ",""FI(DATE,,DATE)"")"
  .Cells(i, 2).formula = f
end with
wb.Worksheets("Dates").Cells(i,2).formula = "=FS(" & Cells(1, i).Address(0,0) & ";""FI(DATE,,DATE)"")"

可能有更好的方法将列号转换为字母(这是您遇到的问题以及双引号)!

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

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