VBA excel,如果Cells(counter,1)=“text”则

时间:2017-07-12 07:50:44

标签: vba if-statement text range cells

我正在尝试执行if语句,该语句仅在某个单元格包含特定文本时才会激活。有问题的单元需要根据一个会改变的整数动态改变,到目前为止我已经尝试了多种方法,但似乎没有任何工作。

If Cells(counter, 1).text = "text" then

If Cells(counter, 1).value = "text" then

If Range(Cells(counter, 1)).text = "text then

If Range(Cells(counter, 1)).value = "text then

这似乎是一个简单的程序,有人有解决方案吗?

谢谢,Sporre

编辑:

Private Sub CheckBox_Change() 
If CheckBox.Value = True Then 
   'do stuff 
End If 
ElseIf CheckBox.Value = False Then 
    If Cells(1, counter).Value = "text1" Or Cells(1, counter).Value = 
    "text2" Or Cells(1, counter).Value = "text3" Then
       'do stuff 
    End If 
End If 
End Sub

这是我收到错误消息“Application-definded or Object-defined error”。

编辑2: 问题是我试图在几个不同的潜艇中调用计数器,它不是一个公共整数。谢谢你的帮助!

3 个答案:

答案 0 :(得分:1)

这个会起作用

if (Trim(ThisWorkbook.Worksheets("Sheet1").Cells(counter, 1).Value)="text") Then

答案 1 :(得分:0)

This should work:

If Worksheets("Name of your worksheet").Cells(counter, 1).Value)="text" Then
    'execute some code
End if

答案 2 :(得分:0)

您无法使用End If,然后使用ElseIf进行跟进。第一个完全结束If语句,这意味着你必须开始一个新语句。根据您的编辑,我认为您的代码应该如下所示:

Private Sub CheckBox_Change()
    If CheckBox.Value = True Then
       'do stuff
    ElseIf CheckBox.Value = False Then
        If (Counter < 1) Then
            'Show an error if the counter is less than 1
            MsgBox "Error: Counter less than 1", vbCritical
        ElseIf Cells(1, counter).Value = "text1" Or Cells(1, counter).Value = "text2" Or Cells(1, counter).Value = "text3" Then
           'do stuff
        End If
    End If
End Sub