简体   繁体   English

VBA 用于过滤的宏,从列中复制指定值并创建然后粘贴到具有该列名称的新工作表中

[英]VBA Macro to filter, copy the specified value from a column and create then paste in a new sheet with that column name

I am very new to VBA macro.我对 VBA 宏很陌生。 I coded the macro below that filters on column "N" containing "Ocean" and copies its corresponding data.我对下面的宏进行了编码,该宏对包含“Ocean”的列“N”进行了过滤,并复制了其相应的数据。 Then it creates a new worksheet with the name "Ocean" and pastes the data there.然后它创建一个名为“Ocean”的新工作表并将数据粘贴到那里。

Or is it possible to filter on column N containing "Ocean" and delete the non-matching data?或者是否可以过滤包含“Ocean”的 N 列并删除不匹配的数据? Please help.请帮忙。 Below is my code and excel screenshot for reference.下面是我的代码和excel截图供参考。

Dim Wf As Workbook
Dim Tsht As Worksheet, FSht As Worksheet
Dim lRow As Long, lRw As Long

Set Wf = ActiveWorkbook
Set Tsht = Wf.Sheets("Main")

With Tsht
        lRow = .Cells(.Rows.Count, "N").End(xlUp).Row
    End With
    
Application.AskToUpdateLinks = False


Set FSht = Wf.Sheets("Ocean")

    With FSht
        .AutoFilterMode = False
        lRw = .Cells(.Rows.Count, "C").End(xlUp).Row
        .Range("A" & lRw).AutoFilter Field:=2, Criteria1:="Ocean"
        .AutoFilter.Range.Copy

      End With 

N列

I want the macro to only split rows containing Ocean in a new sheet, with a sheet name of "Ocean".我希望宏仅在新工作表中拆分包含 Ocean 的行,工作表名称为“Ocean”。 Or macro should keep only data corresponding to Ocean and delete the rest... Please help...........或者宏应该只保留与Ocean对应的数据并删除rest ...请帮忙......

AutoFilter Copy自动过滤复制

This will delete the worksheet Ocean if it exists.这将删除工作表Ocean (如果存在)。 Then it will add a new sheet, name it Ocean and copy the filtered data from worksheet Main to it.然后它将添加一个新工作表,将其命名为Ocean并将过滤后的数据从工作表Main复制到它。

The Code代码

Option Explicit

Sub AutoFilterCopy()

    Application.AskToUpdateLinks = False
    
    Dim wb As Workbook
    ' If the code is in the ActiveWorkbook you should use ThisWorkbook instead.
    Set wb = ActiveWorkbook
        
    ' Delete Target Worksheet.
    Dim FSht As Worksheet
    On Error Resume Next
    Set FSht = wb.Worksheets("Ocean")
    If Err.Number = 0 Then
        Application.DisplayAlerts = False
        FSht.Delete
        Application.DisplayAlerts = True
    End If
    On Error GoTo 0
    
    ' Define Target Worksheet.
    Set FSht = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count))
    FSht.Name = "Ocean"
    
    ' Define Source Worksheet.
    Dim Tsht As Worksheet
    Set Tsht = wb.Worksheets("Main")
    With Tsht
        If .AutoFilterMode Then
            .AutoFilterMode = False
        End If
        ' 14 is column N
        .Range("A1").AutoFilter Field:=14, Criteria1:="Ocean"
        .AutoFilter.Range.Copy FSht.Range("A1")
    End With
    
    MsgBox "Worksheet created, data copied.", vbInformation, "Success"
    
End Sub

EDIT:编辑:

  • Instead of column N (14), OP wants to identify the criteria column with its header: "Mode". OP 想要用其 header:“模式”来标识标准列,而不是列N (14)。

Edited Code编辑代码

Option Explicit

Sub AutoFilterCopy()

    Application.AskToUpdateLinks = False
    
    Dim wb As Workbook
    ' If the code is in the ActiveWorkbook you should use ThisWorkbook instead.
    Set wb = ActiveWorkbook
        
    ' Delete Target Worksheet.
    Dim FSht As Worksheet
    On Error Resume Next
    Set FSht = wb.Worksheets("Ocean")
    If Err.Number = 0 Then
        Application.DisplayAlerts = False
        FSht.Delete
        Application.DisplayAlerts = True
    End If
    On Error GoTo 0
    
    ' Define Target Worksheet.
    Set FSht = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count))
    FSht.Name = "Ocean"
    
    ' Define Source Worksheet.
    Dim Tsht As Worksheet
    Set Tsht = wb.Worksheets("Main")
    With Tsht
        If .AutoFilterMode Then
            .AutoFilterMode = False
        End If
        Const FieldName As String = "Mode"
        Dim FieldNumber As Long
        ' Note that there will be an error if "Mode" cannot be found.
        FieldNumber = Application.Match(FieldName, .Rows(1), 0)
        .Range("A1").AutoFilter Field:=FieldNumber, Criteria1:="Ocean"
        .AutoFilter.Range.Copy FSht.Range("A1")
    End With
    
    MsgBox "Worksheet created, data copied.", vbInformation, "Success"
    
