我想搜索一个包含名称列表的excel文件。所有名称都是随机排列的。我希望能够搜索诸如“Tom”之类的字符串,并返回获取所有附加数据的“Tom”字符串。因此,如果有一个包含500个名称的列表,并且Tom只有15个条目,我希望公式拉出所有15个条目并将它们输出到电子表格的另一个区域。此外,是否可以执行此操作,然后还返回与“Tom”关联的所有列以完成整个行条目?提前谢谢。
答案 0 :(得分:1)
这是一个简单的宏来显示输入框,并过滤和复制与输入到新工作表上的值相匹配的数据。
Public Sub sortAndCopy()
Dim rngFilterRange As Range
Dim strSearchString As String
Dim wsTargetSheet As Worksheet
'change this to refer to the sheet that contains the data
Set rngFilterRange = ThisWorkbook.Sheets("Data").UsedRange
'prompt for string to filter by
strSearchString = Application.InputBox("Enter value to search for")
With rngFilterRange
'filter data range - assumes data is in column 1, but change the field if necessary
.AutoFilter Field:=1, Criteria1:=strSearchString
'creates a new sheet and copies the filtered data -
'change this to refer to the range you require the data to be copied to
.Copy Destination:=ThisWorkbook.Sheets.Add.Range("A1")
'turn off filters
.Parent.ShowAllData
.Parent.AutoFilterMode = False
End With
End Sub
答案 1 :(得分:0)
您可以使用ADO:
Dim cn As Object
Dim rs As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Dim s As String
Dim i As Integer, j As Integer
''This is not the best way to refer to the workbook
''you want, but it is very convenient for notes
''It is probably best to use the name of the workbook.
strFile = ActiveWorkbook.FullName
''Note that if HDR=No, F1,F2 etc are used for column names,
''if HDR=Yes, the names in the first row of the range
''can be used.
''This is the Jet 4 connection string, you can get more
''here : http://www.connectionstrings.com/excel
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
''Late binding, so no reference is needed
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
strSQL = "SELECT * " _
& "FROM [Sheet1$] " _
& "WHERE MyField ='Tom' "
rs.Open strSQL, cn, 3, 3
''You can iterate through the fields here if you want headers
''Pick a suitable empty worksheet for the results
Worksheets("Sheet3").Cells(2, 1).CopyFromRecordset rs
''Tidy up
rs.Close
Set rs=Nothing
cn.Close
Set cn=Nothing
答案 2 :(得分:0)
要查看此数据,您只需对数据应用过滤器,然后从名称列中选择名称。无需以这种方式复制数据。
要获取数据的副本,请正常复制粘贴(隐藏的行不会被复制)
要自动执行,请编写Sub
以重复这些步骤。