|
|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
- Sub FilterDataByCode()
- Dim wsData As Worksheet, wsResult As Worksheet
- Dim dataArray As Variant
- Dim searchCode As String
- Dim i As Long, j As Long, matchCount As Long
- Dim lastRow As Long, lastCol As Long
-
- ' 设置工作表对象
- Set wsData = ThisWorkbook.Worksheets("数据")
- Set wsResult = ThisWorkbook.Worksheets("结果")
-
- ' 获取查询编码(转换为字符串防止类型不匹配)
- searchCode = CStr(wsResult.Range("B1").Value)
-
- ' 获取数据表最后一行和列数
- lastRow = wsData.Cells(wsData.Rows.Count, "A").End(xlUp).Row
- lastCol = wsData.Cells(1, wsData.Columns.Count).End(xlToLeft).Column
-
- ' 将数据读入数组
- dataArray = wsData.Range("A1").Resize(lastRow, lastCol).Value
-
-
- matchCount = 0
- For i = 2 To UBound(dataArray, 1) ' 假设第一行为标题
- If CStr(dataArray(i, 1)) = searchCode Then
- matchCount = matchCount + 1
- For j = 1 To UBound(dataArray, 2)
- dataArray(matchCount, j) = dataArray(i, j)
- Next j
- End If
- Next i
-
- If matchCount = 0 Then
- MsgBox "未找到编码:" & searchCode, vbInformation
- Exit Sub
- End If
-
-
- ' 清除旧数据并输出结果
- With wsResult
- ' 清除A10及以下所有数据
- .Range("A10").Resize(.Rows.Count - 9, lastCol).ClearContents
- ' 输出结果数组
- .Range("A10").Resize(matchCount, UBound(dataArray, 2)).Value = dataArray
- End With
-
- MsgBox "已找到 " & matchCount - 1 & " 条匹配记录", vbInformation
- End Sub
复制代码 |
|