您的位置:首页 > 汽车 > 新车 > EXCEL跨文件查询,指定条件列,返回满足条件的指定列

EXCEL跨文件查询,指定条件列,返回满足条件的指定列

2024/11/13 9:46:52 来源:https://blog.csdn.net/VB973490770/article/details/141274978  浏览:    关键词:EXCEL跨文件查询,指定条件列,返回满足条件的指定列

EXCEL跨文件查询,指定条件列,返回满足条件的指定列

Private Sub cmd_find_from_workbooks_Click()
Dim S_Cols As String, thePath As String, Sor_Col As Integer, sz_Cols As Variant
S_Cols = T_jieguo_cols.Text
sz_Cols = Split(S_Cols, ",")
thePath = T_path.Text
Sor_Col = T_Search_Col_No.Text
InsertColumnToRightByIndex T_Search_Col_No.Text, UBound(sz_Cols) + 1 '右侧插入列Sub_FindFromWorkbooks Sor_Col, T_Search_ROW_Str.Text, thePath, S_ColsEnd SubSub Sub_FindFromWorkbooks(ByVal Sor_Col As Integer, ByVal str_ROW As Integer, ByVal mubiao_Path As String, ByVal return_Cols As String)'跨文件查询数据Dim SourceWorkbook As WorkbookDim TargetWorkbook As WorkbookDim SourceSheet As WorksheetDim TargetSheets As Object, TargetSheet As ObjectDim FoundRange As RangeDim SearchValue As String, SearchPath As StringDim rng As RangeDim cell As RangeDim last_Row_No As LongDim sz_Cols As VariantDim i%, j%, i_s$' 设置源工作簿和工作表Set SourceWorkbook = ThisWorkbook ' 当前打开的工作簿Set SourceSheet = SourceWorkbook.ActiveSheet ' 源工作表' 设置目标工作簿和工作表'SearchPath = "F:\F\20240529-贝达项目\001-清单\001-02-弱电清单\搜索网线标签.xls"SearchPath = mubiao_PathSet TargetWorkbook = Workbooks.Open(SearchPath)last_Row_No = SourceSheet.UsedRange.Rows.Count + SourceSheet.UsedRange.Row - 1 '最后一行sz_Cols = Split(return_Cols, ",")For i = str_ROW To last_Row_Noi_s = SourceSheet.Cells(i, Sor_Col).Value' 设置要搜索的值SearchValue = i_s   ' 获取搜索值Set TargetSheets = TargetWorkbook.Worksheets' 遍历目标工作簿中的所有工作表For Each TargetSheet In TargetSheets' 遍历工作表中的所有单元格Set rng = TargetSheet.UsedRangeFor Each cell In rngIf InStr(1, cell.Value, SearchValue, vbTextCompare) > 0 And InStr(1, TargetSheet.Name, "内容", vbTextCompare) > 0 Then' 如果找到了匹配项,则输出旁边的单元格值'MsgBox "Found in " & TargetSheet.Name & ": " & cell.Offset(0, 1).Value'MsgBox TargetSheet.NameFor j = LBound(sz_Cols) To UBound(sz_Cols)'输出sheet名称,和所需要的列的内容。Select Case jCase Is = 0SourceSheet.Cells(i, Sor_Col + j + 1).Value = TargetSheet.Name & "--" & cell.Row - 1Case ElseSourceSheet.Cells(i, Sor_Col + j + 1).Value = cell.ValueEnd SelectNext jExit For ' 可选:如果只需要找到第一个匹配项End IfNext cellNext TargetSheetNext i' 关闭目标工作簿(可选)TargetWorkbook.Close SaveChanges:=False
End SubSub GetLastRowUsedRange()
'获得有效行数Dim ws As WorksheetSet ws = ThisWorkbook.ActiveSheetDim lastRowUsedRange As LonglastRowUsedRange = ws.UsedRange.Rows.Count + ws.UsedRange.Row - 1 ' UsedRange的Row属性给出的是范围的第一行的行号MsgBox "The last row with data in the used range is: " & lastRowUsedRange
End Sub

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com