问题描述
我在VBA上挣扎,无法在Internet上找到解决方案。
这就是我想要做的。 我有两张纸的Excel文件 第一页是从数据库中提取的内容(有很多列,特别是一列称为“国家”)。它被格式化为ListObject 第二张纸是一个计算器,用于计算另一张纸中每个国家/地区的发生次数。它还被格式化为列表对象
例如,最后我将得到: 法国:10 美国:25 意大利:30
我发现了如何使用Application.WorksheetFunction.CountIf函数来计算此值。
现在我的问题是:是否可以在单元格中编写公式,而不是编写结果? 目的是生成一个充满公式的工作表,以便当我更改数据库工作表中的内容时,它将自动重新计算结果。
这是我当前的代码:可以,但是我想在单元格中写一个公式,而不是结果。 有这样做的简便方法吗?
感谢lof的帮助! 问候,
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)