简体   繁体   English

用VBA在单元格中写一个Excel公式

[英]Write an excel formula in a cell by VBA

I want to write an excel formula into a cell by a VBA code. 我想通过VBA代码将Excel公式写入单元格。 I have a table in "sheets1" named "Table1". 我在“ sheets1”中有一个名为“ Table1”的表。 In "sheets2", cell "A2" I want to add a formula to subtract first row and final row of column B of "Table1" from "sheets1" so that the user can see the formula in the cell. 在“ sheets2”的单元格“ A2”中,我想添加一个公式以从“ sheets1”中减去“ Table1”的B列的第一行和最后一行,以便用户可以在单元格中看到该公式。 Is there any way to do that? 有什么办法吗?

Would be something like this 会是这样的

Public Function Substract()
    dim firstRow as Integer
    dim endrow as Integer

    firstrow = IIf(IsEmpty(Sheets("Table1").Range("B1")), Sheets("Table1").Range("B1").End(xlDown).Row, 1)
    endrow =  Sheets("Table1").Cells(Sheets("Table1").Rows.count,"B").End(xlUp).Row

    Substract = firstrow  - endrow
End Function

Note: You have to Create a Module an put the Code in there 注意:您必须创建一个模块,并将代码放入其中

In excel you can call this as a Formular with =Substract() 在excel中,您可以使用= Substract()将其称为公式

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

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