【问题标题】:VBA - multiple conditions for each cellVBA - 每个单元格的多个条件
【发布时间】:2017-06-19 14:07:49
【问题描述】:

我正在尝试解决无法运行的代码问题:

'========================================================================
' CHECKS IF MARKET SECTOR IS EMPTY (FOR LEDGER)
'========================================================================

Private Sub Fill_MarketSector()

Dim LastRow As Long
Dim rng As Range, C As Range

With Worksheets("Ready to upload") ' <-- here should be the Sheet's name
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' last row in column A
    Set rng = .Range("A2:A" & LastRow) ' set the dynamic range to be searched
    Set rng2 = .Range("F2:F" & LastRow)

    ' loop through all cells in column A and column F
    For Each C In rng and For Each C in rng2
        If rng.C.Value = "Ledger" and rng2.C.value IsEmpty Then
            C.Value = "599" ' use offset to put the formula on column "L"
        End If
    Next C
End With

End Sub

代码应该检查A列是否包含单词“Ledger”并且F列是否为空,然后它应该放入F列“599”。它应该始终检查到最后一行。你能帮帮我吗?

非常感谢!

【问题讨论】:

  • re: '*'应该放入F列“599”'* - F列还是L列?您的叙述与代码中的注释冲突。
  • 您遇到什么错误?提供有关您陷入困境的信息。
  • 你说得对,我在 cmets 和 code 之间存在差异。它应该将“599”放入 F 列。我收到语法错误,这部分代码已突出显示:For Each C In rng and For Each C in rng2 If rng.C.Value = "Ledger" and rng2.C .value IsEmpty Then

标签: excel vba if-statement multiple-conditions


【解决方案1】:

您可以访问 F 列中的相应单元格,方法是遍历 A 列中的单元格,然后对 F 列使用 .Offset,然后再次偏移以将值放入 L 列。

' loop through all cells in column A and column F
For Each C In rng
    If LCase(C.Value) = "ledger" and IsEmpty(C.Offset(0, 5) Then
        C.Offset(0, 11) = 599  'use offset to put the number on column "L"
    End If
Next C

【讨论】:

  • 谢谢你!它工作顺利。 IsEmpty(C.Offset(0, 5)) 后面只是缺少分隔符。非常感谢!
  • 不幸的是,它只在某些时候有效,在大多数情况下,它什么也没做。请问您知道为什么吗?
  • '它只在某些时候有效' - 这既不是有效的错误代码,也不是错误的有效描述。这也不是 - '在大多数情况下,它什么都不做'。阅读minimal reproducible example后提供样本数据。
猜你喜欢
  • 2021-03-15
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-05
  • 1970-01-01
  • 1970-01-01
  • 2017-11-03
相关资源
最近更新 更多