简体   繁体   English

如果单元格包含某些文本,则复制文本的一部分并移至新表

[英]if cell contains certain text copy part of text and move to new sheet

Im trying to use VBA in order to detect cells which contain the word HELLO and then: 我试图使用VBA来检测包含单词HELLO的单元格,然后:

take the 7th to 10th characters and copy those to a new sheet on the first available row 取第7至第10个字符,并将其复制到第一行上的新表中

then copy the 12th to last character to a second column on the new sheet. 然后将第12个倒数第二个字符复制到新工作表的第二列。

Repeat for all cells containing the phrase. 对所有包含该短语的单元格重复此操作。

Right now I can't get the code to copy the first cell that contain the phrase. 现在,我无法获取代码来复制包含该短语的第一个单元格。

This is the current code: 这是当前代码:

Sub test()
Dim LR As Long, i As Long
With Sheets("Sheet1")
LR = .Range("A" & Rows.Count).End(xlUp).Row
For i = 1 To LR
    If .Range("A" & i) Like "*HELLO*" Then
    .Copy Mid(Range("A" & i), 2, 2)

Next i
End Sub

Instead of copying, it would be better just to assign the partial string value into the next cell in the second sheet. 代替复制,最好将部分字符串值分配给第二张工作表的下一个单元格。 I also added UCASE to your if statement in case the HELLO isn't capitalized. 我还将UCASE添加到您的if语句中,以防HELLO不大写。 Then added an If to check if the string was 12 characters long atleast before returning the 12th to last character. 然后添加一个If,以检查字符串是否至少为12个字符长,然后再返回第12个字符到最后一个字符。

Sub test()
Dim LR As Long, i2 As Long


LR = Sheets(1).Range("A" & Rows.Count).End(xlUp).Row
i2 = 1

For i = 1 To LR
    If UCase(Sheets(1).Range("A" & i).Value) Like "*HELLO*" Then
        Sheets(2).Range("A" & i2).Value = Mid(Sheets(1).Range("A" & i).Value, 7, 3)
        If Len(Sheets(1).Range("A" & i).Value) > 11 Then
            Sheets(2).Range("B" & i2).Value = Mid(Sheets(1).Range("A" & i).Value,13, Len(Sheets(1).Range("A" & i).Value) - 12)
        End If
        i2 = i2 + 1
    End If
Next i

End Sub

You probably can't copy it, you may have yo just place it in another cell location something like 您可能无法复制它,您可能只是将其放置在另一个单元格中,例如

Sub Button1_Click()

    Dim LR As Long, i As Long
    With Sheets("Sheet1")
        LR = .Range("A" & Rows.Count).End(xlUp).Row
        For i = 1 To LR
            If .Range("A" & i) Like "*HELLO*" Then
                Cells(Rows.Count, "C").End(xlUp).Offset(1, 0) = Mid(Range("A" & i), 2, 2)
            End If
        Next i
    End With
End Sub

Edit: Ah, somebody else had the same idea. 编辑:啊,其他人也有同样的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM