我正在使用instr函数来查找 vba 范围内的值,当我查找"ra01"
的字符串时,它正在找到它并且工作正常,但它不是我的意思是 sheet1 ,范围C
row2 ( 2_x_ra01_ff string),
row3 ( ff_x_xxxx_ff), row4 (xxxxxxx),
row5 (fffffff) row6 ( 1_f_ra01_xx)
row7 (dfdfdfd) row8(f_x_ra01_xx)
这些是字符串,因此当我尝试将查找值粘贴到 sheet2 时,它正在复制并粘贴完美但不是正确增加,而是我的 sheet2 看起来像这样row2( 2_x_ra01_ff string)
然后row3 empty row4 empty row5 empty row6( 1_f_ra01_xx)
等等。那么为什么不在row3
或row4
或row5
中粘贴它,为什么它会从 sheet1 中选择完全相同的行。这是我的代码,如果你运行它,你将更好地理解。
Sub find()
Dim x As String, i As Long, lastrow As Long, y As Long
x = "ra01"
y = 2
lastrow = Sheets("Sheet1").UsedRange.Rows.Count + 1
For i = 2 To lastrow
If Sheets("Sheet1").Cells.InStr(i, 6).Value = x Then
Sheets("Sheet2").Range("A" & y) = Sheets("Sheet1").Cells(i, 1)
y = y + 1
End If
Next i
End Sub
答案 0 :(得分:0)
你可以试试这个:
Sub find()
Dim x As String, i As Long, lastrow As Long, y As Long
Dim sh1 As Worksheet, sh2 As Worksheet
Set sh1 = Sheets("Sheet1"): Set sh2 = Sheets("Sheet2")
x = "ra01"
With sh1
lastrow = .Range("F" & .Rows.Count).End(xlUp).Row
For i = 2 To lastrow
If InStr(.Range("F" & i).Value, x) <> 0 Then
.Range("A" & i).Copy _
sh2.Range("A" & sh2.Rows.Count).End(xlUp).Offset(1, 0)
End If
Next i
End With
End Sub
HTH。