EXCEL VBA -将多个选定工作表中的特定列复制到新的工作表/工作簿

m3eecexj  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(195)

我想从大约40-50张纸中提取一些数据,如果是单张纸,我知道该怎么做。但是我不知道如何从多张纸中提取。。一点是,选择一些表(选定的表),但不是所有的,因为一些隐藏的表,我不需要使用。
如果它是单页的,我的代码如下,我也尝试使用“for each”,但它选择了所有的。有谁能帮我选多张纸吗?谢谢

Sub CopyRetentionData()
    Dim wsInput As Worksheet
    Dim wsOutput As Worksheet
    Dim lastRow As Long
    Dim outputRow As Long

    Set wsInput = ActiveSheet

    ' Check if the Output sheet exists, if not, create it
    On Error Resume Next
    Set wsOutput = Worksheets("Output")
    If wsOutput Is Nothing Then
        Set wsOutput = Worksheets.Add
        wsOutput.Name = "Output"
    End If
    On Error GoTo 0

    wsOutput.Cells.Clear     'Clear any previous content in the Output sheet

    lastRow = wsInput.Cells(wsInput.Rows.Count, "B").End(xlUp).Row

    outputRow = 2

    For i = 1 To lastRow

        If InStr(1, wsInput.Cells(i, "B").Value, "Retention") > 0 Then 'Check if column B contains the word "Retention"

            wsOutput.Cells(outputRow, "A").Value = Right(wsInput.Range("D4").Value, 13)
            wsOutput.Cells(outputRow, "B").Value = wsInput.Cells(i, "C").Value
            wsOutput.Cells(outputRow, "C").Value = wsInput.Cells(i, "R").Value
         
            outputRow = outputRow + 1
        End If
    Next i

    MsgBox "Complete!", vbInformation, "Operation Complete"
End Sub
lsmepo6l

lsmepo6l1#

使用For Each是正确的,但您需要测试工作表是否可见(未隐藏)并被选中。

Sub demo()

    Dim ws As Worksheet, wb As Workbook
    
    Set wb = ThisWorkbook
    
    For Each ws In wb.Sheets
        If ws.Visible = xlSheetVisible And IsWSSelected(ws, wb) Then
            CopyRetentionData
        End If
    Next

End Sub

我得到了一个函数来检查是否从MrExcel中选择了一个工作表

Function IsWSSelected(wsToTest As Worksheet, Optional wb As Workbook) As Boolean
'Credit: Greg Truby https://www.mrexcel.com/board/threads/check-if-worksheet-is-selected.193955/
    Dim ws As Worksheet
    If wb Is Nothing Then Set wb = ThisWorkbook
    For Each ws In wb.Windows(1).SelectedSheets
        If ws Is wsToTest Then IsWSSelected = True: Exit Function
    Next ws
End Function

您需要更改在CopyRetentionData例程中放置输出的位置,即将outputRow = 2替换为outputRow = lastRow(ws) + 1我使用以下代码查找工作表中的最后一行

Public Function lastRow(rg As Variant) As Long
'Find the last row used in a worksheet - regardless of where the data starts and ends
'and regardless of whether the data is contiguous or jagged
'Note use of Variant for the input range parameter
'This allows both worksheets and ranges to passed into the function
    On Error Resume Next
    Dim lr As Long
    lr = rg.Cells.Find(What:="*" _
                    , LookAt:=xlPart _
                    , LookIn:=xlFormulas _
                    , SearchOrder:=xlByRows _
                    , SearchDirection:=xlPrevious).Row
    If Err.Number <> 0 Then
        lr = 1  'cater for a completely empty sheet
    End If
    On Error GoTo 0
    lastRow = lr
End Function

相关问题