excel - 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
解决方案
如果您想在单元格中查看公式,那么您可以创建一个函数,然后调用它并传递您的值。
例如,创建一个模块:
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)
推荐阅读
- python - 如何使用一个热编码 csv 文件作为 GroundTruth 将图像移动到文件夹中?
- c# - 有没有办法修复 button_name_clicked 匹配委托 Eventhandler 的重载问题
- reactjs - 状态正在更新,但组件没有将 props 中的更新状态发送到 Reactjs 中的子组件
- c - 如何计算进程收到信号的次数
- python - Python解析元素
- ios - Flutter ios 共享首选项显示 setstring on null 错误
- canvas - 是否可以将流作为源添加到 html 画布元素作为 html 视频元素?
- typescript - 为什么 Typescript 中的数组条目不允许空检查?
- c - 编译错误:从指针转换为不同大小的整数
- python - 是否有python函数(最好是seaborn)可以帮助我将两组点与散点图上的一条线连接起来?