按列值将数据拆分为不同的工作表

2024-02-03

假设我有一个工作表,A 列中有多个不同的值。有没有办法创建一个宏,将列条目为 0 的所有行放入一个单独的工作表中,所有行的条目 1 都放在另一个工作表中,依此类推?我的第一直觉是创造一些东西:

1) 按相关列排序

2) 使用 IF 语句检查前一个单元格和下一个单元格之间的差异为 0 的第一个位置

3) 创建一个新工作表,复制第一个差异 0 之前的所有行,包括计算中产生差异 0 的第一个单元格

4) 选择新工作表并将数据块粘贴到

5) 继续此过程,直到与正在检查的列不同的计数器列中的空白单元格产生空白值(这是因为正在排序的列确实有空白值)

有更好的方法来解决这个问题吗?如果没有,在构建上述内容时提供任何帮助将不胜感激。随着我的进展,我将尝试用新代码更新这篇文章。

更新:我认为这是朝着正确方向迈出的一步,如果有人能提供建议那就太好了。

Dim lastrow As Long
Dim myRange As Long


lastrow = Cells(Rows.Count, "A").End(xlUp).Row
myRange = Range("G1:G" & lastrow)

For i = 1 To myRange.Rows.Count
    If myRange(i, i+1) <> 0 then
        Range("1:i").Copy
    Sheets.Add After:=Sheet(3)
    Sheet(3).Paste
    ElseIf myRange(i , i+1) = 0
    End If
Next i

我认为这种设计将带您到达目的地...考虑一个如下所示的工作簿:

下面的脚本将在第 2 列中找到一个空白单元格(可在代码中自定义),然后根据您的规范对数据块进行操作。内置了一些健全性检查,包括唯一组的计数(您真的想要超过 25 个结果表吗?当然,该数字可以在代码中自定义),并且您是否期望对超过 10,000 行进行操作? (行检查也是可定制的。)

Option Explicit
Sub SplitDataIntoSheets()

Dim SafetyCheckUniques As Long
SafetyCheckUniques = 25 '<~ more than this number of output sheets? might be a mistake...
Dim SafetyCheckBlank As Long
SafetyCheckBlank = 10000 '<~ more than this number of rows? might be a mistake...
Dim ErrorCheck As Long

Dim Data As Worksheet, Target As Worksheet
Dim LastCol As Long, BlankCol As Long, _
    GroupCol As Long, StopRow As Long, _
    HeaderRow As Long, Index As Long
Dim GroupRange As Range, DataBlock As Range, _
    Cell As Range
Dim GroupHeaderName As String
Dim Uniques As New Collection

'set references up-front
Set Data = ThisWorkbook.Worksheets("Data")  '<~ assign the data-housing sheet
GroupHeaderName = "ID"                      '<~ the name of the column with our groups
BlankCol = 2                                '<~ the column where our blank "stop" row is
GroupCol = 1                                '<~ the column containing the groups
HeaderRow = 1                               '<~ the row that has our headers
LastCol = FindLastCol(Data)
StopRow = FindFirstBlankInCol(BlankCol, HeaderRow, Data)

'sanity check: if the first blank is more than our safety number,
'              we might have entered the wrong BlankCol
ErrorCheck = 0
If StopRow > SafetyCheckBlank Then
    ErrorCheck = MsgBox("Dang! The first blank row in column " & _
                        BlankCol & " is more than " & SafetyCheckBlank & _
                        " rows down... Are you sure you want to run this" & _
                        " script?", vbYesNo, "That's a lot of rows!")
    If ErrorCheck = vbNo Then Exit Sub
End If

'identify how many groups we have
With Data
    Set GroupRange = .Range(.Cells(HeaderRow, GroupCol), .Cells(StopRow, GroupCol))
    GroupRange.AdvancedFilter Action:=xlFilterInPlace, Unique:=True
    For Each Cell In GroupRange.SpecialCells(xlCellTypeVisible)
        If Cell.Value <> GroupHeaderName Then
            Uniques.Add (Cell.Value)
        End If
    Next Cell
End With
Call ClearAllFilters(Data)

'sanity check: if there are more than 25 unique groups, do we really want
'              more than 25 sheets? prompt user...
ErrorCheck = 0
If Uniques.Count > SafetyCheckUniques Then
    ErrorCheck = MsgBox("Whoa! You've got " & Uniques.Count & " groups in column " & _
                        GroupCol & ", which is more than " & SafetyCheckUniques & _
                        " (which is a lot of resultant sheets). Are you sure you" & _
                        " want to run this script?", vbYesNo, "That's a lot of sheets!")
    If ErrorCheck = vbNo Then Exit Sub
End If

'loop through the unique collection, filtering the data block
'on each unique and copying the results to a new sheet
With Data
    Set DataBlock = .Range(.Cells(HeaderRow, GroupCol), .Cells(StopRow, LastCol))
