2017-07-04 142 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