遍历行和列以满足条件

时间:2012-12-11 10:57:54

标签: excel-vba vba excel

如果有人可以帮我解决这个问题,我会非常感激......

我想有一个excel宏,如果在sheet1的单元格b3中满足booth条件,则会通过sheet2的第一行和第一列返回值。 条件将在sheet1上指定;单元格b1将包含应搜索sheet2中的行的条件,单元格b2将包含应搜索sheet2中的列的条件。结果应复制到sheet1中的单元格b3中。

提前致谢

加成..............

我有这个子行,它遍历行并查找条件1(strDate)但我只是设法做到这一点是列是固定的。我应该添加一个计数器,它将通过列来满足条件2(strProduct)但我不

   Sub LookUpValuesRCC2()
'
Dim shtData     As Worksheet    ' Sheet containing data 
Dim shtOutput   As Worksheet    ' Output Sheet 
Dim strDate     As String       ' Date - condition 1
Dim strProduct  As String       ' Product - condition 2   
Dim i           As Integer      ' Counter in shtData Sheet
Dim j           As Integer      ' Counter in shtOutput Sheet
'
Set shtData = Worksheets("sheet2")
Set shtOutput = Worksheets("sheet1")
'
' Loop through "Data" Sheet Rows
For i = 1 To 1000

    strDate = shtData.Cells(i, 1)
    '
    ' Loop through dates in "Output" Sheet
    ' if date match then vrite values
    For j = 1 To shtOutput.Cells(Rows.Count, 14).End(xlUp).Row
        If shtOutput.Cells(j, 14) = strDate Then
            shtOutput.Cells(j, 2) = shtData.Cells(i, 18)

        End If
    Next j
Next i

End Sub

1 个答案:

答案 0 :(得分:0)

首先欢迎来到SO。其次,由于您的代码与您想要的描述不完全匹配,或者在我看来并不是这样做,因此不能100%清楚您的后续内容。

我根据您的描述所写的内容编写了以下代码,因为您拥有的代码并不是您想要的,所以无论如何我都认为它需要修改。

如果这不符合您的要求,请评论。

Sub LookUpValuesRCC2()

Dim shtData     As Worksheet    ' Sheet containing data
Dim shtOutput   As Worksheet    ' Output Sheet
Dim strDate     As Date       ' Date - condition 1
Dim strProduct  As String       ' Product - condition 2
Dim strResult As String         'result to print

Dim rngFound As range, rngFoundAgain As range

Set shtData = Worksheets("sheet2")
Set shtOutput = Worksheets("sheet1")

strDate = shtOutput.range("B1").Value
strProduct = shtOutput.range("B2").Value

strResult = "Nothing Found"

With shData

    'first look down the first column for the date
    Set rngFound = .Columns(1).Find(strDate, lookat:=xlWhole)

    If Not rngFound Is Nothing Then

        'if that is found, look for the product in the row with the date
        Set rngFoundAgain = rngFound.EntireRow.Find(strProduct, lookat:=xlWhole)

        If Not rngFoundAgain Is Nothing Then strResult = rngFoundAgain.Value

    End If

End With

shtData.range("B3") = strResult


End Sub