End With
Application.DisplayAlerts = False
For Index = 1 To Uniques.Count
    Call ClearAllFilters(Data)
    'make sure the sheet doesn't exist already... delete the sheet if it's found
    If DoesSheetExist(Uniques(Index)) Then
        ThisWorkbook.Worksheets(CStr(Uniques(Index))).Delete
    End If
    'now build the sheet and copy in the data
    Set Target = ThisWorkbook.Worksheets.Add
    Target.Name = Uniques(Index)
    DataBlock.AutoFilter Field:=GroupCol, Criteria1:=Uniques(Index)
    DataBlock.SpecialCells(xlCellTypeVisible).Copy Destination:=Target.Cells(1, 1)
Next Index
Application.DisplayAlerts = True
Call ClearAllFilters(Data)

End Sub


'INPUT: a worksheet name (string)
'RETURN: true or false depending on whether or not the sheet is found in this workbook
'SPECIAL CASE: none
Public Function DoesSheetExist(dseSheetName As String) As Boolean
    Dim obj As Object
    On Error Resume Next
    'if there is an error, sheet doesn't exist
    Set obj = ThisWorkbook.Worksheets(dseSheetName)
    If Err = 0 Then
        DoesSheetExist = True
    Else
        DoesSheetExist = False
    End If
    On Error GoTo 0
End Function

'INPUT: a column number (long) to examine, the header row we should start in (long)
'       and the worksheet that both exist in
'RETURN: the row number of the first blank
'SPECIAL CASE: return 0 if column number is <= zero,
'return 0 if the header row is <= zero,
'return 0 if sheet doesn't exist
Public Function FindFirstBlankInCol(ffbicColNumber As Long, ffbicHeaderRow As Long, _
    ffbicWorksheet As Worksheet) As Long
    If ffbicColNumber <= 0 Or ffbicHeaderRow <= 0 Then
        FindFirstBlankInCol = 0
    End If
    If Not DoesSheetExist(ffbicWorksheet.Name) Then
        FindFirstBlankInCol = 0
    End If
    'use xl down, will land on the last row before the blank
    With ffbicWorksheet
        FindFirstBlankInCol = .Cells(ffbicHeaderRow, ffbicColNumber).End(xlDown).Row
    End With
End Function

'INPUT: a worksheet on which to identify the last column
'RETURN: the column (as a long) of the last occupied cell on the sheet
'SPECIAL CASE: return 1 if the sheet is empty
Public Function FindLastCol(flcSheet As Worksheet) As Long
    If Application.WorksheetFunction.CountA(flcSheet.Cells) <> 0 Then
        FindLastCol = flcSheet.Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
    Else
        FindLastCol = 1
    End If
End Function

'INPUT: target worksheet on which to clear filters safely
'TASK: clear all filters
Sub ClearAllFilters(cafSheet As Worksheet)
    With cafSheet
        .AutoFilterMode = False
        If .FilterMode = True Then
            .ShowAllData
        End If
    End With
