簡體   English   中英

Excel宏-迭代地將行從一張紙復制到另一張紙

[英]Excel macro - Iteratively copy rows from one sheet to another

工作簿中有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。

您可以使用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

您是否必須堅持餐桌風格? 我認為,如果將組包含在工作表Sheet1的額外列中會更容易,然后可以將工作表2&3的數據透視表用於顯示基礎數據的過濾視圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM