.

iT邦幫忙

0

VBA 抓取特定關鍵字對應DATA

vba
  • 分享至 

  • xImage

我需要從Excel 的表格裡、在幾千筆資料抓取特定資訊的對應的data,但data沒有統一的邏輯位置。

舉例: 我要抓取Vis的對應data

SPEC1. (要抓出862)
Vis Pa-sec 862

SPEC2. (要抓出37 - 40 )

  • Vis @ 100 rpm: 37 - 40 cPs

SPEC3. (要抓出50 )
Vis (23°C) Pa•s {P} 50 {50}

我是否只能先搜尋"Vis",撈出整列,之後再人工篩出對應的data,無法使用VBA全部自動帶出了?

joy99814 iT邦新手 5 級 ‧ 2025-03-17 17:07:03 檢舉
Sub ExtractVisData()
Dim ws As Worksheet
Dim rng As Range, cell As Range
Dim lastRow As Long
Dim regex As Object
Dim matches As Object
Dim outputRow As Integer

' 設定工作表
Set ws = ActiveSheet
lastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row ' 找到最後一行
outputRow = 2 ' 結果輸出起始行

' 建立正則表達式物件
Set regex = CreateObject("VBScript.RegExp")
regex.Global = True
regex.IgnoreCase = True
regex.Pattern = "\d+(\.\d+)?"

' 搜尋 "Vis" 並擷取數字
For Each cell In ws.Range("A1:A" & lastRow) ' 假設資料在 A 欄
If InStr(1, cell.Value, "Vis", vbTextCompare) > 0 Then
' 使用正則表達式提取數字
Set matches = regex.Execute(cell.Value)
If matches.Count > 0 Then
ws.Cells(outputRow, 2).Value = matches(0) ' 儲存第一個找到的數字
outputRow = outputRow + 1
End If
End If
Next cell

' 清除物件
Set regex = Nothing
MsgBox "提取完成,請檢查 B 欄的結果!", vbInformation
End Sub
.

尚未有邦友回答

立即登入回答