VBA将结果IF语句放在一个单元格中作为清单

时间:2019-03-06 12:29:01

标签: vba class if-statement range

我想我的问题很简单,但我无法弄清楚。 翻译:Ja =是/ Nee =否

因此,如果单元格A2说“ Nee”,那么J2中应该有一个句子,否则就什么也不做。 每行的其他所有单元格都一样。

我运行我的代码,它执行if语句。但是它只需要合并到一个单元格中即可。

带有示例显示方式的Excel屏幕快照如下:

Excel screenshot with example how it should be

代码:

Sub SampleMacro()
' Get the last row
Dim startRow As Long, lastRow As Long
startRow = 2
lastRow = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Row

Dim i As Long, Wat As String
Dim j As Long, Waarom As String

Dim sClass As String
Dim tClass As String

' Go through the parameter columns
For i = startRow To lastRow
    Wat = Sheet1.Range("A" & i).Value

    ' Check parameters and classify accordingly
    If Wat = "Nee" Then
        sClass = " Er wordt in de cookie policy niet uitgelegd wat cookies zijn."
    Else
        sClass = ""
    End If

For j = startRow To lastRow
    Waarom = Sheet1.Range("B" & j).Value

    If Waarom = "Nee" Then
        tClass = "  Waarom ze nuttig zijn is hier niet omschreven."
    Else
        tClass = ""
    End If

     ' Write out the class to columns
    Sheet1.Range("J" & i).Value = sClass
    Sheet1.Range("K" & j).Value = tClass

Next

Next

End Sub

2 个答案:

答案 0 :(得分:0)

您的代码可以简化为:

For i = startRow To lastRow
    ' Check parameters and classify accordingly
    If Sheet1.Range("A" & i).Value = "Nee" Then
        Sheet1.Range("J" & i).Value = " Er wordt in de cookie policy niet uitgelegd wat cookies zijn."
    End If
    ' If there's Nee in B column, then append next sentence with new line (Chr(10))
    If Sheet1.Range("B" & i).Value = "Nee" Then
        Sheet1.Range("J" & i).Value = Sheet1.Range("J" & i).Value & Chr(10) & "  Waarom ze nuttig zijn is hier niet omschreven."
    End If
Next

答案 1 :(得分:0)

您可以尝试将此公式放在J列中,这样可以避免使用宏

=IF(A2="Nee",IF(B2="Nee"," Er wordt in de cookie policy niet uitgelegd wat cookies zijn." &CHAR(10)& "  Waarom ze nuttig zijn is hier niet omschreven."," Er wordt in de cookie policy niet uitgelegd wat cookies zijn."),"")