excel:用iftesting条件

我试图检查使用VBA填写我的列和行不同的条件。

这是我迄今为止所尝试的:

For i = 1 To Lastrow For j = 1 To 11 If (IsEmpty(ws1.Range("C12"))) And (IsEmpty(ws1.Range("D12"))) = True Then ws2.Cells(i, j) = ws1.Cells(i, j).Value ElseIf (IsEmpty(ws1.Range("C12")) And (ws1.Cells(i, 8) <= ws1.Cells(12, 4))) = True Then ws2.Cells(i, j) = ws1.Cells(i, j).Value ElseIf (IsEmpty(ws1.Range("D12")) And (ws1.Cells(i, 8) <= ws1.Cells(12, 4))) = True Then ws2.Cells(i, j) = ws1.Cells(i, j).Value ElseIf (ws1.Cells(12, 3) >= ws1.Cells(i, 7) And ws1.Cells(12, 3) <= ws1.Cells(i, 8)) Or (ws1.Cells(12, 4) >= ws1.Cells(i, 7) And ws1.Cells(12, 4) <= ws1.Cells(i, 8)) Or ((ws1.Cells(12, 3) >= ws1.Cells(i, 7)) And (ws1.Cells(12, 4) <= ws1.Cells(i, 8))) Then ws2.Cells(i, j) = ws1.Cells(i, j).Value End If Next j Next i 

正如你所看到的,我testing了很多条件。

问题在于单元格C12或D12为空的语句。 如果D12是空的,则代码应该给我所有从C12开始的date。

例如,我想要从15/05/2017开始的一切:

在这里输入图像说明

这就是我得到的结果:

在这里输入图像说明

正如你所看到的,这是不正确的。 我单独testing了一切,它的工作原理,但是当我把所有东西都收拾起来的时候,就会有一些错误。

另外,如果我的If/ElseIf语句正在testing所有的条件,或者如果我以正确的方式写入,我真的怀疑。 有没有另一种方法来按照我想要的顺序运行它?

没有validation你的IF,但是Select语句会更清晰:

 For i = 1 To lastrow For j = 1 To 11 Select Case True Case IsEmpty(ws1.Range("C12")) And IsEmpty(ws1.Range("D12")): ws2.Cells(i, j) = ws1.Cells(i, j).Value Case IsEmpty(ws1.Range("C12")) And ws1.Cells(i, 8) <= ws1.Cells(12, 4): ws2.Cells(i, j) = ws1.Cells(i, j).Value Case IsEmpty(ws1.Range("D12")) And ws1.Cells(i, 8) <= ws1.Cells(12, 4): ws2.Cells(i, j) = ws1.Cells(i, j).Value Case (ws1.Cells(12, 3) >= ws1.Cells(i, 7) And ws1.Cells(12, 3) <= ws1.Cells(i, 8)) Or _ (ws1.Cells(12, 4) >= ws1.Cells(i, 7) And ws1.Cells(12, 4) <= ws1.Cells(i, 8)) Or _ (ws1.Cells(12, 3) >= ws1.Cells(i, 7) And (ws1.Cells(12, 4) <= ws1.Cells(i, 8))): ws2.Cells(i, j) = ws1.Cells(i, j).Value Case Else: ws2.Cells(i, j) = "No match" End Select Next j Next i