在VBA excel中使用“If cell contains”

我试图写一个macros,如果有一个单词“TOTAL”,那么它会在它下面的单元格中input一个破折号。 例如:

在这里输入图像描述

在上面的例子中,我想在单元格F7中input一个破折号(注意:可以有任意数量的列,所以它总是第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 

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

这将遍历所定义的给定范围内的所有单元格("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 
 Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) If Not Intersect(Target, Range("C6:ZZ6")) Is Nothing Then If InStr(UCase(Target.Value), "TOTAL") > 0 Then Target.Offset(1, 0) = "-" End If End If End Sub 

这将允许您dynamic添加列,并在包含不区分大小写的“Total”之后的6行之后自动在C行的任何列下方插入一个破折号。 注意:如果您经过ZZ6,您将需要更改代码,但是这应该让您在需要的地方。

这是你想要的?

  If ActiveCell.Value == "Total" Then ActiveCell.offset(1,0).Value = "-" End If 

你可以做这样的事情

  Dim celltxt As String celltxt = ActiveSheet.Range("C6").Text If InStr(1, celltxt, "Total") Then ActiveCell.offset(1,0).Value = "-" End If 

这与你所拥有的相似。