Error 5018 vba

I just wrote my first VBA script for Excel because I have to write many "*.txt" files from a folder into an excel spreadsheet. But when I run this script, I get the error '5018'. It is invoked by the

I just wrote my first VBA script for Excel because I have to write many «*.txt» files from a folder into an excel spreadsheet. But when I run this script, I get the error ‘5018’. It is invoked by the line

If reg.Test(file.Name) Then

Any idea what I am doing wrong? Here is the complete script:

Sub get_filenames()
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set Files = fso.GetFolder("C:myfolder").Files
    Set reg = CreateObject("vbscript.regexp")

    reg.IgnoreCase = True
    reg.MultiLine = False
    reg.Pattern = "*.txt"

    For Each file In Files
        If reg.Test(file.Name) Then
            i = i + 1
            Cells(i, 1) = file.Name
        End If        
    Next
End Sub

warren's user avatar

warren

9,78023 gold badges84 silver badges144 bronze badges

asked Oct 29, 2009 at 10:45

Lucas's user avatar

Just fixed it. Apparently my regular expression is wrong. 5018 stands for «Unexpected quantifier in regular expression». So I changed it to

reg.Pattern = "^.+.txt$"

answered Oct 29, 2009 at 10:54

Lucas's user avatar

LucasLucas

7194 gold badges13 silver badges26 bronze badges

3

Im trying to extract size from product details by using the below REGEX..

With rgx
    .Global = True
    .MultiLine = False
    .Pattern = "([0-9.,*?/]+{1,5}s*(g|G|ML|ml|mL|Ml|oz|OZ|Oz|ea|s+)){1,3}"
    
    Set temp = .Execute(Rng)

However, while executing the regex im facing 5018 error in line Set temp = .Execute(Rng)
Why im getting this error anything wrong in h eregex?

asked Apr 1, 2021 at 7:50

Linga's user avatar

9

As noted in this post, 5018 stands for «Unexpected quantifier in regular expression».

Look at [0-9.,*?/]+{1,5} where there is +{1,5}, two quantifiers at a row.

In VBA regex this is an error.

If you match 1 to 5 characters belonging to the [0-9.,*?/] set, use [0-9.,*?/]{1,5}.

If you match one or more, use [0-9.,*?/]+.

Do not chain quantifiers.

answered Apr 1, 2021 at 21:40

Ryszard Czech's user avatar

Ryszard CzechRyszard Czech

17.7k3 gold badges22 silver badges37 bronze badges

2

Как отмечено в эта почта, 5018 означает «Неожиданный квантификатор в регулярном выражении».

Посмотрите на [0-9.,*?/]+{1,5}, где есть +{1,5}, два квантификатора подряд.

В регулярном выражении VBA это ошибка.

Если вы соответствуете от 1 до 5 символов, принадлежащих набору [0-9.,*?/], используйте [0-9.,*?/]{1,5}.

Если вы соответствуете одному или нескольким, используйте [0-9.,*?/]+.

Не связывайте кванторы в цепочку.

Спасибо за подробное объяснение. Одно уточнение, если я хочу зафиксировать размер, где 100 мл + 20 мл, что может быть для него шаблоном (регулярным выражением)?


— Linga

02.04.2021 08:34

@Linga Ваше выражение выглядит хорошо, обратите внимание, как извлечь все совпадения в stackoverflow.com/questions/44979363/…. Выражение вроде (d+(?:[,.]d+)*)s*(g|G|ML|ml|mL|Ml|oz|OZ|Oz|ea) может сработать для вас.


— Ryszard Czech

02.04.2021 20:13

Хорошо, я пытался понять это, но, поскольку я новичок в регулярных выражениях, я был менее чем успешным. Моя цель здесь состоит в том, чтобы создать совпадение, сравнивающее одну строку с другой, которая может быть намного больше или того же размера, что и предыдущая строка. Это совпадение должно происходить только в том случае, если первая строка 1. является нечувствительным к регистру совпадением с какой-либо частью другой строки, 2. строка, успешно совпавшая с другой строкой, должна быть отдельным словом или фразой, а не частью другого слова, что означает он начинается либо с начала строки, либо с пробела и заканчивается концом строки или с пробелом. Любая помощь от опытного пользователя регулярных выражений будет приветствоваться.

'this yields : run time error 5018 = Unexpected quantifier in regular expression
RegExPattern = "(b|^)?" + "[" + ColumnArr(PhraseCt) + "]" + "(b|[ ])?)" 
With RegEx
     .MultiLine = False
     .Global = True
     .IgnoreCase = False
     .Pattern = RegExPattern
End With
Set Matches = RegEx.Execute(SearchTerm)

  • #1

Why the following is not giving the desired result:

msgbox replace(«The Date is 05-02-2015″,»??-??-????»,format(Date,»dd-mm-yyyy»))

How to achieve that in VBA?

  • #2

What do you want the MsgBox to actually show? Replace function will try to find «??-??-????» in the String «The Date is 05-02-2015», if found will replace it with 05-02-2015

In the example you have given the ??-??-???? is not found, so no replacement takes place.

  • #4

Paul. I want to use a Pattern Matching here. Not possible?

jdraw


  • #7

Hi Paul and jd,
Thank you for referring that. I believe it will be a new thing that I (must) learn. Anyway just want to confirm: Actually the pattern matching is working in the VBE Editor manually when you search and replace but not through code. Can I take it as a confirmation that when we want to use pattern search and replace (using regEx) we can achieve it only through using the VB Script reference. Right?

Thanks in Advance…

Regards,
Prabhakaran

jdraw


  • #8

You need a reference as in the attached.

  • RegexReference.jpg

    RegexReference.jpg

    46.1 KB · Views: 117

  • #9

Why am I getting the following error?
Run-time error ‘5018’:
Method ‘Test’ of object ‘IRegExp2’ failed

in the following code:

Sub RegEx()
Dim myregex As New RegExp
With myregex
.Pattern = «??-???-????»
.IgnoreCase = False
.Global = False
End With
MsgBox myregex.Test(«Date is: 15-Jan-2015»)
End Sub

How to replace that 15-Jan-2015 with current date 09-Feb-2015 using a pattern match?

  • #10

Your patter is wrong. You have to specify the pattern.

Code:

Sub RegEx()
    Dim myregex [COLOR=Red][B]As RegExp[/B][/COLOR]
    Set myregex = New RegExp
    With myregex
        .Pattern = "((0[1-9]|[12][0-9]|3[01])[-][A-Z][a-z][a-z])[-](19|20)[0-9]{2}"
        [COLOR=Green]'Use the Following if it is Numeric month.
        '.Pattern = "((0[1-9]|[12][0-9]|3[01])[-]0[1-9]|1[012])[-](19|20)[0-9]{2}"[/COLOR]
        .Global = False
    End With
    MsgBox myregex.Replace("Date is: 15-Jan-2015", Format(Date, "dd-mmm-yyyy"))
End Sub

  • #11

Code:

MsgBox "The Date is " & CStr(format(CDate(Right("The Date is 05-02-2015", 10)), "dd-mm-yyyy"))

Something like this?

  • #12

Hi Paul. Thanks for your pattern. How to modify this pattern to pick for both:

02-Jan-2015
and
2-Jan-2015

I know we have to add/modify this: (0[1-9]|[12][0-9]|3[01]) but how? Thanks in advance.

  • #13

[1-9]|0[1-9]

Solved my purpose.

Хорошо, я пытался понять это, но, будучи довольно новым для Регулярных выражений, я был менее успешным. Моя цель состоит в том, чтобы создать сопоставление одной строки с другой, которая может быть намного больше или того же размера, что и прежняя строка. Это совпадение должно происходить только в том случае, если первая строка 1. является нечувствительной к регистру совпадением с некоторой частью другой строки, 2. строка, успешно совпадающая с другой, должна быть отдельным словом или фразой, а не частью другого слова, что означает это ведет либо начало строки, либо пробел и заканчивается концом строки или пробела. Любая помощь от опытного пользователя регулярного выражения была бы очень желанной.

'this yields : run time error 5018 = Unexpected quantifier in regular expression
RegExPattern = "(b|^)?" + "[" + ColumnArr(PhraseCt) + "]" + "(b|[ ])?)"
With RegEx
.MultiLine = False
.Global = True
.IgnoreCase = False
.Pattern = RegExPattern
End With
Set Matches = RegEx.Execute(SearchTerm)

Понравилась статья? Поделить с друзьями:
  • Error 412 что это значит
  • Error 501 на котле аристон ошибка
  • Error 412 precondition failed
  • Error 4109 mql4
  • Error 501 photoshop