使用InStr比较两个字符串但失败

时间:2016-07-06 15:15:26

标签: excel-vba vba excel

我的目标是填写质量控制表。在这张表中,我已经有了所有的测试点,我的工作是查看该点并在另一张表中搜索正确答案,并填写空白单元格。例如:

TV1 | Coulor
TV1 | Size
TV2 | Coulor
TV2 | Size
TV3 | Coulor
TV3 | Size

在另一张表中,我已经有了一份新报告的结果:

TV1 | Coulor : red   | Size : 1
TV2 | Coulor :blue   | Size : 1
TV3 | Coulor : green | Size : yellow

这个例子很简单,在实际报告中我还有更多细节,但一般情况下,它都是一样的。这是我的潜艇:

Private Sub FillTarget(ByVal TargetSheet As String, ByVal DepositSheet As String, _
    ByVal DataRow As Integer, ByVal DataColumn As Integer, _
    ByVal DepositRow As Integer, ByVal DepositColumn As Integer)

Dim i As Integer, j As Integer, k As Integer
Dim OpenedFile As String, myObject As String

Dim MarkRow As Integer
MarkRow = 1
Dim myData As String
Dim EndSearch As Boolean

Dim TargetCell As Range
Dim TargetTag As Range
Dim TargetType As Range
Dim TargetZone As Range
Dim TargetTest As Range

Dim DepositTag As Range
Dim DepositZone As Range
Dim DepositResult As Range

'for every line in the report    
For i = 8 To DataRow
With Worksheets(TargetSheet)
    Set TargetCell = .Cells(i, DataColumn)
    Set TargetTag = .Cells(i, 15)
    Set TargetType = .Cells(i, 17)
    Set TargetZone = .Cells(i, 18)
    Set TargetTest = .Cells(i, 20)
End With
myObject = TargetTag.Text + "_" + TargetType.Text

'search every line in result sheet
For j = MarkRow To DepositRow
    With Worksheets(DepositSheet)
        Set DepositTag = .Cells(j, 1)
        Set DepositZone = .Cells(j, 2)
    End With
    'if the product is right
    If InStr(DepositTag.Value, myObject) <> 0 Then
        OpenedFile = OpenedFile & DepositTag.Text & "|"
        'if the zone is right
        If InStr(DepositZone.Value, TargetZone.Value + ":") <> 0 _  '<===Here's the problem
            Or InStr(TargetZone.Text, "/") <> 0 Then
            'for each cell in this line
            For k = 2 To DepositColumn
                With Worksheets(DepositSheet)
                    Set DepositResult = .Cells(j, k)
                End With
                'find the correct test (colour, siez etc)
                If InStr(DepositResult.Value, TargetTest.Value) <> 0 Then
                    MarkRow = j
                    myData = DepositResult.Text
                    TargetCell.Value = myData
                    EndSearch = True
                    Exit For
                End If

            Next k

        End If

    End If

    If EndSearch Then Exit For
Next j

EndSearch = False
Next i

End Sub

我已经使用了F8来运行,并发现InStr If InStr(DepositTag.Value, myObject) <> 0的第一次比较有效,但是第二次If InStr(DepositZone.Value, TargetZone.Value + ":") <> 0它停止了,即使里面已经有一个字符串,但似乎它无法弄清楚这两个字符串中是否存在相同的部分。

我尝试使用'愚蠢'方式,只是不要使用set和If InStr(Sheets("Brouillon").Cells(j, 2).Text, Sheets("Data").Cells(i, 18).Text) <> 0工作。我没弄清楚问题出在哪里。

所以如果你有一些想法,请留言。谢谢!

0 个答案:

没有答案