如何在Excel中search和显示数据到单元格?

有谁知道在Excel中显示search结果的代码? 目前,我的代码只search并突出显示我的数据,但我希望它显示在特定的单元格中。 我希望城市的search结果显示在单元格H5中,如http://postimg.org/image/xwhb021m3/

这是我现在的代码:

Sub search() Dim City As String, CellName As String City = InputBox("Please enter the city to start search", "Search Input") If City <> "" Then Range("B4").Select For Indx = 0 To G - 1 If ActiveCell.Offset(Indx, 0).Value = City Then CellName = "B" & LTrim(str(4 + Indx)) Range(CellName).Select Exit For End If Next Indx If Indx = G Then Beep MsgBox "The city was not found", , "Not Found" End If Else MsgBox "Search cannot start" & vbCrLf & _ "Because there is no input", , "Search Aborted" End If End Sub 

欢迎丹尼斯!

让用户input一个城市并寻找包括个案在内的精确匹配是无效的,但是无论如何,你可以做下面的代码(有更好的方法来search单元值)。 用你的方法(逐个检查值),理解下面的代码。

修改的代码也设置公式指向人口。

注意:您需要实现一个Sub来删除以前的search结果!

 Sub SearchCity() Dim sSearchFor As String, oRngResult As Range, oRngData As Range sSearchFor = Trim(InputBox("Please enter the city to start search", "Search Input")) If Len(sSearchFor) = 0 Then MsgBox "Search cannot start" & vbCrLf & "Because there is no input", vbExclamation, "Search Aborted" Exit Sub End If ' Initial cell locations Set oRngData = ActiveSheet.Range("B5") ' Data starts from this cell Set oRngResult = ActiveSheet.Range("H5") ' Results starts from this cell ' "Search" until cell is empty on the "data cell" Do Until IsEmpty(oRngData) ' Compare the data cell value with the typed string (convert to lowercase) If LCase(oRngData.Value) = LCase(sSearchFor) Then ' Exact spelling matched, store the address and move the results range to next row oRngResult.Value = Replace(oRngData.Address, "$", "") ' Cell Address for Population oRngResult.Offset(0,1).Formula = "=" & oRngData.Offset(0,3).Address ' 2012 Population column Set oRngResult = oRngResult.Offset(1, 0) End If Set oRngData = oRngData.Offset(1, 0) ' Move down to next row of data Loop Set oRngData = Nothing Set oRngResult = Nothing End Sub 

不要过头。 另一种Find Method是使用范围对象的Find Method

 Dim City As String City = InputBox("Please enter the city to start search", "Search Input") If City <> "" Then With Sheets("SheetName") ' Always try to be explicit Dim c As Range ' You adjust this part to suit Set c = .Range("B4").CurrentRegion.Find(City, , , xlWhole) If Not c Is Nothing Then .Range("H5").Value2 = c.Value2 ' Adjust Offset below to get the population column .Range("I5").Value2 = c.Offset(0, 1).Value2 Else MsgBox "The city was not found", , "Not Found" End If End With Else MsgBox "Search cannot start" & vbCrLf & _ "Because there is no input", , "Search Aborted" End If 

如果您使用内置的方法,它已经返回范围对象
然后,您可以在该对象上进行检索,更改或存储其值。