Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel VBA逻辑不工作_Vba_Excel_Ms Office - Fatal编程技术网

Excel VBA逻辑不工作

Excel VBA逻辑不工作,vba,excel,ms-office,Vba,Excel,Ms Office,第一列有两张公司名称的表格,项目价格为第一行。现在,我需要检查公司名称是否匹配,然后检查行并更新值 Sub addition() Dim j As Integer Dim i As Integer Dim a As Integer Dim b As Integer For i = 2 To 15 For j = 2 To 15 If Sheet1.Cells(i, 1) = Sheet1.Cells(j, 1) T

第一列有两张公司名称的表格,项目价格为第一行。现在,我需要检查公司名称是否匹配,然后检查行并更新值

Sub addition()
    Dim j As Integer
    Dim i As Integer
    Dim a As Integer
    Dim b As Integer

    For i = 2 To 15
        For j = 2 To 15
            If Sheet1.Cells(i, 1) = Sheet1.Cells(j, 1) Then
                For a = 2 To 5
                    For b = 2 To 5
                        If Sheet1.Cells(1, a) = Sheet2.Cells(1, b) Then
                                Sheet1.Cells(i, a) = Sheet2.Cells(j, b) + Sheet1.Cells(i, a)

                        End If
                     Next b
                Next a

            End If
        Next j
    Next i

End Sub
但在某些行中,逻辑起作用,而在其他行中则不起作用

For i = 2 To 15
    For j = 2 To 15
        If Sheet1.Cells(i, 1) = Sheet1.Cells(j, 1) Then
            ...
上面的代码将找到14个匹配项,因为i和j是相同值的14倍,并且它们都引用同一工作表的同一列

由于您在代码后面使用j来指代Sheet2上的一行,因此上述内容很可能更接近于此

For i = 2 To 15
    For j = 2 To 15
        If Sheet1.Cells(i, 1) = Sheet2.Cells(j, 1) Then
            ...
然而,即使切换到Sheet2.Cells(j,1)修复了逻辑,为其他任何事情做任何事情都是非常低效的。对于在找到匹配项后不继续查找匹配项的语句,可以使用Exit减少循环。此外,一个匹配和完成是对列值的匹配,它完全否定了内部循环

Sub addition()
    Dim i As long, a As long
    Dim j As variant, b as variant

    For i = 2 To 15
        i = application.match(Sheet1.Cells(i, 1), Sheet2.Cells(2, 1).resize(14, 1), 0)
        if not iserror(i) then
            For a = 2 To 5
                b = application.match(Sheet1.Cells(1, a), Sheet2.Cells(1, 2).resize(1, 4), 0)
                if not iserror(b) then
                    Sheet1.Cells(i, a) = Sheet2.Cells(j, b) + Sheet1.Cells(i, a)
                End If
            Next a
        End If
    Next i

End Sub

如果Sheet1.单元格(i,1)=Sheet1.单元格(j,1),那么
其中一个单元格应该是Sheet2吗?可能是
Sheet2.Cells(j,1)
…?您的逻辑不起作用?以什么方式?请努力实际解释这个问题。一些样本数据可能也会有帮助。谢谢@Jeeped it worked请阅读-总结是,这不是解决志愿者问题的理想方式,可能会对获得答案产生反作用。请不要将此添加到您的问题中。