End Sub
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按列值将数据拆分为不同的工作表 的相关文章

  • 在Excel中过滤后打印可见区域的宏

    我有一个根据过滤表的宏column A价值观 现在我想打印only过滤器后的可见行 但遗憾的是它打印了所有行 包括过滤期间隐藏的顶部和底部行 在我的工作表中 有来自的数据Column A I 但打印区域只能是Columns C I 过滤后的
  • VBA按空格分割字符串

    我想要一个 Excel 函数 我可以调用该函数并将单元格传递到其中 输入 Firstname Lastname email protected cdn cgi l email protection Firstname midname Las
  • 使用VBA删除Excel中的非重复数据

    我尝试删除非重复数据并保留重复数据 我已经完成了一些编码 但什么也没发生 哦 这是错误 哈哈 这是我的代码 Sub mukjizat2 Dim desc As String Dim sapnbr As Variant Dim shortDe
  • 将 PDFMaker 与 MS Outlook 结合使用

    我想将 Adob e PDFMaker 插件与 MS Outlook 2013 一起使用 使用 PDFMAKER 将多封电子邮件保存为 pdf https stackoverflow com questions 44723984 savin
  • 如何用线条在一个Excel散点图中绘制多个分组数据

    我在 Excel 中的一张图表 带线的散点图 中绘制分组数据 按索引 时遇到一些困难 我将非常感谢您的帮助 我的数据分为三列 第一列是数据或组的索引 即每组数据的唯一编号 第二列是时间 第三列是数据 Group Time Data 1 1
  • Excel 公式或 VBA:在具有 2 列条件的单独表中查找匹配的地址 - 无辅助列

    我需要公式结构方面的帮助 我有2张桌子 我想找到 a 列和 b 列相等的匹配项并获取表 2 中的地址 它们将是唯一的条目 例如 项目信息表 A B C 1 Name Company Project 2 Chris Evans Apple I
  • 使用 SpreadsheetLight 进行行计数

    我正在寻找一个类似于 DataTable Rows Count 的函数 它可以与 SLDocument 一起使用来找出有多少行中有数据 SpreadsheetLight 中有可用的东西吗 还有其他方法可以实现这一目标吗 Brendan SL
  • 如果单元格包含 1 个或多个关键字,则更改不同单元格的值

    我有一个列 其中包含一些字符串描述 例如 Bob davids mowing the lawn tipping cows 此外 我将在不同的工作表或列上列出关键字列表 例如工作关键字列表1 davids work 播放关键字列表 mowin
  • 根据不同的列数据范围隐藏行

    我对使用 VBA 相当陌生 我正在尝试创建一个代码 该代码将查看具有不同数据范围的两个不同列 并隐藏最后一个数据点之外的行 引用两列 目前我有这个 Private Sub Worksheet PivotTableUpdate ByVal T
  • 如何从包含许多表的 Excel 工作表中解析数据帧(使用 Python,可能使用 Pandas)

    我正在处理布局糟糕的 Excel 工作表 我正在尝试解析这些工作表并将其写入数据库 每个工作表可以有多个表 尽管这些可能的表格的标题是已知的 但哪些表格将位于任何给定的工作表上 它们在工作表上的确切位置也不是已知的 表格不以一致的方式对齐
  • 在 Android 上使用 Excel 文件

    我正在开发一个应该能够创建 读取和写入 Excel 文件的模块 是否有 推荐 轻量级 Java 库用于处理可以在 Android 上运行的 Excel 文件 欢迎提出建议 Thanks 找到一个
  • 解析未完全加载 VBA 的网站

    尝试进行简单的网络解析 我的问题是页面在向下滚动之前无法完全加载 谷歌搜索已经提出可能使用硒 但由于我不知道如何使用它 我想我会在这里问 我使用的代码 Sub gfquote Dim oHttp As MSXML2 XMLHTTP Dim
  • Excel 的查找和查找下一个 VBA

    我一直在试图弄清楚如何处理这个问题 但基本上我想要一种方法来打印 B 列中的值 给定与 A 列匹配的特定值 例如 Column A Column B 1 ABC 2 DEF 3 GHI 1 JKL 我想在使用 find findnext 或
  • 在 Excel 中的文件夹内的所有文件上添加一列

    我在一个文件夹内有 250 个不同的 excel 文件 具有相同的布局 其中包含列A to F 我需要在列上添加新列G 传统的方法是打开每个文件并在以下位置添加新列G 有没有使用 Excel 宏或任何其他工具的简单过程来完成此任务 这个链接
  • 使用 VBA 从数据透视表中提取数据

    我编写了以下 vba 代码 该代码应该从 old xlsx 的某些单元格导入任何现有数据 这些单元格是数据透视表的一部分 并且 OE gt location gt qual in 作为其行的子单元格 该列由手动输入的日期决定 strForm
  • 用于更新 Word 文档中所有字段的宏

    多年来 我构建了一个 vba 宏 该宏应该更新 Word 文档中的所有字段 我在发布文档进行审查之前调用此宏 以确保所有页眉和页脚等均正确 目前 它看起来像这样 Sub UpdateAllFields UpdateAllFields Mac
  • alasql 需要已包含的 xlsx

    我正在尝试使用将数据导出到 Excel 工作表alasql and xlsx 我已遵循此处的所有准则 https github com agershun alasql wiki Xlsx https github com agershun
  • 参考上一个问题:为什么 VBA 没有加载所有发票详细信息

    除了上一个问题之外 我们在销售发票上仍然存在相同的加载失败问题 下面的 VBA Json 仍然仅加载一行或第一个产品详细信息行 而不是与表中该销售发票合作的所有产品行详细信息 我们希望下面的 VBA 能够根据参数加载发票详细信息 例如 如果
  • Excel VBA 用户窗体 - 当发生变化时执行 Sub

    我有一个包含很多文本框的用户表单 当这些文本框的值发生变化时 我需要通过调用子例程 AutoCalc 根据文本框值重新计算最终结果值 我有大约 25 个框 我不想向每个调用上述子例程的文本框单独添加 Change 事件 当某些值发生变化时调
  • 导入到 SQL Server 时忽略 Excel 文件中的列

    我有多个具有相同格式的 Excel 文件 我需要将它们导入 SQL Server 我当前遇到的问题是 有两个文本列我需要完全忽略 因为它们是自由文本 并且某些行的字符长度超出了服务器允许我导入的长度 这会导致截断错误 因为我的分析不需要这些

随机推荐