在VBA中使用"如果包含单元格"excel

Moo*_*gle 4 excel vba excel-vba

我正在尝试编写一个宏,如果有一个单词"TOTAL",那么它将在它下面的单元格中输入一个破折号.例如:

在此输入图像描述

在上面的例子中,我想在单元格F7中使用短划线(注意:可能有任意数量的列,因此它始终是第7行但不总是第F列).

我目前正在使用此代码,但它不起作用,我无法弄清楚原因.

Dim celltxt As String
Range("C6").Select
Selection.End(xlToRight).Select
celltxt = Selection.Text
If InStr(1, celltext, "TOTAL") > 0 Then
Range("C7").Select
Selection.End(xlToRight).Select
Selection.Value = "-"
End If
Run Code Online (Sandbox Code Playgroud)

帮助将不胜感激.希望我没有做一些愚蠢的事情.

Chr*_*007 14

这将遍历您定义的给定范围内的所有单元格,("RANGE TO SEARCH")并使用该Offset()方法在下面的单元格中添加短划线.作为VBA的最佳实践,您永远不应该使用该Select方法.

Sub AddDashes()

Dim SrchRng As Range, cel As Range

Set SrchRng = Range("RANGE TO SEARCH")

For Each cel In SrchRng
    If InStr(1, cel.Value, "TOTAL") > 0 Then
        cel.Offset(1, 0).Value = "-"
    End If
Next cel

End Sub
Run Code Online (Sandbox Code Playgroud)