Multi Macro Communication - vba

I am currently attempting to self-teach myself the great world of macro coding in VBA but have come across a stumbling block when trying to process 3 macros that I would ideally like to process as 1 but the code seems to be far too complicated for me at this stage.
What I need is to convert data from US date format mm/dd/yyyy into UK date format dd.mm.yyyy and changing the / to . at the same time ideally overwriting the original data.
This is currently what I have in separate Modules:
Sub FixFormat()
'display a message with an option if US date formats are
'included in the data
MsgBox "US Date Formats Included", vbQuestion + vbYesNo, "Addresses"
If Response = Yes Then MsgBox "Delimit Process Needed", vbOKOnly, "Addresses"
If Response = No Then MsgBox "End", vbOKOnly
End
End Sub
and
Sub FixDates()
Dim cell As Range
Dim lastRow As Long
lastRow = Range("A" & Rows.Count).End(xlUp).Row
For Each cell In Range("A1:A" & lastRow)
If InStr(cell.Value, ".") <> 0 Then
cell.Value = RegexReplace(cell.Value, _
"(\d{2})\.(\d{2})\.(\d{4})", "$3.$2.$1")
End If
If InStr(cell.Value, "/") <> 0 Then
cell.Value = RegexReplace(cell.Value, _
"(\d{2})/(\d{2})/(\d{4})", "$3.$1.$2")
End If
cell.NumberFormat = "yyyy-mm-d;#"
Next
End Sub
Function RegexReplace(ByVal text As String, _
ByVal replace_what As String, _
ByVal replace_with As String) As String
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.Pattern = replace_what
RE.Global = True
RegexReplace = RE.Replace(text, replace_with)
End Function
Is there any way to do this without having to run 2 separate macros?

Yes, you can Call the subroutine you want to run as a result of the message box.
Sub FixFormat()
'display a message with an option if US date formats are
'included in the data
If MsgBox("US Date Formats Included", vbQuestion + vbYesNo, "Addresses") = 6 Then
MsgBox "Delimit Process Needed", vbOKOnly, "Addresses"
Call FixDates
Else
MsgBox "End", vbOKOnly
End If
End Sub
See this link for more information on the MsgBox function: http://msdn.microsoft.com/en-us/library/139z2azd(v=vs.90).aspx

Related

how to loop a range for a value before adding a value to next available row

I'm setting up a button to check a range for a value if the value don't exist then copy value to next available row
Private Sub CommandButton2_Click()
Dim LrowCompleted As String
If TextBox1.Text = "" Then
MsgBox "DON'T DO THAT"
Else
LrowCompleted = Sheets("Budget").range("N4").End(xlDown).Row
Sheets("Budget").range("N" & LrowCompleted + 1) = TextBox1.Text
Unload Me
MechanicalEquipment.Show
End If
End Sub
First. LrowCompleted should be a Long not a String.
Second. You need to build the Find portion. Are you only going to find this value in a single column? Example below. Not tested but it should work.
Private Sub CommandButton2_Click()
Dim LrowCompleted As Long, fText as String, Dim findValue As Range
fText = TextBox1.Text
'You probably dont need to check all 3 below but I'm not on excel to check the best one to use.
If fText = "" Or fText = Nothing Or fText = Null Then
MsgBox "Provide what to look for"
Else
Set findValue = Sheets("Budget").Columns("N:N").Find(fText, Range("N1"), xlValues, xlPart, xlByColumns, xlNext)
If findValue Is Nothing Then
'Nothing found lets place it at the end
LrowCompleted = Sheets("Budget").Range("N4").End(xlUp).Row + 1
Sheets("Budget").Range("N" & LrowCompleted) = fText
Unload Me
MechanicalEquipment.Show
Else
'I found something, do nothing i guess
End If
End If
End Sub

VBA - Inserting Check to Validate Correct File is being Selected

