VBA if语句函数将两列中的数据相乘

时间:2018-10-11 16:11:50

标签: excel vba

我是Vba的新手,我一直在尝试找出在if语句之后如何在两个不同的列中将两个数字相乘。 excel中的数据布局如下。如果货运类型是例如商店转移,但我的下面的代码不起作用,我想做的就是将成本乘以重量乘以重量,但是您的帮助将不胜感激。知道我是否需要两个额外的for循环来获取成本和重量。

    freighttype                
    Column(b)                  

    Store Transfer                      
    Ecommerce   


    Cost        
    Column(c)
    7
    6

    Weight
    column (e)
    2
    3

代码是:

    Option Explicit

    Function essay(ft As Range) As Long

    Dim x As Variant

    For Each x In ft
        If ft = "store transfer" Then
            essay = Range("b2:b365").Offset(0, 1) * Range("b2:b365").Offset(0, 3)
        Else
            essay = 0
        End If
    Next x
    End Function

2 个答案:

答案 0 :(得分:0)

与Excel不同,您不能在VBA中将两个数组相乘。

对于等效项,您可以遍历所有单元格,将它们一一相乘并保持连续运行,也可以在SUMPRODUCT内使用EVALUATE工作表函数

例如,假设您的ft范围在B列中(从B2开始),则可以使用类似以下内容:

Option Explicit
Option Compare Text

Function essay(ft As Range) As Long
  essay = Evaluate("=SUMPRODUCT((" & ft.Address & "=""store transfer"")*OFFSET(" & ft.Address & ",0,1)*OFFSET(" & ft.Address & ",0,3))")
End Function

用于循环:

Function essay2(ft As Range) As Long
    Dim c As Range
    Dim L As Long

For Each c In ft
    If c = "store transfer" Then _
        L = L + c.Offset(0, 1) * c.Offset(0, 3)
Next c

    essay2 = L

End Function

请注意,Option Compare Text语句使例程不区分大小写。

答案 1 :(得分:0)

Hi Guys I managed to solve the problem with your help ,please find the solution below. 


    Option Explicit

    Function ecco(ft As Range) As Long
    Dim x As Variant
    Dim L As Long



    For Each x In ft
    If ft = "st" Then
    L = x.Offset(0, 1) * x.Offset(0, 3)

    Else
    ecco = 0
    End If

    ecco = L

    Next x

    End Function