首页 > 解决方案 > VBA - Excel - 如何使用列表对象在单元格中编写公式而不是值

问题描述

我在 VBA 上苦苦挣扎,在互联网上找不到解决方案。

这就是我想要做的。我有一个带有两张表的 excel 文件 第一张表是从数据库中提取的(有很多列,特别是一个称为“国家”的列)。它的格式为 ListObject 第二张表是一个计算器,用于计算另一张表中每个国家/地区的出现次数。它也被格式化为列表对象

例如最后我会得到: 法国:10 美国:25 意大利:30

我找到了如何使用 Application.WorksheetFunction.CountIf 函数来计算它。

现在我的问题是:是否可以在单元格中写公式,而不是写结果?目标是生成一个填充公式的工作表,这样当我在数据库工作表中更改内容时,它会自动重新计算我的结果。

这是我当前的代码:它有效,但我想在单元格中写一个公式,而不是结果。有一种简单的方法可以做到这一点吗?

非常感谢您的帮助!问候,J。

Dim i As Long

Dim CountryName As Variant
    
Dim KPI_LO As ListObject
Dim REVIEWEDDATA_LO As ListObject

'This is the list object with the database information
Set REVIEWEDDATA_LO = Worksheets(REVIEWEDDATA_SHEET_NAME).ListObjects(REVIEWEDDATA_LISTOBJECT_NAME)
'This is the list object where I'll store my results
Set KPI_LO = Worksheets(WASPKPI_SHEET_NAME).ListObjects(WASPKPI_LISTOBJECT_NAME)
 
'loop through each country column in the result sheet
For i = LBound(GetCountriesList) To UBound(GetCountriesList)
        'Get the name of the first country to find
        CountryName = GetCountriesList(i)
        
        'Count the number of occurence of this country in the column called COL_COUNTRY in the revieweddata List Object (in my database sheet).
        'This is what I'm trying to replace. I want to write a formula that do this calculation in the cell, instead of the result.
        KPI_LO.ListColumns(CountryName).DataBodyRange.Rows(1) = Application.WorksheetFunction.CountIf(REVIEWEDDATA_LO.ListColumns(COL_COUNTRY).DataBodyRange, CountryName)
Next i

标签: excelvbaformulalistobject

解决方案


如果您想在单元格中查看公式,那么您可以创建一个函数,然后调用它并传递您的值。

例如,创建一个模块:

Function fn_Multiply(x As Double, y As Double) As Double

Dim z As Double
z = x * y

fn_Multiply = z

End Function

并在excel中使用它作为这样的公式:

=fn_Multiply(A2,B2)

在此处输入图像描述


推荐阅读