是否可以让此宏更改Instr值所在的同一行中的值?

时间:2017-06-29 11:48:09

标签: excel vba excel-vba

我创建了一个在我的工作表中查找部分字符串的宏。如果找到该字符串,则会在不同的冒号中将值更改为0.

Sub Contain_Copy()
    Dim ranger                              As Long
    Dim lastrow                             As Long
    Dim FromSheet As Worksheet, ToSheet     As Worksheet
    Dim a                                   As Long

    Set FromSheet = Sheets("C")
    Set ToSheet = Sheets("D")
    lastrow = FromSheet.Cells(Rows.Count, "N").End(xlUp).Row

    For ranger = 2 To lastrow
        If InStr(1, FromSheet.Cells(ranger, "N"), "ET7", vbTextCompare) > 0 Then
            a = a + 1
            Worksheets("C").Cells(a, 3) = 0
        End If
    Next ranger
End Sub

在这个例子中,我的工作表“E3A02ET7”中的字符串位于“N”列和第9行。 由于它包含“ET7”,因此列“C”中的值将更改为0.

问题在于它会更改第1行中的值。

我希望它更改第9行中的值,因为这是与部分字符串ET7的值相同的行。

你能帮我找到解决方法吗?

很有必要,
B. van Starkenburg

2 个答案:

答案 0 :(得分:0)

您只需将FromSheet.Cells(a, 3) = 0更改为FromSheet.Cells(ranger, 3) = 0

即可

所以你的代码变成了:

Sub Contain_Copy()
    Dim ranger                              As Long
    Dim lastrow                             As Long
    Dim FromSheet As Worksheet, ToSheet     As Worksheet

    Set FromSheet = Sheets("C")
    lastrow = FromSheet.Cells(Rows.Count, "N").End(xlUp).Row

    For ranger = 2 To lastrow
        If InStr(1, FromSheet.Cells(ranger, "N"), "ET7", vbTextCompare) > 0 Then
            FromSheet.Cells(ranger, 3) = 0
        End If
    Next ranger
End Sub

答案 1 :(得分:0)

代码就是这样。

Sub Contain_Copy()
Dim ranger                              As Long
Dim lastrow                             As Long
Dim FromSheet As Worksheet, ToSheet     As Worksheet
Dim a                                   As Long

Set FromSheet = Sheets("C")
Set ToSheet = Sheets("D")
lastrow = FromSheet.Cells(Rows.Count, "N").End(xlUp).Row
With FromSheet
    For ranger = 2 To lastrow
        If InStr(.Cells(ranger, "N"), "ET7") Then
            .Cells(ranger, 3) = 0
        End If
    Next ranger
End With
End Sub