2017-07-04 138 views
-1

我需要VBA代码剪切串并粘贴到一个不同的范围:VBA

  • 切割的字符串的一部分,直到字“HS”,在列A中
  • 的每个小区将该部分粘贴到上一行的列“N”中。

某些字符串在“HS”之前没有任何内容,所以代码不应该为这些字符运行。我正在处理的工作表有成千上万行。我不确定如何做到这一点...

+0

到目前为止您尝试过哪些方法?您卡在哪里?这里的人不会为你编写代码,所以**不是免费的编码服务**。请用您的代码更新您的问题,以便我们帮助您解决特定的问题。另请阅读[我如何问好问题](https://stackoverflow.com/help/how-to-ask)。 –

+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 
+0

该代码完美适合我,非常感谢。 –

+0

@SouzaSauloSaulo然后请将此答案标记为已接受,谢谢 – Wolfie