编写程序以查找单元格,将其复制到上面的行,将其粘贴到当前行中,然后替换

时间:2019-02-12 03:05:22

标签: excel vba

我对VBA非常陌生(今天第一次使用它),我正在尝试编写程序。

我有一个数据集,我希望它在C列中查找某个字母(b),当找到该字母时,将其复制到上面的行,并将其粘贴到找到该字母的行中,然后将C列中的单元格改回原始字母(b)。

到目前为止,我在阅读各种教程时所获得的知识,但是我找不到任何可以将上面的整行复制并粘贴的内容。

Sub TestProgram()

Dim det As String, Result As String

det = Range(C1, C214511).Value

If det = b Then

Replace(

我不确定使用replace函数的用途,因为我不知道如何使它替换上面的行。也许我需要其他功能吗?

或者我可能完全迷路了!

谢谢!

1 个答案:

答案 0 :(得分:1)

您有了一个好的开始。这应该可以解决问题(经过测试)。正如您提到的,您是VBA的新手,我已对代码进行了注释,以显示每一行的情况。

Sub testProgram()

Dim lastRow As Long     ' This will be our last active row
Dim lastCol As Long     ' This will be our last active column
Dim ws As Worksheet     ' This will be our worksheet
Dim r As Long           ' This will be used to represent the row number when looping

' Set our worksheet
Set ws = ThisWorkbook.Worksheets(1)     ' Change to whichever sheet number/name you're working on

' Define the last row and last column on the working sheet
lastRow = ws.Range("A" & Rows.Count).End(xlUp).Row          ' Change "A" to whichever column you like
lastCol = ws.Cells(1, Columns.Count).End(xlToLeft).Column   ' Change "1" to whichever row you like

' Loop through rows starting at the top
For r = 1 To lastRow Step 1
    ' Check if column C contains the value 'b'
    If ws.Range("C" & r).Value = "b" Then
        ' Grab the row above and copy it to the active row
        ws.Range(Cells(r - 1, 1), Cells(r - 1, lastCol)).Copy Destination:=ws.Range(Cells(r, 1), Cells(r, lastCol))
        ' Reset col C of active row to value 'b'
        ws.Range("C" & r).Value = "b"
    End If
Next r

End Sub