[英]How do I export rows of one excel sheet into a new excel sheet depending on the word in column A
I have a worksheet with over 8,000 rows and each one as 1 of 29 words as an identifier in column A. I would like to write a VBA script that will parse all of the rows, group them by the identifier in column A and export each group into a new work sheet and name each worksheet as its identifier 我有一个工作表,其中有8,000多行,每行作为29个单词中的1个作为A列中的标识符。我想编写一个VBA脚本,该脚本将解析所有行,并按A列中的标识符对它们进行分组并导出每行分组到一个新的工作表中,并命名每个工作表作为其标识符
For example if this is my data: 例如,如果这是我的数据:
Column A Column B Column C
X cat blue
Y dog red
Z bird green
Y whale yellow
Z tiger black
X wolf purple
I would like this output for Sheet 1 named X: 我想要名为X的工作表1的输出:
Column A Column B Column C
X cat blue
X wolf purple
I would like this output for Sheet 2 named Y: 我想要名为Y的工作表2的输出:
Column A Column B Column C
Y dog red
Y whale yellow
And this output for Sheet 3 named Z: 并将工作表3的此输出命名为Z:
Column A Column B Column C
Z bird green
Z tiger black
you could use AutoFilter()
methods of Range
object, as follows: 您可以使用Range
对象的AutoFilter()
方法,如下所示:
Option Explicit 显式期权
Sub main()
Dim helperCol As Range, cell As Range
With Worksheets("Data") '<--| reference your relevant sheet (change "Data" to your actual sheet name)
Set helperCol = .UsedRange.Resize(, 1).Offset(, .UsedRange.Columns.COUNT) '<--| set a "helper" range where to store unique identifiers
With .Range("C1", .Cells(.Rows.COUNT, 1).End(xlUp).Offset(1)) '<-- reference its "data" range from cell "A1" to last not empty cell in column "C"
helperCol.Value = .Resize(, 1).Value '<--| copy identifiers to "helper" range
helperCol.RemoveDuplicates Columns:=1, Header:=xlYes '<--| remove duplicates in copied identifiers
For Each cell In helperCol.Resize(helperCol.Rows.COUNT - 1).Offset(1).SpecialCells(xlCellTypeConstants) '<--| loop through unique identifiers, skipping header
.AutoFilter Field:=1, Criteria1:=cell.Value '<--| filter "data" on identifiers column with current (unique) identifier
.SpecialCells(xlCellTypeVisible).Copy Destination:=GetOrCreateSheet(cell.Value).Range("A1") '<--| copy filtered data (skipping header) and paste it to corresponding sheet starting from its column "A" first not emtpy cell
Next cell
End With
.AutoFilterMode = False '<--| show all rows back
helperCol.ClearContents '<--| clear "helper" range
End With
End Sub
Function GetOrCreateSheet(shtName As String) As Worksheet
On Error Resume Next
Set GetOrCreateSheet = Worksheets(shtName)
If GetOrCreateSheet Is Nothing Then
Set GetOrCreateSheet = Worksheets.Add
GetOrCreateSheet.name = shtName
Else
GetOrCreateSheet.Cells.ClearContents
End If
End Function
You've got a bit of a multi-step problem here. 您在这里遇到了一个多步骤问题。 Have you written up any code so far? 到目前为止,您是否编写了任何代码? If you've run into any specific errors, post them here and we'll gladly provide more specific advice. 如果您遇到任何特定的错误,请将其发布在此处,我们很乐意提供更具体的建议。
For now, I would recommend breaking up your problem into its component features. 现在,我建议将您的问题分解成其组件功能。 You can then proceed to work on, seek help with, and complete each of these parts on their own and tie them all together at the end. 然后,您可以继续进行工作,寻求帮助,并单独完成每个部分,最后将它们捆绑在一起。
A recommended step-by-step approach: 推荐的分步方法:
Step 1: Looping through a range. 第1步:遍历范围。
Step 2: Parse and save the results. 步骤2:解析并保存结果。
A starting place for learning about VBA conditional statements. 学习VBA条件语句的起点。
A starting place for learning about VBA arrays. 学习VBA阵列的起点。
Step 3: Adding and naming a new worksheet. 步骤3:添加和命名新的工作表。
A previous Stack Overflow answer. 先前的堆栈溢出答案。
Step 4: Placing your stored information onto your new sheet. 步骤4:将您存储的信息放到新表上。
If you're using the arrays approach, here's a previous Stack Overflow question regarding the Transpose function. 如果您使用的是数组方法,那么这是先前有关Transpose函数的Stack Overflow问题。
Good luck! 祝好运!
Should you use Excel for Windows, you can access the Jet/ACE SQL Engine via ADO ODBC and run SQL queries to achieve needs. 如果您使用Excel for Windows,则可以通过ADO ODBC访问Jet / ACE SQL引擎并运行SQL查询来满足需求。 And yes, you can query the current workbook (last saved instance): 是的,您可以查询当前工作簿(最后保存的实例):
Sub RunSQL()
Dim conn As Object, rst As Object
Dim strConnection As String, strSQL As String
Dim i As Integer, fld As Object
Dim WS As Worksheet, var As Variant
Set conn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")
' STRING CONNECTION (TWO VERSIONS)
' strConnection = "DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" _
' & "DBQ=C:\Path\To\Workbook.xlsm;"
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source='C:\Path\To\Workbook.xlsm';" _
& "Extended Properties=""Excel 8.0;HDR=YES;"";"
' OPEN DB CONNECTION
conn.Open strConnection
For Each var In Array("X", "Y", "Z")
' CREATE WORKSHEET
Set WS = ActiveWorkbook.Sheets.Add(After:=Worksheets(Worksheets.Count))
WS.Name = var
' SQL STATEMENT
strSQL = " SELECT [Sheet1$].[Column A], [Sheet1$].[Column B]," _
& " [Sheet1$].[Column C]" _
& " FROM [Sheet1$]" _
& " WHERE [Sheet1$].[Column A] = '" & var & "';"
' OPEN RECORDSET
rst.Open strSQL, conn
' COLUMN HEADERS
WS.Range("A1").Activate
For i = 1 To rst.Fields.Count
WS.Cells(1, i) = rst.Fields(i - 1).Name
Next i
' DATA ROWS
WS.Range("A2").CopyFromRecordset rst
rst.Close
Next var
conn.Close
Set rst = Nothing: Set conn = Nothing
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.