繁体   English   中英

Excel 将数据从 1 个工作表复制剪切粘贴到另一个工作表中,状态在工作表 2 新列中更新

[英]Excel copy cut paste data from 1 sheet to another with a status in updated in sheet 2 new column

我是宏的新手我创建了一个宏,该宏从 Excel sheet1 列 A 和 B 复制数据并将其粘贴到工作表 2 中,状态为 c 列中的更新。 但是,它无法正常工作,它以不正确/不完整的方式执行,例如对于第 2 列 B 中的某些值,它在列 c 中显示更新,但对于某些情况,它没有......请帮助我下面是我的代码。 其次,我首先编码了从 sheet1 到 sheet2 的复制粘贴数据,我指定了范围 A2:A9999 和 B2:B9999 我无法简化它。 我的意思是它应该占用整个 A 列和 B 列而不是指定范围。 请帮我处理这两个部分......................

下面是输出,如果您看到单元格 C2 和 C3 为空白,它也应该填充一条注释更新,这不会发生在我的代码中

Sub CopyData()

Dim i As Long
Dim wt As Excel.Worksheet

Set wr = Worksheets("Sheet2")

'Copies and cuts the data from sheet1(TIS) and paste the same in sheet2

With Worksheets("SampleFile")
    .Range("A2:A9999").Copy wr.Range("A2") 'Copy
    .Range("A2:A9999").Cut wr.Range("A2") 'Cut
    .Range("B2:B9999").Copy wr.Range("B2") 'Copy
    .Range("B2:B9999").Cut wr.Range("B2") 'Cut
End With


For i = 1 To wr.Cells(wr.Rows.Count, "B").End(xlUp).Row
If wr.Range("B" & i).Value = "FXV" Then
   wr.Range("C" & i).Value = "Updated"
   ElseIf wr.Range("B" & i).Value = "FST" Then
   wr.Range("C" & i).Value = "Updated"
   ElseIf wr.Range("B" & i).Value = "FLB" Then
   wr.Range("C" & i).Value = "Updated"
   ElseIf wr.Range("B" & i).Value = "FFH" Then
   wr.Range("C" & i).Value = "Updated"
   ElseIf wr.Range("B" & i).Value = "FFJ" Then
   wr.Range("C" & i).Value = "Updated"
   
   End If
Next i
End Sub

此代码应将工作表SampleFile数据从 A2 剪切到 B 和LastRow并将其粘贴到工作表Sheet2范围 A2 。 然后它将遍历Sheet2所有行以查找 B 列中的值,如果匹配,则Select Cases将在 C 列中输入Updated

Option Explicit
Sub CopyData()

    Dim wr As Worksheet: Set wr = Worksheets("Sheet2")
    'Copies and cuts the data from sheet1(TIS) and paste the same in sheet2
    'there is no need to copy if you are going to cut
    'also use a defined range to copy instead 9999 rows
    With ThisWorkbook.Worksheets("SampleFile")
        Dim LastRow As Long: LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
        'you can also cut both columns at once
        .Range("A2:B" & LastRow).Cut wr.Range("A2") 'Cut
    End With
    
    Dim i As Long
    With wr
        For i = 1 To .Cells(.Rows.Count, "B").End(xlUp).Row
        'in this case is way shorter to code using the Select statement
        'you could also use If x = y or x = z or x = a but Select looks cleaner.
            .Cells(i, "B") = Trim(.Cells(i, "B"))
            Select Case .Range("B" & i)
                Case "FXV", "FST", "FLB", "FFH", "FFJ"
                    .Range("C" & i) = "Updated"
            End Select
        Next i
    End With
    
End Sub

暂无
暂无

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

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