簡體   English   中英

如果條件為,則將excel中的行復制到工作表。

[英]Copy rows in excel to sheets if condition is .

我正在嘗試根據D列中的數據將工作表“全部”的整行復制到另一張工作表中。D列中有多個值(家庭作業/高級/入門),需要復制這些行的工作表相應的名稱。 (作業到作業表)。

工作表“全部”中的數據將被添加到其中,並且需要復制新數據,而無需復制已經存在的數據。

這不是大問題。 最好的辦法是保持簡單,並在“全部”更改時復制所有內容。 我在“所有”工作表上都有一個“重新分發”按鈕,並有事件調用scatterRows()

您沒有說出源工作表的樣子,所以我為工作表“ all”做了一些准備:

9   0.181626294 carrot  beginner    Irene
5   0.221180184 beans   advanced    Eva
8   0.221813735 turnip  advanced    Harry
10  0.314800867 lettuce homework    John
4   0.360163255 peas    homework    Doug
11  0.379956592 pepper  advanced    Karen
3   0.44415906  tomato  beginner    Charlie
6   0.647446239 corn    beginner    Frank
2   0.655706735 potato  advanced    Bob
7   0.666002258 lentils homework    George
1   0.768524361 squash  homework    Alice

代碼相當靈活; 它會找到整個源代碼塊,因此,只要有“ D”列保留工作表鍵並且數據以A1(無標題)開頭,您就可以擁有多少列。 如果您有標題,請將所有A1引用更改為A2。

必須已創建其他工作表(“作業”等)。 -並且您需要對Microsoft腳本運行時的引用集。

代碼中唯一“有趣”的部分是找出目標范圍的字符串(putString)。

Option Explicit

'' Copy rows from the "all" sheet to other sheets
'' keying the sheetname from column D.
'' **** Needs Tools|References|Microsoft Scripting Runtime
'' Changes:
''      [1] fixed the putString calculation.
''      [2] Added logic to clear the target sheets.

Sub scatterRows()

    Dim srcRange As Range
    Dim srcRow As Range
    Dim srcCols As Integer
    Dim srcCat As String
    Dim putRow As Integer
    Dim putString As String
    Dim s                      ''*New [2]

    '' Current row for each category
    Dim cats As Dictionary
    Set cats = New Dictionary
    cats.Add "homework", 0
    cats.Add "beginner", 0
    cats.Add "advanced", 0

    '' Clear the category sheets  *New [2]
    For Each s In cats.Keys
        Range(s & "!A1").CurrentRegion.Delete
    Next s

    '' Find the source range
    Set srcRange = [all!a1].CurrentRegion
    srcCols = srcRange.Columns.Count

    '' Move rows from source Loop
    For Each srcRow In srcRange.Rows

        '' get the category
        srcCat = srcRow.Cells(4).Value

        '' get the target sheet row and increment it
        putRow = cats(srcCat) + 1
        cats(srcCat) = putRow

        '' format the target range string     *Fixed [1]
        '' e.g. "homework!A3:E3"
        putString = srcCat & "!" & _
            [a1].Offset(putRow - 1, 0).Address & _
            ":" & [a1].Offset(putRow - 1, srcCols - 1).Address

        '' copy from sheet all to target sheet
        Range(putString).Value = srcRow.Value
    Next srcRow
End Sub

暫無
暫無

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

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