In the code below I'm looking to implement a check that verifies the correct file is being selected before executing the rest of the code. Once the 'combinedbook' is open a check will be carried out that verifies certain text is in a certain cell within the workbook. For example, in the code below I need the check to verify that the text "Cash Split" is contained in cell B2 in the combinedWorkbook before carrying out the vlookup and if not to stop executing the code and provide a warning message box.
Sub ImportWriteOffs()
Dim filter As String
Dim caption As String
Dim combinedFilename As String
Dim combinedWorkbook As Workbook
' Open BRAM Report Source Data
MsgBox ("Select 'SRMF0035'")
filter = "Text files (*.xlsx),*.xlsx"
caption = "Select 'SRMF0035'"
combinedFilename = Application.GetOpenFilename(filter, , caption)
If combinedFilename <> "False" Then
Set combinedWorkbook = Application.Workbooks.Open(combinedFilename)
Else
MsgBox "No file was uploaded", vbExclamation
GoTo LastLine
End If
' Conduct Vlookup on BRAM Report
Dim lastRow As Long
With ThisWorkbook.Worksheets("Input Write Offs")
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
.Range("B9:B" & lastRow).FormulaR1C1 = _
"=VLOOKUP(RC[-1],'[" & combinedWorkbook.Name & "]Tabular Version'!R10C2:R700000C56,55,0)"
combinedWorkbook.Close False
End With
LastLine:
End Sub
Many thanks,
Kieran
What you just need to do here is to have an additional conditional statement to check first if the cell("B2") contained the certain text that you want.
With ThisWorkbook.Worksheets("Input Write Offs")
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
If .range("B2") = "Cash Split" Then
.Range("B9:B" & lastRow).FormulaR1C1 = _
"=VLOOKUP(RC[-1],'[" & combinedWorkbook.Name & "]Tabular Version'!R10C2:R700000C56,55,0)"
combinedWorkbook.Close False
Else:
Msgbox "Display Prompt In Here"
combinedWorkbook.Close False 'To Ensure that the workbook will be close before ending the routine.
exit sub
End if
End With

Passing the input value form an input box to another private sub code?

So basically i am trying to do the following:
When a specific sheet is activated/selected, i want an input box to
be displayed.
From that input box i want to get a specific range that can be found
in that specific sheet.
Now, once that custom range is defined, i will use another private sub to analyze if the required conditions are met in that specific range (which was defined by the input box).
Below are the codes that i am currently using.
Private Sub Worksheet_Activate()
Dim x As Range
Set x = Application.InputBox(prompt:="Please select the range you want to be verified for results", Title:="Notifier", Default:="Ex: $A$5:$B$30", Type:=8)
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim A As Range
Dim r As Range
Set objShell = CreateObject("Wscript.Shell")
Set A = x.Range
If Intersect(Target, A) Is Nothing Then Exit Sub
For Each r In Target
If r.Value = "FAIL" Then
intMessage = MsgBox("Please be aware that you have marked one of the required verification points as [Fail]" & vbCr _
& vbCr _
& "To improve the visibility over this issue please submit a new Jira ticket for it." & vbCr _
& vbCr _
& "Would you like to create the ticket now?", _
vbYesNo, "Notifier")
If intMessage = vbYes Then
objShell.Run ("https://custom_link")
Else
End If
End If
Next r
End Sub

Relaunch Input Box

