宏在行中查找特定文本并复制到同一行中的单元格

时间:2017-02-17 20:09:31

标签: excel vba excel-vba

我有一本工作簿,我想要做的就是找到"假期"在B和G之间的行中放置"假日"在A列同一行的单元格中,我附上了一张纸张,我需要忽略包含" Rest"只是把假期"在包含"是"

的单元格中

Holiday Planner

Sub dural()
    Dim AB As Range, r As Range, K As Long
     Set AB = Range("B:G").Cells.SpecialCells(xlCellTypeConstants)
    K = 1
        For Each r In AB
        If InStr(1, r.Value, "holiday") > 0 Then
        r.Copy Cells(K, "A")
        K = K + 1
    End If
    Next
End Sub

我在网站的其他地方找到了这个代码,但它的作用是放置"假期"在第1行的第A列中,按照它找到的次数"假日"

任何人都可以帮助我吗?

5 个答案:

答案 0 :(得分:3)

您还可以创建 For循环来执行此任务:

Sub Holiday()

lastrow = Cells(Rows.Count, "A").End(xlUp).Row

    For i = 2 To lastrow
        If Cells(i, 1).Value = "Yes" Then
            If Application.WorksheetFunction.CountIf("B" & i & ":G" & i, "holiday") > 0 Then
                    Cells(i, 1).Value = "holiday"
            End If
        End If
    Next i

End Sub

由于您还在示例中包含了颜色编码,因此我添加了一行也将您的单元格颜色更改为绿色。

答案 1 :(得分:2)

我不确定,但我相信你正在寻找这样的事情:

Sub dural()

Dim AB As Range, r As Range
Set AB = Range("B:G").Cells.SpecialCells(xlCellTypeConstants)

For Each r In AB
    If InStr(1, LCase(r.Value), "holiday") > 0 And _
        LCase(Cells(r.Row, "A").Value) = "yes" Then
            r.Copy Destination:=Cells(r.Row, "A")
    End If
Next r

End Sub

答案 2 :(得分:1)

假设列H为空:

[H2:H37] = "=IF(AND(A2=""Yes"",COUNTIF(B2:G2,""holiday"")),""holiday"",A2)"
[A2:A37] = [H2:H37].Value2
[H2:H37] = ""

答案 3 :(得分:1)

你并不完全没有解决方案,但无论如何都要进行。这使用了查找

Sub x()

Dim rFind As Range, s As String

With Range("B2", Range("G" & Rows.Count).End(xlUp))
    Set rFind = .Find(What:="holiday", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
    If Not rFind Is Nothing Then
        s = rFind.Address
        Do
            If Cells(rFind.Row, 1).Value = "Yes" Then
                Cells(rFind.Row, 1).Value = "holiday"
            End If
            Set rFind = .FindNext(rFind)
        Loop While rFind.Address <> s
    End If
End With

End Sub

答案 4 :(得分:0)

<img src="image.jpg" alt="Avatar" class="w3-center w3-round w3-border" style="height: 150px; width: 150px; display: block; visibility: visible; border: none; margin: 0px; padding: 0px; position: absolute; top: 0px; left: 0px; opacity: 1;">

根据需要更改参数...我建议使用特定范围而不是全局范围... B1:G10代替B:G用于性能目的