[英]Copy Cell values from One Sheet to Another on certain criteria with the paste
[英]Copy paste specific cell values from one work sheet to another based on a specific criteria
我已經有一段時間沒有做任何類型的編碼了,所以我很生疏。 我正在嘗試編寫一些 VBA 代碼,以便在 excel 工作表中單擊一個按鈕時,它將檢查同一工作簿中的另一個工作表和特定單元格值的副本。 這是基於其中一列中的標准(我數了第 15 列); 我可能應該補充一點,數據在表格中。 如果該行符合第 15 列的指定條件,則使用按鈕將特定列復制到工作表中。
我確實有一些代碼,但我知道其中缺少很多東西。
不勝感激,我在正確的軌道上嗎? 任何人都可以在那里提供幫助,我可以獲得有關我需要使用的編碼的更多信息和提示。 不確定是否有使用表格的簡單方法?
Private Sub CommandButton1_Click()
''This will count how many rows are populated in the table''
a = Worksheets("Billable").Cells(Rows.Count, 1).End(xlUp).Row
''Loop will run from row 6 to the last row (Row 6 is the first row in table)''
For i = 6 To a
''If statement which will check the status column for Detailed Estimate Submitted > column 15''
If Worksheets("Billable").Cells(i, 15).Value = "Detailed Estimate Submitted" Then
Worksheets("Billable").Rows(i).Copy
Worksheets("PM_Forecast").Activate
b = Worksheets("PM_Forecast").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("PM_Forecast").Cells(a + 1, 1).Select
ActiveSheet.Paste
End If
Next
Application.CutCopyMode = False
End Sub
表格示例: - 如果它們滿足狀態列中的特定條件,我只需要復制超過 3 個列
我無法發表評論,所以我將通過這個答案提出問題:
您的變量 b 當前未使用,我認為它應該在這一行: Worksheets("PM_Forecast").Cells(b + 1, 1).Select
但您寫的是 a 而不是 b。
這是否解決了您當前的問題?
你沒有回答我關於格式粘貼的問題......
因此,請測試以經典方式粘貼的下一個代碼。 但沒有選擇和聲明所有使用的變量:
Private Sub CommandButton1_Click()
Dim shB As Worksheet, shPM As Worksheet, lastRowB As Long, lastRowPM As Long
Dim i As Long, lastCol As Long
Set shB = Worksheets("Billable")
Set shPM = Worksheets("PM_Forecast")
lastRowB = Worksheets("Billable").Cells(Rows.Count, 1).End(xlUp).row
'Loop will run from row 6 to the last row (Row 6 is the first row in table)''
For i = 6 To lastRowB
If shB.Cells(i, 15).Value = "Detailed Estimate Submitted" Then
lastCol = shB.Cells(i, Columns.Count).End(xlToLeft).Column
lastRowPM = shPM.Cells(Rows.Count, 1).End(xlUp).row
shB.Range(shB.Range("A" & i), shB.Cells(i, lastCol)).Copy _
shPM.Cells(lastRowPM + 1, 1)
End If
Next
Application.CutCopyMode = False
End Sub
對於使用變體的數組,您只能聲明一個新變量Dim arr As Variant
並替換此部分:
shB.Range(shB.Range("A" & i), shB.Cells(i, lastCol)).Copy _
shPM.Cells(lastRowPM + 1, 1)
有了這個:
arr = shB.Range(shB.Range("A" & i), shB.Cells(i, lastCol)).Value
shPM.Cells(lastRowPM + 1, 1).Resize(, UBound(arr, 2)).Value = arr
然后,刪除代碼行Application.CutCopyMode = False
。 不再需要,因為不使用剪貼板 memory...
並在模塊頂部使用Option Explicit
。 當代碼變得復雜時,它將為您節省很多次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.