【问题标题】:Excel macro - Iteratively copy rows from one sheet to anotherExcel 宏 - 将行从一张表迭代复制到另一张表
【发布时间】:2015-02-24 03:23:31
【问题描述】:

一个工作簿中有 3 张工作表:Sheet1、Sheet2、Sheet3。 Sheet1 有以下数据:

aaa    3
aaa    2
aaa    45
aaa    211
aaa    12
bbbb   3
bbbb   2
bbbb   4
ccc    2
ccc    5
dddd   2
dddd   10
dddd   25

会有这样一个哈希表:

key        values
GroupA     aaa, bbbb
GroupB     ccc, dddd

如何使用宏子例程将数据加载到其他工作表 Sheet2 和 Sheet3 以使 Sheet2 包含所有带有“GroupA”的行,而 Sheet3 在 Sheet1 中包含所有带有“GroupB”的行?

编辑:
我想使用一种结构的哈希表来存储 GroupA、GroupB 等及其值,并相应地迭代处理 sheet1,w.r.t 每个组。

【问题讨论】:

  • 你真的需要按照你建议的方式去做吗?或许如果您对想要完成的任务更加具体,有人可以提出比您目前所设想的更优雅的解决方案。

标签: excel vba


【解决方案1】:

您可以使用 ADO。

Dim cn As Object
Dim rs As Object
Dim rs2 As Object
Dim sFile As String
Dim sCon As String
Dim sSQL As String
Dim s As String
Dim i As Integer, j As Integer

''This is not the best way to refer to the workbook
''you want, but it is very convenient for notes
''It is probably best to use the name of the workbook.

sFile = ActiveWorkbook.FullName

''Note that if HDR=No, F1,F2 etc are used for column names,
''if HDR=Yes, the names in the first row of the range
''can be used.
''This is the Jet 4 connection string, you can get more
''here : http://www.connectionstrings.com/excel

sCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sFile _
    & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"

''Late binding, so no reference is needed

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
Set rs2 = CreateObject("ADODB.Recordset")


cn.Open sCon

sSQL = "SELECT Key, [Values] " _
       & "FROM [Sheet2$] "

rs.Open sSQL, cn, 3, 3

i = 3
Do While Not rs.EOF

    sSQL = "SELECT Key, [Values] " _
           & "FROM [Sheet1$] " _
           & "WHERE '" & rs![Values] _
           & "' Like '%' & Key & '%' "

    rs2.Open sSQL, cn, 3, 3

    ''Pick a suitable empty worksheet for the results
    ''Worksheets.Add
    With Worksheets("Sheet" & i)
        .Cells(1, 1) = rs!Key

        For j = 0 To rs.Fields.Count - 1
            .Cells(2, j + 1) = rs.Fields(j).Name
        Next

        .Cells(3, 1).CopyFromRecordset rs2
    End With

    rs.MoveNext
    i = i + 1
    rs2.Close
Loop

''Tidy up
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing

【讨论】:

    【解决方案2】:

    您必须坚持使用 has 表格样式吗?我认为如果您将该组包含在 sheet1 的额外列中,然后您可以使用表 2 和 3 的数据透视表来显示基础数据的过滤视图会更容易

    【讨论】:

    • 谢谢,多写一列就好了。请给我一个领导,伪代码真的会有所帮助。再次感谢。
    • 以这种方式做事不需要任何代码。这是一个使用数据透视表的示例的链接dummies.com/how-to/computers-software/ms-office/excel/data/… 基本上,这个想法是你有一个日期来源(在你的情况下是 Sheet1),然后你“透视”数据以不同的方式显示它,所以在 Sheet2 上你会有一个过滤器只显示第 1 组等中的记录
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    相关资源
    最近更新 更多