gpt4 book ai didi

regex - Excel VBA + 正则表达式

转载 作者:行者123 更新时间:2023-12-02 09:42:28 25 4
gpt4 key购买 nike

好的,开始吧。我对 VBA 有点生疏,自从我需要使用它以来已经 3 年多了。

简而言之,我正在努力从字符串中提取文本。我使用正则表达式从该字符串中提取我的部门名称和日期。

该部门总是介于 : 和 - 之间。

出于安全原因,我无法共享该文档。但是,我可以解释这种格式,希望我们可以以此为基础开展工作。

A栏----B栏----C栏----D栏

日期(e)--部门(e)--字符串--持续时间

其中(e)表示它是从字符串中提取的。

String Example

到目前为止,我的提取代码如下。目前,它将循环遍历所有可用行并提取部门,但它总是带有 : 和 - !我似乎无法找到一种方法来消除这些。

有什么帮助吗?

我最终可能可以算出日期。

此代码的最终输出是“: Inbound Contacts -”在我需要的地方,“入站联系人”。

Sub stringSearch()
Dim ws As Worksheet
Dim lastRow As Long, x As Long
Dim matches As Variant, match As Variant
Dim Reg_Exp As Object

Set Reg_Exp = CreateObject("vbscript.regexp")

Reg_Exp.Pattern = "\:\s(\w.+)\s\-"


Set ws = Sheet2

lastRow = ws.Range("C" & Rows.Count).End(xlUp).Row

For x = 1 To lastRow
Set matches = Reg_Exp.Execute(CStr(ws.Range("C" & x).Value))
If matches.Count > 0 Then
For Each match In matches
ws.Range("B" & x).Value = match.Value
Next match
End If
Next x
End Sub

最佳答案

这就是如何在没有 的情况下实现你想要的东西,一般来说它应该更快一些并且更容易理解:

Sub TestMe()

Dim inputString As String
inputString = "Planning Unit: Inbound Contacts = Tuesday, 27/03/2018"
Debug.Print Split(Split(inputString, ":")(1), "=")(0)

End Sub
  • inputString 分割为 : 并获取第二部分;
  • 将取出的部分用=分割并取出第一部分;

关于regex - Excel VBA + 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49554429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com