End Sub

Here is another option using Range.Find .这是使用Range.Find的另一个选项。 I generally try to avoid hard coding rows and columns whenever possible.我通常尽量避免对行和列进行硬编码。 You will see where I've searched the header row for "Mode".您将看到我在 header 行中搜索“模式”的位置。 This allows the column order to change without breaking the code.这允许在不破坏代码的情况下更改列顺序。

I would modify my code after seeing the answer provided by @VBasic2008.看到@VBasic2008 提供的答案后,我会修改我的代码。 I would use the .AutoFilter.Copy method, rather than looping through each match.我会使用.AutoFilter.Copy方法,而不是遍历每个匹配项。 I also like how he has checked to see if a sheet with the desired mode already exists.我也喜欢他如何检查是否已经存在具有所需模式的工作表。

Good luck!祝你好运!

Public Sub ExtractDataByMode()

Const mode = "Ocean"

Dim mainWS As Worksheet
Set mainWS = ThisWorkbook.Worksheets("Main")
Dim hdrRow As Range
Set hdrRow = Intersect(mainWS.Rows(1), mainWS.UsedRange)

Dim modeColIdx As Integer
modeColIdx = hdrRow.Find(What:="Mode", lookat:=xlWhole, _
    MatchCase:=False).Column
    
Dim modeColRng As Range
Set modeColRng = Intersect(mainWS.Columns(modeColIdx), mainWS.UsedRange)

Dim firstMatch As Range
Set firstMatch = modeColRng.Find(What:=mode, lookat:=xlWhole, _
    MatchCase:=False)
    
Dim modeWS As Worksheet
Set modeWS = ThisWorkbook.Worksheets.Add( _
    After:=ThisWorkbook.Worksheets( _
    ThisWorkbook.Worksheets.Count))
modeWS.Name = mode
hdrRow.Copy modeWS.Cells(1, 1)

Dim match As Range
Dim nextRow As Integer
Dim matchRow As Range
Set match = firstMatch
nextRow = modeWS.UsedRange.Rows.Count + 1
Do
    Set matchRow = Intersect(mainWS.Rows(match.Row), mainWS.UsedRange)
    matchRow.Copy modeWS.Cells(nextRow, 1)
    Set match = modeColRng.FindNext(match)
    nextRow = modeWS.UsedRange.Rows.Count + 1

Loop While match.Address <> firstMatch.Address

End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 过滤 excel 列并将粘贴复制到另一个新工作表,工作表名称应为过滤器值 - Filter a excel column and copy paste to another new sheet and the sheet name should be filter value 为多个工作表创建VBA,并使用公式将粘贴复制到新列中 - Create VBA for multiple sheet and copy paste in new column with formula 宏VBA根据标题复制列并粘贴到另一个工作表中 - Macro VBA to Copy Column based on Header and Paste into another Sheet VBA 根据日期将工作表 1 中的单元格值复制/粘贴到工作表 2 的宏 - VBA Macro to copy/paste cell value from sheet 1 to 2 based on date VBA 从表 1 复制列并将粘贴转置到表 2 中的行 - VBA copy column from sheet 1 and transpose paste into row in sheet 2 vba代码以查找特定值并在该列的后续单元格中复制值并粘贴到新工作表中 - vba code to find a specific value and copy value in subsequent cell in the column and paste in a new sheet 复制并粘贴到另一个工作表Excel vba中的新列 - Copy and paste to new column in another sheet Excel vba VBA-如何将列中的最后一个值复制并粘贴到另一个工作表 - VBA - How to Copy and Paste the last value in a column to another Sheet Excel VBA 宏从 2 整列创建新值 - Excel VBA macro create new value from 2 entire column 宏,用于将一页中的每一列复制并粘贴到页眉中,以保持不断增长的数据 - Macro to copy and paste column by column from one sheet into master sheet by header to maintain growing data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM