excel:if

时间:2017-06-20 16:12:11

标签: excel vba excel-vba

我尝试使用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

正如您所看到的,我测试了很多条件。

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

例如,我想要从2017年5月15日开始的一切:

enter image description here

这就是我得到的结果:

enter image description here

如您所见,它不正确。 我分别测试了所有内容并且它可以正常工作,但是当我把所有东西都放到一边时它就会出现一些错误。

此外,如果我的If/ElseIf语句按顺序测试所有条件或者我以正确的方式编写,我真的有疑问。 是否有其他方式按我想要的顺序运行它?

1 个答案:

答案 0 :(得分:2)

尚未验证您的IF,但选择语句会更清晰:

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