首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据两个标准找到最高值,然后写入单元格

问根据两个标准找到最高值,然后写入单元格
EN

Stack Overflow用户
提问于 2019-10-09 14:48:38
回答 4查看 153关注 0票数 0

我有一个很大的csv/Excel发票(UPS -不确定这是否会重要)。我每周都会验证和分配缺失的成本中心,使用VBA来自动化这个过程。

通常情况下,它并不比,如果x是这个单元,然后使用y成本中心更复杂。

以下是问题所在:

我们使用综合发票,其中包含许多不同的帐户。有时帐户要收取服务费。如果是的话,该服务费适用于费用最高的账户下的成本中心。

下面是一个精简的示例。

我们首先:

​

因为D8说“服务费”,所以我需要B8以最高的费用与成本中心相等。就Account1而言,CostCenter1的收费最高,为17.00美元。对于Account2,它将是CostCenter3。

最终产品应该如下所示:

​

我会展示一些代码,但我不知道从哪里开始。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2019-10-09 15:27:38

我编写了一个用户定义函数,返回所需的CostCenter:

代码语言:javascript
复制
Public Function MaxCC()

Dim strAcc As String, strCC As String, dblChg As Double, lastrow As Long

strAcc = Application.Caller.Offset(, -1).Value2
lastrow = Application.Caller.Worksheet.Cells(Rows.Count, 1).End(xlUp).Row

Dim dictCC As New Scripting.Dictionary

Dim i As Long
For i = 2 To lastrow
    If Application.Caller.Worksheet.Cells(i, 1).Value2 = strAcc Then
        If i <> Application.Caller.Row Then strCC = Application.Caller.Worksheet.Cells(i, 2).Value2
        dblChg = Application.Caller.Worksheet.Cells(i, 3).Value2

        If Not dictCC.Exists(strCC) Then dictCC.Add strCC, 0

        dictCC(strCC) = dictCC(strCC) + dblChg
    End If
Next i

Dim strMaxCC As String, dblMaxCC As Double, varKey As Variant
dblMaxCC = 0
For Each varKey In dictCC.Keys
    If dictCC(varKey) > dblMaxCC Then
        strMaxCC = CStr(varKey)
        dblMaxCC = dictCC(varKey)
    End If
Next varKey

MaxCC = strMaxCC

End Function

此函数使用字典,只需确保引用Microsoft Scripting Runtime,如here所描述的。

您将能够将=MaxCC()作为公式输入到您需要填充的空单元格中,它将为您提供正确的CostCenter。如果这对你有用,如果你有后续问题,请告诉我。

票数 1
EN

Stack Overflow用户

发布于 2019-10-09 15:13:35

对于单元应用中的公式,

代码语言:javascript
复制
=INDEX(A:C,MATCH(MAXIFS(C:C,A:A,"="& A8,C:C,"<>"&C8),C:C),2)

只需将A8/C8替换为要放入的行,或将其粘贴到B8中,然后将单元格复制/粘贴到其他行。这是一个快速的修复,没有编程,只是使用内置功能的Excel。

​

​

票数 1
EN

Stack Overflow用户

发布于 2019-10-09 15:03:00

代码语言:javascript
复制
 function max2(arr,i) as double
  dim max as double 
  max=arr(i,0);
  for j=0 to ubound(arr,2)
    if arr(i,j)>max then max=arr(i,j)
   next
    max2=max
 end sub 

 sub test

  'build some kind of array structure for your pricing mess

  dim cc() as double
  redim cc(2,3)


   'just fill the structure somehow
   cc(0,0)=1'cc=cost center
   cc(0,1)=2
   cc(0,2)=3

   cc(1,0)=5
   cc(1,1)=1
   cc(1,2)=7

   'get the maximum profit to be able to buy a new Porsche      

  debug.print max2(cc,0)  

  debug.print max2(cc,1)

 'if we need a Ferrari

  result=max2(cc,0)  
  if max2(cc,1) > result then result =max2(cc,1)

  ' or just add a modified max sub with just one dimension
  'or fill a virtual cost center array with the results so far... and run the 
  'max2 fucntion on that  

end sub
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58306830

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档