簡體   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