[英]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). 参数分隔符是逗号(不是分号)。
? 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.