在某些单词之前剪切字符串并粘贴到不同的范围:VBA

时间:2017-07-04 02:50:27

标签: excel-vba vba excel

我需要VBA代码

  • 在A列的每个单元格中切割字符串的一部分,直到单词" HS"
  • 将该部分粘贴到列#34; N"在上一行。

有些字符串在" HS"之前没有任何内容,因此不应为这些字符串运行代码。我正在处理的工作表有数千行。我不确定该怎么做......

1 个答案:

答案 0 :(得分:0)

以下是一些可以实现您想要的注释代码。请注意,您可能会发现this answer对查找最后一行很有用。

此代码避免实际使用剪切和粘贴,因为它是。相反,它直接访问单元格的值。

Sub CopyBeforeHS()
    Dim r As Long, HSindex As Long
    ' There are many ways to find the last row, or just replace 100 manually here
    ' You must start at row 2, as r-1 is used in the loop
    For r = 2 To 100
        ' Your sheet name here...
        With ThisWorkbook.Sheets("Sheet1")
            ' Get location of "HS" in each cell in column A
            HSindex = InStr(.Range("A" & r).Value, "HS")
            ' If HS was found AND it wasn't the first characters
            If HSindex > 1 Then
                ' Copy cell text from before "HS" to previous row, column N
                .Range("N" & r - 1).Value = Left(.Range("A" & r).Value, HSindex - 1)
                ' Remove the same text from column A
                .Range("A" & r).Value = Mid(.Range("A" & r).Value, HSindex)
            End If
        End With
    Next r
End Sub