I have an excel sheet than when its first opened it asks the user to enter a date into the input box and it places it into a cell in the sheet. I have an error handle to pop up an invalid date error box if someone puts in the wrong date. But what I want to do is when an invalid date is entered the original input box for the date pops up again so they can reenter again. I have the code below of what I have written so far but I keep getting an error.
Thanks
ReShowInputBox: cellvalue = Application.InputBox("Please Enter The Date for Data Extracted (dd/mm/yyyy)")
On Error GoTo ErrHandle
ErrHandle:
MsgBox ("Invalid Date")
ReShowInputBox: cellvalue = Application.InputBox("Please Enter The Date for Data Extracted (dd/mm/yyyy)")
If cellvalue = "" Then Exit Sub
ws.Select
ws.Range("A1").Value = DateValue(cellvalue)
MsgBox ("Date Entered!")
How about a simple Do Until Loop:
Dim cellvalue As Variant
Do
cellvalue = Application.InputBox("Please Enter The Date for Data Extracted (dd/mm/yyyy)")
Loop Until IsDate(cellvalue) And IsNumeric(Right(cellvalue, 4)) And IsNumeric(Left(cellvalue, 2)) And IsNumeric(Mid(cellvalue, 4,2))
ws.Range("A1").Value = cellvalue
MsgBox ("Date Entered!")
I tested this pretty thoroughly and it only accepted dates in the exact format you desire.
Here is a simple way to repeatedly ask for a date until you get one, but allow the user to cancel out:
Sub fhskjfs()
Dim i As String, d As Date
i = ""
While Not IsDate(i)
i = Application.InputBox(Prompt:="Enter a date", Type:=2)
If i = False Then Exit Sub
If IsDate(i) Then d = CDate(i)
Wend
End Sub
EDIT#1:
Here is a way to implement a simple format check:
Public Function CheckFormat(i As String) As String
CheckFormat = "junk"
ary = Split(i, "/")
If UBound(ary) <> 2 Then Exit Function
If CLng(ary(2)) < 1900 Or CLng(ary(2)) > 9999 Then Exit Function
If CLng(ary(1)) > 12 Then Exit Function
If CLng(ary(0)) > 31 Then Exit Function
CheckFormat = i
End Function
Sub GetDate()
Dim i As String, d As Date
i = ""
While Not IsDate(i)
i = Application.InputBox(Prompt:="Enter a date", Type:=2)
If i = "False" Then Exit Sub
i = CheckFormat(i)
If IsDate(i) Then d = CDate(i)
Wend
End Sub

VBA loop through column, replace using drop down box

Very new at VBA, I need something that sounds simple but I lack the knowledge or terminology to correctly research how to do this.
I need a way to loop through a column (we'll say D) to find value (X) and prompt a dropdown box from range (T2:T160) to replace value X for each individual occurance of X in rows rows 1 to 10000.
At the same for each time X is found, the value in that row for column B needs to be displayed (the user will query an external application to determine which of the values from the range needs to be set for that unique column B value)
1 b
2 y
3 x
4 t
5 x
and end like this
1 b
2 y
3 q
4 t
5 p
I setup my data like this:
Main code:
Sub findReplace()
Dim iReply As Integer
Dim strName As String
strName = InputBox(Prompt:="Enter Text to Search in Column D", Title:="Search Text", Default:="Enter value to find")
If strName = "Enter value to find" Or strName = vbNullString Then
Exit Sub
Else
For Each cell In Range("D1:D5")
If cell.Value = Trim(strName) Then
'Prompt to see if new value is required
iReply = MsgBox(Prompt:="Found " & strName & vbCrLf & "Value in column B is: " & cell.Offset(0, -2).Value & vbCrLf & "Do you wish to replace it?", _
Buttons:=vbYesNoCancel, Title:="UPDATE MACRO")
'Test response
If strName = "Your Name here" Or _
strName = vbNullString Then
Exit Sub
ElseIf iReply = vbYes Then
'Get new value
UserForm1.Show
ValueSelected = UserForm1.ComboBox1.Value
Unload UserForm1
If ValueSelected = vbNullString Or ValueSelected = "" Then
Exit Sub
Else
'Replace value
cell.Value = ValueSelected
End If
ElseIf iReplay = vbCancel Then
Exit Sub
End If
End If
Next cell
End If
End Sub
Setup a UserForm1 to display a drop down list to provide the user a selection option. Code behind form looks like this: (buttons have to be named the same to work correctly)
Private Sub bnt_Cancel_Click()
Unload Me
End Sub
Private Sub btn_Okay_Click()
Me.Hide
End Sub
Private Sub UserForm_Initialize()
'Populate dropdown list in userform
Dim rng As Range
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
For Each rng In ws.Range("T1:T10")
Me.ComboBox1.AddItem rng.Value
Next rng
End Sub
When you run it you'll get this sequence of popups:
I said no to the second replacement value so now my spread sheet looks like this: