簡體   English   中英

如何循環動態范圍並將該范圍內的選擇信息復制到另一個工作表

[英]How to loop a dynamic range and copy select information within that range to another sheet

我已經創建了一個大約160行的VBA腳本,該腳本會生成您在下面看到的報告。

不使用單元格引用(因為每次運行此命令時日期范圍都會改變),現在我需要獲取用戶ID,名稱,總小時數,總休息時間,加班1和加班2,並將此數據復制到工作表2中。

關於如何構造VBA腳本以搜索B行直到找到空白的任何建議,當找到空白時,復制該行以及復制值以上行中的J,K,L,M列中的值C-現在將這些值粘貼到工作表2上。-繼續此過程,直到找到兩個連續的空白或數據的結尾...

即使您可以提出一種不同於我上面假設的邏輯的方法來解決此問題,也將不勝感激。 如果您有興趣,我可以共享整個代碼,並向您顯示我開始使用的數據。

預先謝謝你,J

例

如上所述,這是我的方法。 所有詳細信息都在代碼的注釋中,因此請確保您已閱讀它們。

Sub GetUserNameTotals()

    Dim ShTarget As Worksheet: Set ShTarget = ThisWorkbook.Sheets("Sheet1")
    Dim ShPaste As Worksheet: Set ShPaste = ThisWorkbook.Sheets("Sheet2")
    Dim RngTarget As Range: Set RngTarget = ShTarget.UsedRange
    Dim RngTargetVisible As Range, CellRef As Range, ColRef As Range, RngNames As Range
    Dim ColIDIndex As Long: ColIDIndex = Application.Match("ID", RngTarget.Rows(1), 0)
    Dim LRow As Long: LRow = RngTarget.SpecialCells(xlCellTypeLastCell).Row

    'Turn off AutoFilter to avoid errors.
    ShTarget.AutoFilterMode = False

    'Logic: Apply filter on the UserName column, selecting blanks. We then get two essential ranges.
    'RngTargetVisible is the visible range of stats. ColRef is the visible first column of stats.
    With RngTarget
        .AutoFilter Field:=ColIDIndex, Criteria1:="=", Operator:=xlFilterValues, VisibleDropDown:=True
        Set RngTargetVisible = .Range("J2:M" & LRow).SpecialCells(xlCellTypeVisible)
        Set ColRef = .Range("J2:J" & LRow).SpecialCells(xlCellTypeVisible)
    End With

    'Logic: For each cell in the first column of stats, let's get its offset one cell above
    'and 7 cells to the left. This method is not necessary. Simply assigning ColRef to Column C's
    'visible cells and changing below to CellRef.Offset(-1,0) is alright. I chose this way so it's
    'easier to visualize the approach. RngNames is a consolidation of the cells with ranges, which we'll
    'copy first before the stats.
    For Each CellRef In ColRef
        If RngNames Is Nothing Then
            Set RngNames = CellRef.Offset(-1, -7)
        Else
            Set RngNames = Union(RngNames, CellRef.Offset(-1, -7))
        End If
    Next CellRef

    'Copy the names first, then RngTargetVisible, which are the total stats. Copying headers is up
    'to you. Of course, modify as necessary.
    RngNames.Copy ShPaste.Range("A1")
    RngTargetVisible.Copy ShPaste.Range("B1")

End Sub

截圖:

設定:

在此處輸入圖片說明

結果:

在此處輸入圖片說明

演示視頻在這里:

使用過濾器和可見單元格

讓我們知道是否有幫助。

暫無
暫無

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

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