【问题标题】:Write to next 3 cells based on condition VBA while leaving formulas intact根据条件 VBA 写入下 3 个单元格,同时保持公式不变
【发布时间】:2015-05-17 16:53:44
【问题描述】:

因此,我正在尝试编写一个 vba 宏,如果前一个单元格中包含单词“lunch”,则可以将单词“lunch”写入接下来的 3 个单元格中,午餐通过 if 语句填充到单元格中。我想要一些 vba 代码来读取行中的每个单元格,如果它找到了单词 lunch。接下来的 3 个单元格现在将包含单词 lunch。我想保留单元格中的公式,以便电子表格的功能保持不变。这是我到目前为止所写的。但它没有按预期工作。请帮忙

Public Sub WriteLunchToCell()
Dim rg As Range
For Each rg In Sheet1.Range("BY62:FP62")
    If InStr(1, rg.Value, "Lunch", vbTextCompare) Then
        rg.Offset(, 1) = "Lunch"
        rg.Offset(, 2) = "Lunch"
        rg.Offset(, 3) = "Lunch"


End If
Next

结束子

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    如果您希望保留公式,则需要更改单元格的格式而不是值。

    rg.Offset(, 1).NumberFormat = "General ""LUNCH"""

    【讨论】:

      【解决方案2】:

      试试这样的:

      Set Rng = Range("a1:a6")
      
      For Each cel In Rng
          If InStr(UCase(cel.Value), "LUNCH") <> 0 Then
              cel.Offset(0, 1).Value = "Lunch"
              cel.Offset(0, 2).Value = "Lunch"
              cel.Offset(0, 3).Value = "Lunch"
          End If
      Next cel
      

      【讨论】:

      • 谢谢。到目前为止,我有这个代码工作,但现在我需要它在下一行运行。直到第 300 行左右Public Sub WriteLunchToCell() Dim rg As Range Dim row As Range Dim cell As Range For Each rg In Sheet1.Range("BG62:EX300") If InStr(1, rg.Value, "3", vbTextCompare) Then rg.Offset(, 1) = "3" rg.Offset(, 2) = "3" rg.Offset(, 3) = "3" Exit For End If Next End Sub
      【解决方案3】:

      你可以嵌套另一个循环:

      For i = 1 To 300
          Set MyRange = Sheet1.Range("BY" & 61 + i & ":FP" & 61 + i)
      
          For Each rg In MyRange
      
              If InStr(1, rg.Value, "Lunch", vbTextCompare) Then
                  rg.Offset(, 1) = "Lunch"
                  rg.Offset(, 2) = "Lunch"
                  rg.Offset(, 3) = "Lunch"
      
      
          End If
          Next rg
      
      Next i
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-13
        • 2022-01-14
        • 1970-01-01
        • 1970-01-01
        • 2019-12-21
        • 1970-01-01
        相关资源
        最近更新 更多