I am stuck - I feel I have checked everything multiple times but I need some pair of fresh eyes on this one:
Sub shopNumConvert()
Call settings
Dim SearchString As String
Dim ReplaceString As String
Dim InputString As String
Dim ShopRange As Range
'Dim RegEx As New RegExp
Dim RegEx As RegExp
SearchString = "[^a-z]{2}"
ReplaceString = "0\\1"
Set ShopRange = DataWs.Range("G2:G10")
Set RegEx = New RegExp
For Each cell In ShopRange
If SearchString <> "" Then
InputString = cell.Value
With RegEx
.Global = True
.IgnoreCase = False
.MultiLine = True
.Pattern = SearchString
End With
If RegEx.Test(InputString) Then
ShopRange.Value = (RegEx.Replace(InputString, ReplaceString))
End If
End If
Next
Set RegEx = Nothing
End Sub
Why do I get the error message Object variable or With block variable not set
In settings() I have defined which sheet 'DataWs' is
Help is much appreciated!
Thank you for your comments (and good practice advise - not working with VBA frequently so I am learning on the go)!
The problem was indeed with DataWs and I had to change something in settings() - the code as posted now runs without throwing an error - I will however look at a few of your comments and see how to incorporate those for improving the code.
Best,
Janine
Related
I'm having trouble using regular expressions in Google Docs to delete periods at the end of every line.
I tried importing the text into Microsoft Word but I don't know how to make the macro. All I have is this code:
Sub doRegexFindReplace()
Dim objRegex As RegExp
Dim matches As MatchCollection
Dim fnd As Match
Dim strSample As String
strSample = "First product code is fox 12, second one is fox 22, and third product is fox 45."
Set objRegex = New RegExp
With objRegex
.Pattern = "(fox) (\d+)"
.Global = True
.IgnoreCase = True
strSample = .Replace(strSample, "$1$2")
End With
Debug.Print strSample
End Sub
It might be too complex to figure out. That's ok if it is.
The regex for a trailing period would be \.$ Now I don’t know if that will work in Google Docs. The \ is the escaping character, which you need because in the RegEx world . is a reserved keyword. The $ means end of line.
Cannot figure out how to implement the following use case.
I pass a folder and criterias (seperated by a ";") to a function and retrieve a file if criterias were matched.
This is working quite well, but I have an exception:
If the criteria pattern in the first position is "ABC", there are multiple files which could match the search pattern.
My goal is to prioritize the finding in a sense that a file containing "RD_" should have a higher prioritization than a file which contains the string "SD_".
Hint:
If a file has the string "RD_" inside and matches also the other criterias, then the function can stop.
If a file has the string "SD_" inside and matches also the other criterias, then the function should not stop and still loop all files within the folder and try to find a file matching all criterias AND "RD_".
Hope you can help me further.
Sub getTargetFile()
Debug.Print getInputFilePath("D:\", "ABC;11111")
End Sub
Function getInputFilePath(inputDirectoryToScanForFile, filenameCriteria) As String
Dim vSplitCriteria: vSplitCriteria = Split(filenameCriteria, ";") ' Split the criteria into pieces and put them into an array
Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Dim i As Integer
Dim sFoundFile As String
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(inputDirectoryToScanForFile)
Dim blnCorrectFiles As Boolean
For Each oFile In oFolder.Files ' Loop through each file in folder
blnCorrectFiles = True ' assume the current file is correct
'Debug.Print oFile.Name
For i = LBound(vSplitCriteria) To UBound(vSplitCriteria) ' Loop through all file name criteria
If Not InStr(1, UCase(oFile.Name), UCase(vSplitCriteria(i))) > 0 Then ' check whether criteia matched
blnCorrectFiles = False
End If
If blnCorrectFiles = False Then Exit For
Next i
If blnCorrectFiles = True Then ' if all criteria are matched, otherwise it was set to false inbetween the above loop
sFoundFile = oFile.Name
Exit For
End If
Next oFile
If blnCorrectFiles = True Then
getInputFilePath = inputDirectoryToScanForFile & sFoundFile
Else
getInputFilePath = ""
End If
End Function
It sounds like you want to check for RD_ first and then if nothing is found, check for SD_. Which sounds like you just need to run the function twice. Trying to mix and match inside the function would be difficult to generalize and only make things messy.
Sub Prioritize()
Dim Directory As String
Directory = "D:\"
Dim Criteria As String
Criteria = "ABC;11111"
Dim fPath As String
fPath = getInputFilePath(Directory, "RD_;" & Criteria)
If fPath = "" Then fPath = getInputFilePath(Directory, "SD_;" & Criteria)
End Sub
I am currently facing an issue when trying to set a public variable through an VBscript in an Custom Action.
Its regarding the Property "MYDOMAIN".
No matter what I am doing, the value is always 0.
Even setting an ";" after (example) Session.Property("MYDOMAIN")="1" does not solve the issue.
When the VBScript is executed locally the value can be retrieved (at least in the variable).
Please find my script below:
'~~~ Query My Domain
Option Explicit
'On Error Resume Next
Dim objWMISvc : Set objWMISvc = GetObject( "winmgmts:\\.\root\cimv2" )
Dim colItems : Set colItems = objWMISvc.ExecQuery( "Select * from Win32_ComputerSystem" )
Dim objSysInfo : Set objSysInfo = CreateObject("ADSystemInfo")
Dim objComp : Set objComp = GetObject("LDAP://" & objSysInfo.ComputerName)
Dim objCompDN : objCompDN = objComp.distinguishedName
Dim objItem
Dim strComputerDomain
Dim Session
For Each objItem in colItems
strComputerDomain = objItem.Domain
' If objItem.PartOfDomain Then
' WScript.Echo "Computer Domain: " & strComputerDomain
' Wscript.Echo "Computername: " & strComputerName
' End If
Next
If strComputerDomain = "DOMAIN1.loc" Then
Session.Property("MYDOMAIN")="1"
elseif strComputerDomain = "DOMAIN2.loc" Then
call CheckIRL(objCompDN,"(?:Division-)(8[0-9]\d{1,2}|982)-")
elseif strComputerDomain = "DOMAIN3.loc" Then
Session.Property("MYDOMAIN")="3"
Else
if strComputerDomain = "" then
Session.Property("MYDOMAIN")="0"
End if
End if
Sub CheckIRL(strReturnValue, strPattern)
Dim objRegEx : set objRegex = new RegExp
objRegex.pattern = strPattern
objRegex.global = true
If objRegex.Test( strReturnValue ) Then
Session.Property("MYDOMAIN") = "6"
Else
Session.Property("MYDOMAIN") = "7"
End If
End Sub
Sub CheckSLO(strReturnValue, strPattern)
Dim objRegEx : set objRegex = new RegExp
objRegex.pattern = strPattern
objRegex.global = true
If objRegex.Test( strReturnValue ) Then
Session.Property("MYDOMAIN") = "4"
Else
Session.Property("MYDOMAIN") = "5"
End If
End Sub
To be honest: I am out of ideas...
A friend inserted the script into an InstallShield project and the Property could be resolved. Any idea is appreciated :)
I would recommend you trying to debug your VBS action code by inserting a message box (MsgBox function) in each of your IF block of your VBS code. This is just to make sure your VBS code do indeed set the related property to a value different than 0 before it exits.
Just use a MsgBox statement like this:
MsgBox Session.Property("MYDOMAIN")
to display the property value.
Then if the VBS do indeed set the property to a value different than 0 before exiting, in this case we will need more details about the exact execution sequence when the property is reverted back to 0.
I will give this a try and will come back to you once checked.
In the meantime I created a second msi file to do the config...not the best solution but it seems to work :)
My code:
Public Sub splitUpRegexPattern()
Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String
Dim Myrange As Range
Set Myrange = ActiveSheet.Range("B2:B4279")
For Each c In Myrange
strPattern = "([A-Z]{2}\/[A-Z]{2}\/[A-Z][0-9]{2}\/[a-z]{3}[0-9]{9}\/)([0-9]{4})"
If strPattern <> "" Then
strInput = c.Value
strReplace = "$1"
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.test(strInput) Then
c.Offset(0, 1) = regEx.Replace(strInput, "$2")
Else
c.Offset(0, 1) = ""
End If
End If
Next
End Sub
It was initially working well, it would give me an error, but still complete the task it was doing. But when I use this macro on a new spreadsheet, it gives me the error:
Compile Error: Method or Data Member not found.
All the solutions on this site are tailored to different situations, so I couldn't apply them to my circumstance unfortunately.
I have no idea why this is happening, as I haven't changed any of the code. I am sure if I had a greater understanding with VBA script that I would be able to understand this, but I do not, so I came to find out if someone here could help me!
Thanks!
Aydan
You need to add a reference to a library called "Microsoft VBScript Regular Expressions 5.5" to make it work.
If this code works in a workbook that simply means you have added that library reference and when you copy the code to a new workbook there you will need to add the same reference again.
In the existing code you are auto instantiating the variable called redEx which assumes that the library reference has been already added to make it work properly.
To avoid this, you may use the late binding technique which will not require you to add the reference and the code will work on any workbook.
To do so declare the regEx variable as an Object like below...
Dim regEx As Object
Set regEx = CreateObject("VBScript.RegExp")
My best guess is that you've lost a reference to a library. In VBE, select Tools - References. Find Microsoft VBScript Regular Expressions 5.5 and tick it.
Is there any SQL equivalent of "%" sign in VBA?
I need to return a few files just with some characters in the middle.
Help really appreciated!
For instance here is my code: I need to download all file that has in the name 2013 from that webpage and save and call them differently. Is this mission possible?
Sub Sample()
Dim strURL As String
Dim strPath As String
Dim i As Integer
strURL = "http://cetatenie.just.ro/wp-content/uploads/Ordin-********.2013.pdf"
strPath = "C:\Documents and Settings\ee28118\Desktop\178.pdf"
Ret = URLDownloadToFile(0, strURL, strPath, 0, 0)
If Ret = 0 Then
MsgBox "File successfully downloaded"
Else
MsgBox "Unable to download the file"
End If
End Sub
You can use the Like Operator.
Characters in pattern Matches in string
? Any single character.
* Zero or more characters.
# Any single digit (0–9).
[charlist] Any single character in charlist.
[!charlist] Any single character not in charlist
Example :
Dim MyCheck
MyCheck = "aBBBa" Like "a*a" ' Returns True.
MyCheck = "F" Like "[A-Z]" ' Returns True.
MyCheck = "F" Like "[!A-Z]" ' Returns False.
MyCheck = "a2a" Like "a#a" ' Returns True.
MyCheck = "aM5b" Like "a[L-P]#[!c-e]" ' Returns True.
MyCheck = "BAT123khg" Like "B?T*" ' Returns True.
MyCheck = "CAT123khg" Like "B?T*" ' Returns False.
When you navigate to the uploads folder, you get a directory listing of all the files in it. You can loop through the hyperlinks on that listing and test each to see if it meets your criterion and, if so, download it. You need a reference to MSXML and MSHTML. Here's an example.
Sub Sample()
Dim sUrl As String
Dim xHttp As MSXML2.XMLHTTP
Dim hDoc As MSHTML.HTMLDocument
Dim hAnchor As MSHTML.HTMLAnchorElement
Dim Ret As Long
Dim sPath As String
Dim i As Long
sPath = "C:\Documents and Settings\ee28118\Desktop\"
sUrl = "http://cetatenie.just.ro/wp-content/uploads/"
'Get the directory listing
Set xHttp = New MSXML2.XMLHTTP
xHttp.Open "GET", sUrl
xHttp.send
'Wait for the page to load
Do Until xHttp.readyState = 4
DoEvents
Loop
'Put the page in an HTML document
Set hDoc = New MSHTML.HTMLDocument
hDoc.body.innerHTML = xHttp.responseText
'Loop through the hyperlinks on the directory listing
For i = 0 To hDoc.getElementsByTagName("a").Length - 1
Set hAnchor = hDoc.getElementsByTagName("a").Item(i)
'test the pathname to see if it matches your pattern
If hAnchor.pathname Like "Ordin-*.2013.pdf" Then
Ret = UrlDownloadToFile(0, sUrl & hAnchor.pathname, sPath, 0, 0)
If Ret = 0 Then
Debug.Print sUrl & hAnchor.pathname & " downloaded to " & sPath
Else
Debug.Print sUrl & hAnchor.pathname & " not downloaded"
End If
End If
Next i
End Sub
Edit
I assumed that URLDownloadToFile was already written. I didn't write one, I just used the below function to test the code that iterates through the files. You can use it to make sure the above code works for you, but you'll need to write the actual code to download the file eventually. With all the arguments to URLDownloadToFile, I'm surprised it doesn't exist already.
Function UrlDownloadToFile(lNum As Long, sUrl As String, sPath As String, lNum1 As Long, lNum2 As Long) As Long
UrlDownloadToFile = 0
End Function
Try below code : The boolean function would return true if the string has the string 2013 in it.
Sub Sample()
Dim result As Boolean
result = has2013("http://cetatenie.just.ro/wp-content/uploads/Ordin-********.2013.pdf")
Debug.Print result
result = has2013("http://cetatenie.just.ro/wp-content/uploads/Ordin-********.2014.pdf")
Debug.Print result
End Sub
Function has2013(lnk As String) As Boolean
has2013 = lnk Like "*2013*"
End Function
in VBA use the LIKE function with wildcard characters:
here is an example (copied from Ozgrid Forums)
Dim sht As Worksheet
For Each sht In ActiveWorkbook.Worksheets
If sht.Name Like "FRI*" Then
'Add code for Friday sheets
Else
If sht.Name Like "MON*" Then
'Add code for Monday sheets
End If
End If
Next
The multiplication character * takes the place of zero or more characters, whereas ? takes the place of exactly 1 character, and # takes the place of 1 number. There are other more specific char. matching strategies if you only want to match certain characters.
so there you go!
Also, you could take a look at Ozgrid Forums: Using Regular Expressions in VBA
To get a list of the files on the server, read up on FTP (using DIR) at Mr Excel - List files using FTP