簡體   English   中英

根據第一張工作表中列的非空單元格,將特定的行范圍復制到另一張工作表的特定范圍

[英]Copy specific row range to another sheet's specific range based on non empty cells of a column in first sheet

嗨,這是我的第一篇文章,對於給您帶來的任何不便,請原諒,而且我對VBA代碼也不滿意。 我有工作表“ alvin”,如果列Q中有一個值,我想從其中獲取某個行范圍,然后將其粘貼到另一個名為“訂單模板”的工作表中。 我嘗試了以下代碼,但不是傳輸正確的行,而是根據Q單元格值傳輸行。 例如,如果單元格Q5具有10,則代碼將傳輸第10行而不是第5行...

Sub test_TRANSFER_to_Order_template()

Application.ScreenUpdating = False

Dim ws1 As Worksheet
Set ws1 = Worksheets("ALVIN")
Dim ws2 As Worksheet
Set ws2 = Worksheets("order template")
Dim q As Range
Dim LRow As Long
LRow = ws2.Range("b" & Rows.Count).End(xlUp).Row + 0
Dim m As Long

For Each q In Range("q4", Range("q1500").End(xlUp))
    If Not IsEmpty(q) Then
        LRow = LRow + 1
        ws2.Range("b" & LRow).Value = ws1.Range("l" & q).Value
        ws2.Range("c" & LRow).Value = ws1.Range("m" & q).Value
        ws2.Range("d" & LRow).Value = ws1.Range("n" & q).Value   'part number
        ws2.Range("e" & LRow).Value = ws1.Range("q" & q).Value
        ws2.Range("f" & LRow).Value = ws1.Range("r" & q).Value

        Application.ScreenUpdating = True
    End If
Next

End Sub

由於q定義為Range ,並且您試圖獲取行號,因此需要將其修改為q.Row

例如,

ws2.Range("b" & LRow).Value = ws1.Range("l" & q).Value

應該:

ws2.Range("b" & LRow).Value = ws1.Range("l" & q.Row).Value

其余的等等...


編輯 :以確保您檢查的值正確,最好是使用Worksheets("ALVIN")完全限定范圍。

修改循環

With ws1 ' <-- qualify the range with "ALVIN" worksheet
    For Each q In .Range("Q4", .Range("Q1500").End(xlUp))
        If Not IsEmpty(q) Then
            LRow = LRow + 1
            ws2.Range("b" & LRow).Value = .Range("l" & q.Row).Value
            ws2.Range("c" & LRow).Value = .Range("m" & q.Row).Value
            ws2.Range("d" & LRow).Value = .Range("n" & q.Row).Value   'part number
            ws2.Range("e" & LRow).Value = .Range("q" & q.Row).Value
            ws2.Range("f" & LRow).Value = .Range("r" & q.Row).Value

            Application.ScreenUpdating = True
        End If
    Next q
End With

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM