【问题标题】:VBA excel, if Cells(counter,1)="text" thenVBA excel,如果 Cells(counter,1)="text" 那么
【发布时间】:2017-12-16 12:32:27
【问题描述】:

我正在尝试执行一个 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

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

谢谢,孢子

编辑:

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

这是我收到错误消息“应用程序定义或对象定义错误”的地方。

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

【问题讨论】:

  • 代码If Cells(i, 1).value = "text" Then 应该可以工作。但是,您应该发布更多代码,因为不清楚是什么使代码运行。它是手动执行的,还是应该在 Worksheet_Change 等上运行?
  • 好的,所以当我激活工作表时它可以工作,但是当复选框更改为 false 时它不起作用。唯一的区别是我在 IF 语句中有多个语句,如: If Cells(i, 1).value = "text1" or Cells(i, 1).value = "text2" then
  • 尝试发布更多代码。该错误并非源自您发布的If 声明。
  • Private Sub UT_Change() If UT.Value = True Then 'do stuff End If ElseIf UT.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 抱歉,格式似乎不正确
  • 尝试编辑您的原始帖子,而不是将其作为评论发布。您还应该指定 UT.Value 是什么。

标签: vba if-statement text range cells


【解决方案1】:

这个可以用

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

【讨论】:

  • 当我尝试它时,我收到一条错误消息:“应用程序定义或对象定义错误”
【解决方案2】:

这应该可行:

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

【讨论】:

    【解决方案3】:

    您不能使用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
    

    【讨论】:

    • 仍然是同样的问题,它突出显示了 Cells(1, counter).value="text1" 等行并给了我同样的错误信息
    • 问题可能是您的Counter。我尝试在代码中添加对其值的简单检查。但它并不能处理所有场景。
    • 是的,问题是我试图在几个不同的 subs 中调用计数器,但它不是公共整数。感谢您的帮助!
    猜你喜欢
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多