I am trying to error check in a userform where I want to be able to check that the time that was entered is a valid time expression (00:00 or 00 PM) as I am sending it through a TimeValue command for the output so that the time is standardized. If the value entered is not a valid expression I will have an error message display and allow to reenter a valid expression. I am not sure if this is something I can accomplish with Regex or if there is a simpler option. I have attached my code below.
Private Sub CommandButton_OK_Click()
Dim emptyrow As Long
'Error Check
If NameText.Value = "" Then
MsgBox "Please Enter Valid Name", vbOKOnly
Exit Sub
End If
'Make Sheet 1 Active
Sheet1.Activate
'Determine emptyRow
emptyrow = WorksheetFunction.CountA(Range("E:E")) + 1
'Convert Time of Inspection to Time Value
TimeText.Value = TimeValue(TimeText.Value)
'Transfer Info
Cells(emptyrow, 5).Value = DateText.Value
Cells(emptyrow, 6).Value = NameText.Value
Cells(emptyrow, 7).Value = ShiftText.Value
Cells(emptyrow, 8).Value = TimeText.Value
If CornNo.Value = True Then
Cells(emptyrow, 9).Value = "No"
Else
Cells(emptyrow, 9).Value = "Yes"
End If
If SurgeNo.Value = True Then
Cells(emptyrow, 10).Value = "No"
Else
Cells(emptyrow, 10).Value = "Yes"
End If
If MillNo.Value = True Then
Cells(emptyrow, 11).Value = "No"
Else
Cells(emptyrow, 11).Value = "Yes"
End If
If FBedNo.Value = True Then
Cells(emptyrow, 12).Value = "No"
Else
Cells(emptyrow, 12).Value = "Yes"
End If
If DDGOutNo.Value = True Then
Cells(emptyrow, 13).Value = "No"
Else
Cells(emptyrow, 13).Value = "Yes"
End If
If DDGInNo.Value = True Then
Cells(emptyrow, 14).Value = "No"
Else
Cells(emptyrow, 14).Value = "Yes"
End If
Unload Me
End Sub
It looks like you may want to user error handling with the On Error GoTo Label statement, I think that this will get what you want done
Private Sub CommandButton_OK_Click()
If nameText.Value = "" Then GoTo InvalidName
'' Do some stuff
On Error GoTo InvalidTime
Let TimeText.Value = TimeValue(TimeText.Value)
On Error GoTo 0
'' Do some more stuff
Let Cells(emptyrow, 9).Value = IIf(CornNo.Value = True, "No", "Yes")
'' Do even more stuff
Exit Sub
InvalidName:
MsgBox "Please Enter a Name", vbInformation + vbOKOnly, "Error"
Exit Sub
InvalidTime:
MsgBox "Please Enter a Valid Time", vbInformation + vbOKOnly, "Error"
Exit Sub
End Sub
Related
I have tried to convert one of my Visual Basic 6 programs to Visual Basic.NET. This program basically crawls email and mobile number data from a web page link. This program works great in Visual Basic 6 but after converting to Visual Basic.NET is not providing any function or result in .NET.
Imports VBScript_RegExp_55
Imports System.Collections.Specialized
Imports System.Diagnostics
Public Class autoextratorform
Dim emailsearch As New ListViewItem()
Dim numbersearch As New ListViewItem
Private Declare Function SendMessageByString _
Lib "user32" _
Alias "SendMessageA" _
(ByVal hwnd As Long, _
ByVal wMsg As Long, _
ByVal wParam As Long, _
ByVal lParam As String) _
As Long
Private Const LB_SELECTSTRING = &H18C
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Private WithEvents cIE As InternetHtml
Private WithEvents cExtLinks As cExtractLinks
Private cGSearch As cGoogleSearch
Dim Excel As Object
Dim Excelsheet As Object
Dim a() As String
Dim b() As String
Dim c() As String
Dim i As Integer
' Needs reference to Microsoft VBscript Regular Expressions I recomend ver 5.5.
'
Dim baseurl As String ' var to store base url so we can build the full path
Dim dVisited ' Dictionary to hold visited urls = I think Missing here
Dim dEmail ' dictionary to hold emails = I think Missing here
Dim dnumber ' = I think Missing here
Dim dweb '= I think Missing here
' We are putting the emails in a list also, for user feed back
'It would be less momery intensive and faster to just keep these in the dictionry object
'which allows to easily tell if the email already exist
Dim regxPage ' var to hold regular expression to extract urls
Dim regxEmail ' var to hold regular expression to extract emails
Dim regnumber
Dim regweb
Dim Match, Matches As String ' we use these to store are regx matches
Dim Match1, Matches1 As String
Dim Match2, Matches2 As String
' Regular expressions are super powerfull and have been a part of unix for a long time
' goto the form load event to see the regex initialization
' to learn more about regular expressions and to download the latest scripting runtime see
' http://msdn.microsoft.com/scripting/default.htm?/scripting/vbscript/techinfo/vbsdocs.htm
Dim email, pageurl, mnumber, sweb As String
' The above is only because dictionary.exist does not work directly on Match var
Dim stopcrawl As Integer ' Used to exit crawl loop
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Select Case ComboBox1.SelectedIndex
Case 0
ListBox2.Items.Clear()
ListBox2.Items.Add("http://classads.jang.com.pk/default.asp?cityid=1")
ListBox2.Items.Add("http://www.merapakistan.com/classifieds/")
ListBox2.Items.Add("http://olx.com.pk/")
ListBox2.SelectedIndex = 0
txtStartUrl.Text = ListBox2.Text
Case 1
ListBox2.Items.Clear()
ListBox2.Items.Add("http://www.locanto.com.pk/")
ListBox2.Items.Add("http://pakistanclassifiedads.com/")
ListBox2.Items.Add("http://pkr.com.pk/")
txtStartUrl.Text = ListBox2.Text
Case 2
ListBox2.Items.Clear()
ListBox2.Items.Add("http://adpost.pk/")
ListBox2.Items.Add("http://page.com.pk/")
ListBox2.Items.Add("http://www.clasf.pk/")
ListBox2.SelectedIndex = 0
txtStartUrl.Text = ListBox2.Text
Case 3
ListBox2.Items.Clear()
ListBox2.Items.Add("http://www.nelaam.com/")
ListBox2.Items.Add("http://www.asani.com.pk/")
ListBox2.Items.Add("http://freepost.com.pk/")
ListBox2.SelectedIndex = 0
txtStartUrl.Text = ListBox2.Text
End Select
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Command1.Click
stopcrawl = 0 ' set stop crawl so we do not exit loop
If txtStartUrl.Text & "" = "" Then
lblresult.Text = ("Please Load your Desired Site List !")
Exit Sub
ElseIf txtStartUrl.Text & "" = "http://" Then
lblresult.Text = ("Please Load your Desired Site List !")
Exit Sub
ElseIf txtStartUrl.Text = "" Then
lblresult.Text = ("Please Load your Desired Site List !")
Exit Sub
End If
' the above should really check for a valid url, but I am a lazy PERL programmer
ListBox1.Items.Add(txtStartUrl.Text) 'add item to list
Label16.Text = (ListBox2.Items.Count - 1)
Label8.Text = (ListBox2.Items.Count)
lblresult.Text = " Start service for searching Email address and Mobile Numbers"
Command1.Enabled = False
ComboBox1.Enabled = False
LaVolpeButton4.Enabled = True
'UPGRADE_ISSUE: (2064) ComboBox property Combo1.Locked was not upgraded. More Information: https://docs.mobilize.net/vbuc/ewis#2064
LaVolpeButton8.Enabled = False
LaVolpeButton9.Enabled = False
txtStartUrl.ReadOnly = True
crawl() ' and were off
End Sub
Private Sub autoextrator_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With listnumber
.Columns.Clear()
.Columns.Add("Count!", CInt(Width * 0.1))
.Columns.Add("Mobile Number!", CInt(Width * 0.2))
.Columns.Add("Web URL!", CInt(Width * 0.68))
End With
With listemail
.Columns.Clear()
.Columns.Add("Count!", CInt(Width * 0.1))
.Columns.Add("Email Address!", CInt(Width * 0.2))
.Columns.Add("Web URL!", CInt(Width * 0.68))
End With
'initialize dictionary and regx objects
dVisited = CreateObject("Scripting.Dictionary")
dVisited.CompareMode = CompareMethod.Binary
dEmail = CreateObject("Scripting.Dictionary")
dEmail.CompareMode = CompareMethod.Binary
dnumber = CreateObject("Scripting.Dictionary")
dnumber.CompareMode = CompareMethod.Binary
dweb = CreateObject("Scripting.Dictionary")
dweb.CompareMode = CompareMethod.Binary
Dim counting1 As String
Dim counting2 As String
regxPage = New VBScript_RegExp_55.RegExp() ' Create a regular expression.
regxPage.Pattern = "HREF=""[^""#]+[.][^""#]+" ' Set pattern."
regxPage.IgnoreCase = True ' Set case insensitivity.
regxPage.Global = True ' Set global applicability.
regxEmail = New VBScript_RegExp_55.RegExp() ' Create a regular expression.
regxEmail.Pattern = "\b[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}\b" ' Set pattern."
regxEmail.IgnoreCase = True ' Set case insensitivity.
regxEmail.Global = True ' Set global applicability.
regnumber = New VBScript_RegExp_55.RegExp()
counting1 = "(\+92)-?\d{3}-?\d{7}"
counting2 = "(?:0092|0|\+92)-?\d{3}-?\d{7}"
regnumber.Pattern = counting1
regnumber.Pattern = counting2
regnumber.IgnoreCase = True
regnumber.Global = True
cIE = New InternetHtml()
cGSearch = New cGoogleSearch()
cExtLinks = New cExtractLinks()
End Sub
Sub crawl()
While ListBox1.Items.Count > 0 ' loop while list has data
If stopcrawl = 1 Then GoTo exitcrawl
getpage(ListBox1.Items(0)) ' This is the heart of the prog, except for the regx = I think Missing here
' stuff in the form load event
ListBox1.Items.Remove(0) ' remove item from list
End While
ListBox2.Items.Remove(ListBox2.SelectedIndex)
If ListBox2.SelectedIndex < ListBox2.Items.Count - 1 Then
ListBox2.SelectedIndex += 1
txtStartUrl.Text = ListBox2.Items.ToString
exitcrawl:
If ListBox2.Items.Count = 0 Then
MessageBox.Show("Searching has completed !", "Done ! searching", MessageBoxButtons.OK, MessageBoxIcon.Information)
txtStartUrl.ReadOnly = False
txtStartUrl.Text = ""
Label3.Text = "-----------------------------------------------------------"
LaVolpeButton4.Enabled = False
Command1.Enabled = True
LaVolpeButton8.Enabled = True
LaVolpeButton9.Enabled = True
End If
End If
End Sub
Sub getpage(ByVal page As String)
On Error Resume Next
If dVisited.Contains(page) Then
Exit Sub
Else
dVisited.Add(page, 1) ' add page to dVisited dictionary
Label6.Text = CStr(ListBox1.Items.Count)
Label14.Text = CStr(dVisited.Count)
Label3.Text = page
End If
baseurl = getpath(page) ' build full url - see getpath
TextBox1.Text = ""
If ListBox1.Items.Count > 5000 Then Exit Sub ' sets the maximum cache (so we don't run out of mem)
Using wc As New System.Net.WebClient
TextBox1.Text = wc.DownloadString(page)
End Using
Matches = regxPage.Execute(TextBox1.Text) ' Execute search.
For Each Me.Match In Matches
pageurl = Match
If InStr(1, pageurl, "http://", vbTextCompare) Then
If dVisited.Exists(pageurl) = False Then ListBox1.Items.Add(Mid(pageurl, 7))
Else
If dVisited.Exists(baseurl & Mid(pageurl, 7)) = False Then ListBox1.Items.Add(baseurl & Mid(pageurl, 7))
End If
Next
' search for email
Matches = regxEmail.Execute(TextBox1.Text) ' Execute search.
For Each Me.Match In Matches ' Iterate Matches collection.
' check if email exist
email = Match
Debug.Print(email & dEmail.Exists(email))
If dEmail.Exists(email) = False Then
dEmail.Add((email), 1)
Dim d As Integer
d = listemail.Items.Count
d = d + 1
emailsearch = listemail.Items.Add(d)
emailsearch.SubItems.Add(email.ToString)
emailsearch.SubItems.Add(pageurl.ToString)
ListBox3.Items.Add(email)
Label10.Text = listemail.Items.Count
End If
Next
Matches1 = regnumber.Execute(TextBox1.Text)
For Each Me.Match1 In Matches1
mnumber = Match1
Debug.Print(mnumber & dnumber.Exists(mnumber))
If dnumber.Exists(mnumber) = False Then
dnumber.Add((mnumber), 1)
Dim c As Integer
c = listnumber.Items.Count
c = c + 1
numbersearch = listnumber.Items.Add(c)
numbersearch.SubItems.Add(mnumber.ToString)
numbersearch.SubItems.Add(pageurl.ToString)
Label12.Text = listnumber.Items.Count
End If
Next
End Sub
Function getpath(ByVal URL As String) As String
' look for the last / and get a string up to that location
Dim lastbar As Integer = URL.LastIndexOf("/") + 1
Dim tmppath As String = URL.Substring(0, Math.Min(lastbar, URL.Length))
If tmppath = "http://" Then tmppath = URL ' full path already so return url
Return tmppath
End Function
Public Function StripOut(ByVal From As String, ByVal What As String) As String
Dim result As String = ""
result = From
For i As Integer = 1 To Strings.Len(What)
result = result.Replace(What.Substring(i - 1, Math.Min(1, What.Length - (i - 1))), "")
Next i
Return result
End Function
Private Sub LaVolpeButton4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LaVolpeButton4.Click
stopcrawl = 1
MsgBox(" Service has Stoped by USER !")
LaVolpeButton4.Enabled = False
Command1.Enabled = True
End Sub
Private Sub LaVolpeButton8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LaVolpeButton8.Click
Dim strData As String = ""
Dim strQ() As String
Dim intFile As Integer
' Set up the Common Dialog initial Directory
' to the application path. Filter for Text and All files
' Prompt the user to select a file
'
cmd.InitialDirectory = My.Application.Info.DirectoryPath
cmd.Filter = "Text Files(*.txt)|*.txt|All Files(*.*)|*.*"
cmd.Title = "Select Email Addresses File"
cmd.ShowDialog()
If cmd.FileName <> "" Then
'
' If the user selected a file
' open and read the entire contents
' then split it into records
'
intFile = FileSystem.FreeFile()
FileSystem.FileOpen(intFile, cmd.FileName, OpenMode.Input)
strData = FileSystem.InputString(intFile, FileSystem.LOF(intFile))
FileSystem.FileClose(intFile)
strQ = strData.Split(CChar(Environment.NewLine))
'
' Populate the texbox array with the questions
' (either the number of textboxes in the control array or
' number of questions, which ever is the smaller)
For Each strQ_item As String In strQ
ListBox2.Items.Add(strQ_item)
Next strQ_item
txtStartUrl.Text = ListBox2.Text
End If
End Sub
End Class
2- This is Visual basic 6 Code that works perfect.
Dim baseurl As String ' var to store base url so we can build the full path
Dim dVisited As Dictionary ' Dictionary to hold visited urls
Dim dEmail As Dictionary ' dictionary to hold emails
Dim dnumber As Dictionary
Dim dweb As Dictionary
Sub crawl()
While List1.ListCount > 0 ' loop while list has data
If stopcrawl = 1 Then GoTo exitcrawl
getpage List1.List(0) ' This is the heart of the prog, except for the regx
' stuff in the form load event
List1.RemoveItem (0) ' remove item from list
Wend
List2.RemoveItem (List2.ListIndex)
If List2.ListIndex < List2.ListCount - 1 Then
List2.ListIndex = List2.ListIndex + 1
txtStartUrl = List2.Text
Command1_Click
Else
exitcrawl:
If List2.ListCount = 0 Then
MsgBox "Searching has completed !", vbInformation, "Done ! searching"
WebBrowser1.Stop
txtStartUrl.Locked = False
txtStartUrl.Text = ""
Label3.Caption = "-----------------------------------------------------------"
LaVolpeButton4.Enabled = False
Command1.Enabled = True
LaVolpeButton8.Enabled = True
LaVolpeButton9.Enabled = True
End If
End If
End Sub
This is not code I wrote completely, some I have pieced together from one or two sites and some is what I have set. What I'm trying to do is use a regex function defined in regex.Pattern to look at message subject and extract a value. This is what I'm going to see in the email subject:
New Linux Server: prod-servername-a001
So far I can get the full message subject into the Excel file, but when I have tried to implement the regex portion, I get an error code 5017 (error in expression from what I can find) and the regex is not "working". My expectation is the script will pull the message subject, use the regex to extract the value and place it in the cell. I'm using RegEx Builder (regex testing program) to test the expression and it works there, but not here. I am very new to VB, so I don't know if the issue is that VB can't use this expression or if the script is failing somewhere else and the error is something residual from another problem. Or is there a better way to write this?
Sub ExportToExcel()
On Error GoTo ErrHandler
'Declarations
Dim appExcel As Excel.Application
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Dim rng As Excel.Range
Dim strSheet As String
Dim filePath As String
Dim strPath As String
Dim intRowCounter As Integer
Dim intColumnCounter As Integer
Dim msg As Outlook.MailItem
Dim nms As Outlook.NameSpace
Dim fld As Outlook.MAPIFolder
Dim itm As Object
'RegEx Declarations
Dim result As String
Dim allMatches As Object
Dim regex As Object
Set regex = CreateObject("vbscript.regexp")
regex.Pattern = "(?<=Server: ).*"
regex.Global = True
regex.IgnoreCase = True
' Set the filename and path for output, requires creating the path to work
strSheet = "outlook.xlsx"
strPath = "D:\temp\"
filePath = strPath & strSheet
'Debug
Debug.Print filePath
'Select export folder
Set nms = Application.GetNamespace("MAPI")
Set fld = nms.PickFolder
'Handle potential errors with Select Folder dialog box.
If fld Is Nothing Then
MsgBox "There are no mail messages to export", vbOKOnly, "Error"
Exit Sub
ElseIf fld.DefaultItemType <> olMailItem Then
MsgBox "There are no mail messages to export", vbOKOnly, "Error"
Exit Sub
ElseIf fld.Items.Count = 0 Then
MsgBox "There are no mail messages to export", vbOKOnly, "Error"
Exit Sub
End If
'Open and activate Excel workbook.
Set appExcel = CreateObject("Excel.Application")
appExcel.Workbooks.Open (filePath)
Set wkb = appExcel.ActiveWorkbook
Set wks = wkb.Sheets(1)
wks.Activate
appExcel.Application.Visible = True
'Copy field items in mail folder.
For Each itm In fld.Items
intColumnCounter = 1
Set msg = itm
If itm.UnRead = True Then
intRowCounter = intRowCounter + 1
wks.Cells(1, 1).value = "Subject" 'Row 1 Column 1 (A)
wks.Cells(1, 2).value = "Unread" 'Row 1 Column 2 (B)
wks.Cells(1, 3).value = "Server" 'Row 1 Column 3 (C)
Set rng = wks.Cells(intRowCounter + 1, intColumnCounter)
If InStr(msg.Subject, "Server:") Then
Set allMatches = regex.Execute(msg.Subject)
rng.value = allMatches
intColumnCounter = intColumnCounter + 1
msg.UnRead = False
Else
rng.value = msg.Subject
intColumnCounter = intColumnCounter + 1
msg.UnRead = False
End If
Set rng = wks.Cells(intRowCounter + 1, intColumnCounter)
rng.value = msg.UnRead
intColumnCounter = intColumnCounter + 1
End If
Next itm
Set appExcel = Nothing
Set wkb = Nothing
Set wks = Nothing
Set rng = Nothing
Set msg = Nothing
Set nms = Nothing
Set fld = Nothing
Set itm = Nothing
Exit Sub
ErrHandler:
If Err.Number = 1004 Then
MsgBox filePath & " doesn't exist", vbOKOnly, "Error"
ElseIf Err.Number = 13 Then
MsgBox Err.Number & ": Type Mismatch", vbOKOnly, "Error"
ElseIf Err.Number = 438 Then
MsgBox Err.Number & ": Object doesn't support this property or method", vbOKOnly, "Error"
ElseIf Err.Number = 5017 Then
MsgBox Err.Number & ": Error in expression", vbOKOnly, "Error"
Else
MsgBox Err.Number & ": Description: ", vbOKOnly, "Error"
End If
Set appExcel = Nothing
Set wkb = Nothing
Set wks = Nothing
Set rng = Nothing
Set msg = Nothing
Set nms = Nothing
Set fld = Nothing
Set itm = Nothing
End Sub
VBA regex does not support lookbehinds, but in this case, you do not need a positive lookbehind, you just can use a capturing group - "Server: (.*)"` - and then access Group 1 value:
Set regex = CreateObject("vbscript.regexp")
regex.Pattern = "Server: (.*)"
regex.IgnoreCase = True
Set allMatches = regex.Execute("New Linux Server: prod-servername-a001")
If allMatches.Count <> 0 Then
rng.Value = allMatches(0).Submatches(0)
End If
Here,
Server: - matches a string Server: + space
(.*) - matches and captures into Group 1 zero or more characters other than a newline up to the end of line.
See more about capturing groups.
This is not code I wrote completely, some I have pieced together from one or two sites and some is what I have set. What I'm trying to do is use a regex function defined in regex.Pattern to look at message subject and extract a value. This is what I'm going to see in the email subject:
New Linux Server: prod-servername-a001
So far I can get the full message subject into the Excel file, but when I have tried to implement the regex portion, I get an error code 5017 (error in expression from what I can find) and the regex is not "working". My expectation is the script will pull the message subject, use the regex to extract the value and place it in the cell. I'm using RegEx Builder (regex testing program) to test the expression and it works there, but not here. I am very new to VB, so I don't know if the issue is that VB can't use this expression or if the script is failing somewhere else and the error is something residual from another problem. Or is there a better way to write this?
Sub ExportToExcel()
On Error GoTo ErrHandler
'Declarations
Dim appExcel As Excel.Application
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Dim rng As Excel.Range
Dim strSheet As String
Dim filePath As String
Dim strPath As String
Dim intRowCounter As Integer
Dim intColumnCounter As Integer
Dim msg As Outlook.MailItem
Dim nms As Outlook.NameSpace
Dim fld As Outlook.MAPIFolder
Dim itm As Object
'RegEx Declarations
Dim result As String
Dim allMatches As Object
Dim regex As Object
Set regex = CreateObject("vbscript.regexp")
regex.Pattern = "(?<=Server: ).*"
regex.Global = True
regex.IgnoreCase = True
' Set the filename and path for output, requires creating the path to work
strSheet = "outlook.xlsx"
strPath = "D:\temp\"
filePath = strPath & strSheet
'Debug
Debug.Print filePath
'Select export folder
Set nms = Application.GetNamespace("MAPI")
Set fld = nms.PickFolder
'Handle potential errors with Select Folder dialog box.
If fld Is Nothing Then
MsgBox "There are no mail messages to export", vbOKOnly, "Error"
Exit Sub
ElseIf fld.DefaultItemType <> olMailItem Then
MsgBox "There are no mail messages to export", vbOKOnly, "Error"
Exit Sub
ElseIf fld.Items.Count = 0 Then
MsgBox "There are no mail messages to export", vbOKOnly, "Error"
Exit Sub
End If
'Open and activate Excel workbook.
Set appExcel = CreateObject("Excel.Application")
appExcel.Workbooks.Open (filePath)
Set wkb = appExcel.ActiveWorkbook
Set wks = wkb.Sheets(1)
wks.Activate
appExcel.Application.Visible = True
'Copy field items in mail folder.
For Each itm In fld.Items
intColumnCounter = 1
Set msg = itm
If itm.UnRead = True Then
intRowCounter = intRowCounter + 1
wks.Cells(1, 1).value = "Subject" 'Row 1 Column 1 (A)
wks.Cells(1, 2).value = "Unread" 'Row 1 Column 2 (B)
wks.Cells(1, 3).value = "Server" 'Row 1 Column 3 (C)
Set rng = wks.Cells(intRowCounter + 1, intColumnCounter)
If InStr(msg.Subject, "Server:") Then
Set allMatches = regex.Execute(msg.Subject)
rng.value = allMatches
intColumnCounter = intColumnCounter + 1
msg.UnRead = False
Else
rng.value = msg.Subject
intColumnCounter = intColumnCounter + 1
msg.UnRead = False
End If
Set rng = wks.Cells(intRowCounter + 1, intColumnCounter)
rng.value = msg.UnRead
intColumnCounter = intColumnCounter + 1
End If
Next itm
Set appExcel = Nothing
Set wkb = Nothing
Set wks = Nothing
Set rng = Nothing
Set msg = Nothing
Set nms = Nothing
Set fld = Nothing
Set itm = Nothing
Exit Sub
ErrHandler:
If Err.Number = 1004 Then
MsgBox filePath & " doesn't exist", vbOKOnly, "Error"
ElseIf Err.Number = 13 Then
MsgBox Err.Number & ": Type Mismatch", vbOKOnly, "Error"
ElseIf Err.Number = 438 Then
MsgBox Err.Number & ": Object doesn't support this property or method", vbOKOnly, "Error"
ElseIf Err.Number = 5017 Then
MsgBox Err.Number & ": Error in expression", vbOKOnly, "Error"
Else
MsgBox Err.Number & ": Description: ", vbOKOnly, "Error"
End If
Set appExcel = Nothing
Set wkb = Nothing
Set wks = Nothing
Set rng = Nothing
Set msg = Nothing
Set nms = Nothing
Set fld = Nothing
Set itm = Nothing
End Sub
VBA regex does not support lookbehinds, but in this case, you do not need a positive lookbehind, you just can use a capturing group - "Server: (.*)"` - and then access Group 1 value:
Set regex = CreateObject("vbscript.regexp")
regex.Pattern = "Server: (.*)"
regex.IgnoreCase = True
Set allMatches = regex.Execute("New Linux Server: prod-servername-a001")
If allMatches.Count <> 0 Then
rng.Value = allMatches(0).Submatches(0)
End If
Here,
Server: - matches a string Server: + space
(.*) - matches and captures into Group 1 zero or more characters other than a newline up to the end of line.
See more about capturing groups.
I've had this function for almost two years now, and I can't seem to figure out why it's not working for colorizing. Here's the entire function, but you'll see the core parts that aren't working below.
function showscoreboard()
local function len(arg)
return string.len(arg)
end
local function tbuff(arg)
if len(arg) < 3 then
return arg.." "
else
return arg
end
end
local function sbuff(arg)
if len(arg) < 2 then
return " "..arg
else
return arg
end
end
local function cteam(t,s)
local status = s or nil
local forecolor = ""
if status == "p" then
forecolor = "yellow"
elseif status == "w" then
forecolor = "cyan"
else
forecolor = "limegreen"
end
return "<color fore="..forecolor..">"..t.."</color>"
end
local function bcolor(i)
local i = i or 0
if i%2 == 1 then
return "maroon"
else
return "navy"
end
end
local scorestring = ""
local allteams = {["ATL"]=0,["WAS"]=0,["MIA"]=0,["CLE"]=0,["OAK"]=0,["SD"]=0,["IND"]=0,["NYJ"]=0,["TEN"]=0,["SEA"]=0,["PHI"]=0,["DEN"]=0,["GB"]=0,["BUF"]=0,["TB"]=0,["PIT"]=0,["MIN"]=0,["HOU"]=0,["DET"]=0,["TB"]=0,["CAR"]=0,["CHI"]=0,["STL"]=0,["NYG"]=0,["ARI"]=0,["NO"]=0,["KC"]=0,["SF"]=0,["NE"]=0}
local byeweek = ""
for _,v in ipairs(nflscores.ss) do
allteams[v[5]] = 1
allteams[v[7]] = 1
end
for i,v in pairs(allteams) do
if v == 0 then
byeweek = byeweek .. "<color white>".. i .."</color>\r"
end
end
for i,v in ipairs(nflscores.ss) do
local hteam = v[7]
local ateam = v[5]
local qgame = v[3]
local hscre = v[8] or 0
local ascre = v[6] or 0
if v[4] then
qtime = "<color white>Time: "..v[4].."</color>"
else
qtime = ""
end
local gposs = v[9] or ""
if gposs ~= "" then
if gposs == hteam then
hteam = cteam(tbuff(hteam),"p")
ateam = cteam(tbuff(ateam))
else
ateam = cteam(tbuff(ateam),"p")
hteam = cteam(tbuff(hteam))
end
else
hteam = cteam(tbuff(hteam))
ateam = cteam(tbuff(ateam))
end
if qgame == "Final" or qgame == "final overtime" then
if hscre > ascre then
hteam = cteam(tbuff(hteam),"w")
ateam = cteam(tbuff(ateam))
elseif hscre < ascre then
ateam = cteam(tbuff(ateam),"w")
hteam = cteam(tbuff(hteam))
else
ateam = cteam(tbuff(ateam))
hteam = cteam(tbuff(hteam))
end
if qgame == "Final" then
qgame = "<color cyan>F</color>"
elseif qgame == "final overtime" then
qgame = "<color cyan>F/OT</color>"
end
elseif qgame == "Pregame" then
qgame = "<color cyan>Pre</color>"
elseif qgame == "Halftime" then
qgame = "<color white>"..qgame.."</color>"
else
qgame = "<color white>Q"..qgame.."</color>"
end
scorestring = scorestring .. "<color back="..bcolor(i) .. ">".. v[1] .. ": " .. ateam .. "<color white>: " .. sbuff(ascre) .. "</color> <color black>#</color> " .. hteam .. "<color white>: ".. sbuff(hscre) .."</color></color> " .. qgame .. " " .. qtime .. "\r"
end
return scorestring .. "<color white>Bye week:</color>\r"..byeweek
end
The part that isn't working properly is:
if hscre > ascre then
hteam = cteam(tbuff(hteam),"w")
ateam = cteam(tbuff(ateam))
elseif hscre < ascre then
ateam = cteam(tbuff(ateam),"w")
hteam = cteam(tbuff(hteam))
else
ateam = cteam(tbuff(ateam))
hteam = cteam(tbuff(hteam))
end
The function for cteam is:
local function cteam(t,s)
local status = s or nil
local forecolor = ""
if status == "p" then
forecolor = "yellow"
elseif status == "w" then
forecolor = "cyan"
else
forecolor = "limegreen"
end
return "<color fore="..forecolor..">"..t.."</color>"
end
Now, it colors the "p" status just fine. But when the status changes to "w", it fails, and for the life of me, I cannot figure out why. Am I missing something? Could this code be a lot cleaner?
Edit: I haven't found the issue to the problem, but apparently the "elseif status == "w" statement is completely bypassed. When the games are being played, the correct team in possession shows yellow. However, after the game is over, both teams are lime green, as if no score was higher than the other.
2nd Edit: The error listed in the first answer has been corrected. Still, it doesn't solve the issue. I'm still quite at a loss.
Nothing jumps out and I can't test here but here are some things to check:
You mention that cteam works correctly during the game, and that it's only once the game is over that cteam doesn't give the correct final result. So the logic of cteam is correct. The problem must be in the code that calls cteam: does cteam ever get called with s equals "w": this would never happen if hscre and ascre are always the same. Also there is a typo in the branch code that calls cteam:
if hscre > ascre then
hteam = cteam(tbuff(hteam),"w")
ateam = cteam(tbuff(ateam))
elseif hscre < ascre then
ateam = cteam(tbuff(ateam,"w")) -- ERR
hteam = cteam(tbuff(hteam))
else
ateam = cteam(tbuff(ateam))
hteam = cteam(tbuff(hteam))
end
The line that is tagged ERR should be:
ateam = cteam(tbuff(ateam),"w")
About cleaning up the code: post your question on StackOverflow's code review forum.
I'm trying to add some Input Validation in Classic ASP by using the function/code seen below.
The only one that looks like it's working correctly is the "text" type. the others I keep getting errors or it just does not filter correctly.
I'm trying to understand what I'm doing wrong please help me.
Valid Data Types: "email", "integer", "date", "string" and "text".
The first three are obvious, the last two have slight differences.
The "email" should only allow numbers and leters, and the following characters "#" , "-" , "." , "_"
The "date" should validate by running IsDate and if True then allow if False DON'T.
The "string" should validate text-based querystrings, allowing only letters, numbers, _, - and .
Whereas "text" is any free-form text form field type content.
The "integer" should only allow numbers and a period (.)
Usage Example: <input type="text" value="<%=MakeSafe("test#test.com</HTML>1234.5",integer,50)%>">
Eg: MakeSafe(dataInput,dataType,dataLength)
<%
'// CODE BY: dB Masters
'// FOUND AT: http://successontheweb.blogspot.com/2008/03/input-validation-for-security-in.html
Function MakeSafeConvert(encodeData)
encodeData = replace(encodeData,"&", "&")
encodeData = replace(encodeData,"'", "'")
encodeData = replace(encodeData,"""", """)
encodeData = replace(encodeData,">", ">")
encodeData = replace(encodeData,"<", "<")
encodeData = replace(encodeData,")", ")")
encodeData = replace(encodeData,"(", "(")
encodeData = replace(encodeData,"]", "]")
encodeData = replace(encodeData,"[", "[")
encodeData = replace(encodeData,"}", "}")
encodeData = replace(encodeData,"{", "{")
encodeData = replace(encodeData,"--", "--")
encodeData = replace(encodeData,"=", "=")
MakeSafeConvert = encodeData
End Function
Function MakeSafe(dataInput,dataType,dataLength)
Dim regex, validInput, expressionmatch
regex = ""
validInput = "1"
If dataType = "string" And Len(dataInput) > 0 Then
regex = "^[\w-\.]{1,"& dataLength &"}$"
ElseIf dataType = "email" And Len(dataInput) > 0 Then
regex = "^[\w-\.]+#([\w-]+\.)+[\w-]{2,6}$"
ElseIf dataType = "integer" And Len(dataInput) > 0 Then
regex = "^\d{1,"& dataLength &"}$"
ElseIf dataType = "date" And Len(dataInput) > 0 Then
If Not IsDate(dataInput) Then validInput = "0" End If
ElseIf dataType = "text" And Len(dataInput) > 0 Then
If Len(dataInput) > dataLength Then validInput = "0" End If
End If
If Len(regex) > 0 And Len(dataInput) > 0 Then
Set RegExpObj = New RegExp
RegExpObj.Pattern = regex
RegExpObj.IgnoreCase = True
RegExpObj.Global = True
RegExpChk = RegExpObj.Test(dataInput)
If Not RegExpChk Then
validInput = "0"
End If
Set RegExpObj = nothing
End If
If validInput = "1" And Len(dataInput) > 0 Then
MakeSafe = MakeSafeConvert(dataInput)
ElseIf Len(dataInput) = 0 Then
MakeSafe = ""
Else
Response.Write "<h2>Processing Halted.</h2>"
Response.End
End If
End Function
%>
EXAMPLE CODE AND ERROR(S):
When I test this using the code:
<%=MakeSafe("test#test.com1234.5",email,50)%>
* Does NOT Validate Anything.*
I don't get an error message but it DOES NOT Validate anything.
**The OUTPUT IS : test#test.com1/27/20121234.5
SHOULD BE ONLY: test#test.com**
When I test this using the code:
<%=MakeSafe("test#test.com1/27/20121234.5",date,50)%>
I don't get an error message but it DOES NOT Validate anything.
The OUTPUT IS : test#test.com1/27/20121234.5
SHOULD BE ONLY: 1/27/2012
The other two give me this error message:
<%=MakeSafe("test#test.com1234.5",string,50)%>
* ERROR!!! Wrong number of arguments or invalid property assignment: 'string'
<%=MakeSafe("test#test.com1234.5",integer,50)%>
* ERROR!!! Syntax error
Thank you so much for any help that you provide...
If it's not a typo then your fault was in the second parameter of the function call.
You call the function like:
<%=MakeSafe("test#test.com1234.5",email,50)%>
which is wrong because you should "..." the second parameter too. This should work:
<%=MakeSafe("test#test.com1234.5","email",50)%>