使用vba比较多个单元格中的文本

时间:2017-11-20 07:58:59

标签: excel vba excel-vba

假设我想将这五个这些单元格进行比较(其中" line"是一个整数),如果它们都具有这些确切的单词"不适用"在他们中,我希望输出中的单元格也是"不适用"我尝试用.Value替换.Text,但它也没有用。总是出现运行时错误" 13"

Private Sub CommandButton1_Click()
Dim DocNo As Integer
Dim line As Integer

DocNo = (InputBox("Please input document number of record you would like to view"))
line = 1

'Checks the first cell of the results sheet until the number in first cell = the DocNo
'if "DocNo" = the number in the cell, Line is set to its respective y coordinate

Do
    line = line + 1
Loop While (DocNo <> Worksheets("Results").Cells(line, 1))
If (Worksheets("Results").Cells(line, 5).Text) And 
   (Worksheets("Results").Cells(line, 57).Text) And 
   (Worksheets("Results").Cells(line, 59).Text) And 
   (Worksheets("Results").Cells(line, 32).Text) And 
   (Worksheets("Results").Cells(line, 40).Text)  = "Not Applicable" Then
   Worksheets("Output").Cells(26, 3) = "Not Applicable"
End If

End Sub

如果这是一些愚蠢的错误,请原谅我,我已经开始使用VBA几天

3 个答案:

答案 0 :(得分:0)

一点点格式化很长一段路。确保使用适当的代码缩进,如下所示。

以下是您的代码存在的两个主要问题:

  • 你有一行“DocNo”不是评论的一部分,因此不是有效的代码。
  • 你正在为你的If块弄乱End If

此代码更正了这些问题:

Private Sub CommandButton1_Click()
    Dim DocNo As Integer, line As Integer

    DocNo = InputBox("Please input document number of record you would like to view")

    line = 1

    ' Checks the first cell of the results sheet until the number in first cell = the DocNo
    ' if "DocNo" = the number in the cell, Line is set to its respective y coordinate
     Do
        line = line + 1
    Loop While (DocNo <> Worksheets("Results").Cells(line, 1))

    If (Worksheets("Results").Cells(line, 5).Text) And _
        (Worksheets("Results").Cells(line, 57).Text) And _
        (Worksheets("Results").Cells(line, 59).Text) And _
        (Worksheets("Results").Cells(line, 32).Text) And _
        (Worksheets("Results").Cells(line, 40).Text)  = "Not Applicable" Then
        Worksheets("Output").Cells(26, 3) = "Not Applicable"
    End If
End Sub

答案 1 :(得分:0)

尝试以下方法:

 If ((Worksheets("Results").Cells(line, 5).Text)  = "Not Applicable") And 
 (Worksheets("Results").Cells(line, 57).Text)   = "Not Applicable") And 
 (Worksheets("Results").Cells(line, 59).Text)   = "Not Applicable") And 
 (Worksheets("Results").Cells(line, 32).Text)   = "Not Applicable") And 
 (Worksheets("Results").Cells(line, 40).Text)  = "Not Applicable") Then
    Worksheets("Output").Cells(26, 3) = "Not Applicable"
End If

答案 2 :(得分:0)

不幸的是,你必须以不同的方式写它。

说,你有5个单元格的文本,A1,B1,C1,D1和E1简化,你可以做到

IF Range("A1").Value = "Not Applicable" And Range("B1").Value = "Not Applicable" ...

如果我没记错的话,Excel有一个完全相同的本机工作表函数 - 精确(范围,文本)