簡體   English   中英

在 VBA 中搜索單元格文本並將文本復制到另一個單元格?

[英]Search cell for text and copy text to another cell in VBA?

我有一列,其中包含帶有參數的行。 例如

W2 = [生產][FO][2.0][客戶]

W3 = [生產][GD][1.0][P3]

W4 = 客戶的生產問題

我有一個將其他列復制到另一個工作表的功能,但是對於此列,我需要執行以下操作

  • 搜索單元格並查找 [P*]
  • 星號代表 1 到 5 之間的數字
  • 如果找到 [P*],則將 P* 復制到第 4 列中的“計算”表
  • 基本上,從單元格中刪除所有內容,除了有方括號的地方,然后是 P、數字和方括號

有誰知道我怎么能做到這一點? 或者,可能更容易復制該列,然后刪除不符合上述條件的所有內容。

第二次編輯:

我在這里編輯以使用正則表達式而不是循環。 這可能是實現目標的最有效方法。 請參閱下文,讓我們知道它是否適合您:

Function MatchWithRegex(sInput As String) As String
    Dim oReg As Object
    Dim sOutput As String

    Set oReg = CreateObject("VBScript.RegExp")

    With oReg
        .Pattern = "[[](P[1-5])[]]"
    End With

    If oReg.test(sInput) Then
        sOutput = oReg.Execute(sInput)(0).Submatches(0)
    Else
        sOutput = ""
    End If

    MatchWithRegex = sOutput
End Function

Sub test2()
    Dim a As String

    a = MatchWithRegex(Range("A1").Value)


    If a = vbNullString Then
        MsgBox "None"
    Else
        MsgBox MatchWithRegex(Range("A1").Value)
    End If
End Sub

第一次編輯:

我的解決方案如下。 我會編寫一個函數,首先測試字符串中是否存在 Pattern,如果存在,我會根據括號對其進行拆分,並選擇與模式匹配的括號。 讓我知道這是否適合您。

Function ExtractPNumber(sInput As String) As String
    Dim aValues
    Dim sOutput As String

    sOutput = ""
    If sInput Like "*[[]P[1-5][]]*" Then
        aValues = Split(sInput, "[")
        For Each aVal In aValues
            If aVal Like "P[1-5][]]*" Then
                sOutput = aVal
            End If
        Next aVal
    End If

    ExtractPNumber = Left(sOutput, 2)
End Function


Sub TestFunction()
    Dim sPValue As String

    sPValue = ExtractPNumber(Range("A2").Value)

    If sPValue = vbNullString Then
        'Do nothing or input whatever business logic you want
    Else
        Sheet2.Range("A1").Value = sPValue
    End If
End Sub

舊帖子:

在 VBA 中,您可以使用帶有模式的Like運算符來表示開括號、字母 P、1-5 之間的任何數字,然后使用以下語法表示閉括號:

Range("A1").Value LIke "*[[]P[1-5][]]*"

編輯:修復了錯誤的解決方案

如果你對空格沒問題並且不在乎 *>5,我會這樣做並復制第 4 列:

=IF(ISNUMBER(SEARCH("[P?]",FirstSheet!$W2)), FirstSheet!$W2, "")

需要注意的重要事項:

  • ? 是單個字符的通配符; 如果您可以在該位置使用多個字符,則可以使用 *
  • 如果找到將顯示單元格的原始值,否則留空

之后,您可以突出顯示該列並根據需要刪除空白。 或者,您可以用占位符字符串替換空白。

如果 * 必須是 1-5,則分別使用兩列 E 和 D:

=MID(FirstSheet!$W2,SEARCH("[P",FirstSheet!$W2)+2,1)
=IF(AND(ISNUMBER($E2),$E2>0,$E2<=5,MID($W2,SEARCH("[P",FirstSheet!$W2)+3,1))), FirstSheet!$W2, "")

其中 FirstSheet 是初始工作表的名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM