VBA:根据条件在单元格中显示数据

时间:2018-10-25 19:23:07

标签: excel vba

我在excel中有数百条显示资源数据的条目。我想创建一个带有一个按钮的excel工作表,单击该按钮将显示所选资源的数据。

这是excel工作表的一小段。

resource data should show here

我尝试了以下代码,但无法弄清楚如何在字段上显示

Dim FindEID As String
Dim Rng As Range

FindEID = Sheets("Sheet1").Range("D17").Value
If Trim(FindEID) <> "" Then
    With Sheets("Roster").Range("C:C")
        Set Rng = .Find(What:=FindEID, _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlValues, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
        If Not Rng Is Nothing Then
            Application.Goto Rng, True
        Else
            MsgBox "Nothing found"
        End If
    End With
End If
End Sub

1 个答案:

答案 0 :(得分:0)

所以我建议您做这样的事情。而不是使用.Find方法,您应该遍历C列并在找到时获取所需的数据。像这样:

Sub mySub()
    Dim cell As Range
    Dim strSearch As String
    Dim lastRow As Long
    Dim outputRowNum As Integer



    'This will speed things up a bit
    Application.ScreenUpdating = False


    strSearch = Sheets("Sheet1").Range("D17").Value 'grab our serach value (I assume its a string here)
    outputRowNum = 4 'first output row in Sheet1.D column is row 4

    'grab the last used row in the third column on Roster tab
    lastRow = ThisWorkbook.Worksheets("Roster").Cells(Worksheets("Roster").Rows.Count, 3).End(xlUp).Row

    For Each cell In ThisWorkbook.Worksheets("Roster").Range("C1:C" & lastRow)
        If cell.Value = strSearch Then
            'Here, we found a match, so grab all the data you need and print it
            'to the range you want...
            'There are many ways to do this, I just use the Offset method to move over to the next column

            Sheets("Sheet1").Range("D" & outputRowNum).Value = cell.Offset(0, 0) 'Column C
            outputRowNum = outputRowNum + 1

            Sheets("Sheet1").Range("D" & outputRowNum).Value = cell.Offset(0, 1) 'column D
            outputRowNum = outputRowNum + 1

            Sheets("Sheet1").Range("D" & outputRowNum).Value = cell.Offset(0, 5) 'column H
            outputRowNum = outputRowNum + 1

            'Note that you run the risk of overwriting the criteria that started out in
            'cell Sheet1!D17 if there are more than 4 matches. The code will still work,
            'you'll just lose that original value in D17.

        End If
    Next cell

    Application.ScreenUpdating = True
End Sub

有关要从中复制或打印到哪些单元格的更多信息,我可以对其进行更新以满足您的需求。