具有条件的自动填充细胞

时间:2011-03-25 14:01:32

标签: excel excel-vba cells autofill vba

我坚持使用代码。我承认我不是专业程序员,但尽管已经花了很多时间在互联网上搜索,但我无法构建代码。情况就是这样。

我有SheetB 2列(A和C)。在A列中,我有一堆ID号,并且总是有更多行具有相同的数字(例如:ID 12345在第6行到第15行)。对于每个ID号,C列中都有相应的日期。

在SheetA中,在Cell C4中我选择ID号,我想创建自动填充F(sheetA)列的代码,从第12行开始,所有可用日期都与SheetB中的ID匹配。

是的,有人能帮帮我吗?谢谢!

2 个答案:

答案 0 :(得分:0)

尝试在Sheet1代码中使用此代码...随时询问是否有不清楚的内容。

编辑:略微改变了清理程序。

Private Sub Worksheet_Change(ByVal Target As Range)

Dim oCell As Excel.Range
Dim oCellResult As Excel.Range
Dim oCellClean As Excel.Range
Dim oRangeID As Excel.Range
Dim iCellCount As Integer

If Target.Address = "$C$4" Then

    'Set source data
    Set oRangeID = Sheets(2).Range("A:A")

    'Define initial target for the results obtained
    Set oCellResult = Sheets(1).Range("F12")

    'Clear up any previous data
    'Set oCellClean = oCellResult
    'While Len(oCellClean.Value) > 0
    '    
    '    oCellClean.Clear
    '    Set oCellClean = oCellClean.Offset(1, 0)
    '    
    'Wend

    Set oCellClean = Range(oCellResult, oCellResult.End(xlDown))
    oCellClean.ClearContents

    'Scans source range for match data
    For Each oCell In oRangeID

        If oCell.Value = "" Then Exit For

        If oCell.Value = Target.Value Then

            oCellResult.Offset(iCellCount, 0).Value = oCell.Offset(0, 2).Value
            iCellCount = iCellCount + 1

        End If

    Next oCell

End If

End Sub

修改

更新了清理代码。检查它是否符合您的期望。

答案 1 :(得分:0)

试试这个:

Dim rgIDsAndDates As Range: Set rgIDsAndDates = Range("name")
Dim DATEs As Collection ' to collect date values for a given ID
Dim IDs   As Collection ' to collect all the DATEs collections for all IDs

' step 1: loop to create (initially empty) collections for each unique ID
Set IDs = New Collection
Dim rgRow As Range
For Each rgRow In rgIDsAndDates.Rows
    Set DATEs = New Collection
    On Error Resume Next
    ' the foll line will save an (empty) DATEs collection keyed by the ID
    Call IDs.Add(DATEs, CStr(rgRow.Cells(1, 1).Value))  ' col 1 as the ID
    On Error GoTo 0
Next rgRow

' step 2: loop to fill each DATEs collection with the dates for that ID
For Each rgRow In rgIDsAndDates.Rows
    ' the foll line retrieves the DATEs for the corresp ID
    Set DATEs = IDs(CStr(rgRow.Cells(1, 1).Value)) ' col 1 has the ID
    Call DATEs.Add(rgRow.Cells(1, 3).Value)        ' store the date from col 3
Next rgRow

' for testing ... list the dates for ID "123"
Set DATEs = IDs("123")
Dim dt As Variant
For Each dt In DATEs
    Debug.Print "date: " & dt
    ' put that dt where you want
Next dt