我有大量的数据表,并且想要将包含"HVT"
的所有行复制并粘贴到另一表中。我是VBA的新手,我认为我搜索的代码将搜索整个单元格而不是单元格的内容。例如,如果单元格只说"HVT"
可以,但是单元格中有多个字符串。一个可能存在于单元格中的示例例如为"mechanical system damper HVT purchased"
Private Sub CommandButton1_Click()
a = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To a
If Worksheets("Sheet1").Cells(i, 11).Value = "HVT" Then
Worksheets("Sheet1").Rows(i).Copy
Worksheets("Sheet2").Activate
b = Worksheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("Sheet2").Cells(b + 1, 1).Select
ActiveSheet.Paste
Worksheets("Sheet1").Activate
End If
Next
Application.CutCopyMode = False
ThisWorkbook.Worksheets("Sheet1").Cells(1, 1).Select
End Sub
答案 0 :(得分:1)
Excel if语句接受通配符,因此您只需要知道是否要匹配整个单词“ HVT”:
匹配整个单词:
If Worksheets("Sheet1").Cells(i, 11).Value Like "* HVT *" Or Worksheets("Sheet1").Cells(i, 11).Value Like "HVT *" Or Worksheets("Sheet1").Cells(i, 11).Value Like "* HVT" Then
或匹配任何HVT实例(“ xHVTx”返回true
):
If Worksheets("Sheet1").Cells(i, 11).Value Like "*HVT*" Then
会工作
答案 1 :(得分:0)
以下代码已更新:
Sub transferHVT()
Dim mySH As Worksheet
Set mySH = ThisWorkbook.Sheets("Sheet1")
Dim sSH As Worksheet
Set sSH = ThisWorkbook.Sheets("Sheet2")
Application.ScreenUpdating = False
Dim sh2_Row As Integer
sh2_Row = 1
For a = 2 To mySH.Cells(Rows.Count, 11).End(xlUp).Row
If InStr(mySH.Cells(a, 11).Value, "HVT") <> 0 Then
'Loop through all the column
For b = 1 To mySH.Cells(a, Columns.Count).End(xlToLeft).Column
sSH.Cells(sh2_Row, b).Value = mySH.Cells(a, b).Value
Next b
sh2_Row = sh2_Row + 1
End If
Next a
Application.ScreenUpdating = True
End Sub