VBA End Private Sub if First Sub Routine is exited - vba

I want the entire Private Sub to Exit if the Copier routine is exited. So the DoDays routines is never called.
Sub Copier()
Dim x As String
Dim z As Integer
x = InputBox("Enter Number of Days in Month")
If x = "" Then
MsgBox "User Pressed Cancel!" & vbCrLf & _
"or did not enter a value!", vbOKOnly + vbInformation, _
"Inputbox Result:"
z = 10
Exit Sub
ElseIf CInt(x) = 0 Then
MsgBox "User Pressed Cancel!" & vbCrLf & _
"or did not enter a value!", vbOKOnly + vbInformation, _
"Inputbox Result:"
z = 10
Exit Sub
Else: End If
y = CInt(x) - 1
For numtimes = 1 To y
ActiveWorkbook.Sheets("Sheet1").Copy _
after:=ActiveWorkbook.Sheets("Sheet1")
Next
DoDays
End Sub
Private Sub COPY_NUMBER_Click()
COPY_NUMBER.BackColor = 12713921
Copier
' DoDays
COPY_NUMBER.BackColor = 12500670
COPY_NUMBER.Enabled = False
End Sub
The call to the DoDays in the Copier sub doesn't seem to work because I literally need to exit the Private Sub so the button remains enabled.

I would merge the Copier procedure into the COPY_NUMBER_Click event procedure:
Private Sub COPY_NUMBER_Click()
COPY_NUMBER.BackColor = 12713921
Dim x As String
x = InputBox("Enter Number of Days in Month")
If x = "" Then
MsgBox "User Pressed Cancel!" & vbCrLf & _
"or did not enter a value!", vbOKOnly + vbInformation, _
"Inputbox Result:"
Exit Sub
ElseIf CInt(x) = 0 Then
MsgBox "User Pressed Cancel!" & vbCrLf & _
"or did not enter a value!", vbOKOnly + vbInformation, _
"Inputbox Result:"
Exit Sub
End If
y = CInt(x) - 1
For numtimes = 1 To y
ActiveWorkbook.Sheets("Sheet1").Copy _
After:=ActiveWorkbook.Sheets("Sheet1")
Next
DoDays
COPY_NUMBER.BackColor = 12500670
COPY_NUMBER.Enabled = False
End Sub

Create a global variable and update it at the end of your Copier method then check it before DoDays is called
Private bRunDoDays As Boolean
Sub Copier()
'set to false
bRunDoDays = False
Dim x As String
Dim z As Integer
x = InputBox("Enter Number of Days in Month")
If x = "" Then
MsgBox "User Pressed Cancel!" & vbCrLf & _
"or did not enter a value!", vbOKOnly + vbInformation, _
"Inputbox Result:"
z = 10
Exit Sub
ElseIf CInt(x) = 0 Then
MsgBox "User Pressed Cancel!" & vbCrLf & _
"or did not enter a value!", vbOKOnly + vbInformation, _
"Inputbox Result:"
z = 10
Exit Sub
Else: End If
y = CInt(x) - 1
For numtimes = 1 To y
ActiveWorkbook.Sheets("Sheet1").Copy _
after:=ActiveWorkbook.Sheets("Sheet1")
Next
'set to true
bRunDoDays = True
End Sub
Private Sub COPY_NUMBER_Click()
COPY_NUMBER.BackColor = 12713921
Copier
If bRunDoDays = False Then Exit Sub
DoDays
COPY_NUMBER.BackColor = 12500670
COPY_NUMBER.Enabled = False
End Sub

You can change Copier to a Boolean Function and edit the call to test whether it executed successfully.
Your call would look like:
If Not Copier Then Exit Sub
Your Copier Function would look like:
Public Function Copier() As Boolean
'Does Stuff
Copier = True
End Function
Make sure you have Option Explicit enabled. It should have thrown a compile error on the If z = 10 Then Exit Sub since it is out of scope.

Related

How to take values from an open Access continuous sub form, and "paste" them into another form?

Okay. Let me try to explain what is happening here.
User will select record in form 1 and click button.
That will open form 2 to a detail form of that record.
User will then select one or multiple codes from Form 2 and click order button.
Form 3 will open with the info from Form 2, but I am having trouble getting the codes to fill in on Form 3. This is where I need help.
Existing code as follows:
**Form 1 CODE**
Option Compare Database
Option Explicit
Private Sub RequeryForm()
Dim SQL As String, WhereStr As String
WhereStr = ""
If Search <> "" Then
If WhereStr <> "" Then WhereStr = WhereStr & " AND "
WhereStr = "LocationID Like ""*" & AccountSearch & "*"""
End If
If NameSearch <> "" Then
If WhereStr <> "" Then WhereStr = WhereStr & " AND "
WhereStr = "FirstNameLastName Like ""*" & NameSearch & "*"""
End If
If CodeSearch <> "" Then
If WhereStr <> "" Then WhereStr = WhereStr & " AND "
WhereStr = "Code Like ""*" & CodeSearch & "*"""
End If
SQL = "Select * From AMSQuery"
If WhereStr <> "" Then
SQL = SQL & " Where " & WhereStr
End If
Me.RecordSource = SQL
End Sub
Private Sub ClearSearchBtn_Click()
SetDefaults
RequeryForm
End Sub
Private Sub OpenDetailbtn_Click()
DoCmd.OpenForm "Form2", , , "LocationID=" & Me.LocationID
End Sub
Private Sub SearchBtn_Click()
RequeryForm
End Sub
Private Sub SetDefaults()
AccountSearch = Null
NameSearch = Null
CodeSearch = Null
End Sub
**Code For Form2**
Private Sub ExitBTN_Click()
DoCmd.Close acForm, "Form2"
End Sub
Private Sub OrderILbtn_Click()
DoCmd.OpenForm "RequestForm", acNormal, , , acFormAdd
End Sub
**Form 3 Code**
Option Compare Database
Option Explicit
'Private Sub IncNumber_BeforeUpdate(Cancel As Integer)
'If Not (Me!IncNumber = "IncNumber" Or (Me!IncNumber <> 11) Or IsNull(Me!IncNumber)) Then
'MsgBox "The Incident Number entered is less than 11 characters."
'Cancel = True
'End If
'End Sub
Private Sub CloseFormBtn_Click()
DoCmd.Close acForm, "Form3", acSaveYes
DoCmd.SelectObject acForm, "Form1"
End Sub
Private Sub Form_Load()
Forms!RequestForm!Account = Forms!Form2!LocationID
End Sub
Private Sub SaveBtn_Click()
If IsNull([Account]) Then
MsgBox "You forgot to add a Y account.", vbOKOnly, "Missing Y account Warning!"
Else
DoCmd.RunCommand acCmdSaveRecord
DoCmd.GoToRecord , , acNewRec
End If
'ILRequestID = "IL" & Right(Year([DateAndTimeRequested]), 2) & Format(Month([DateAndTimeRequested]), "00") & Format(Day([DateAndTimeRequested]), "00") & [EntryID]
End Sub

Debugging MS Word Macro for importing JPGs that is returning duplicate images

I'm looking through the following macro I inherited and trying to figure out why it's importing duplicate images when it pulls unique photos from the same folder. Any help would be much appreciated, I don't have a lot of experience with VBA.
The purpose of the macro is to pull all image files in the same folder as the word document and embed them in the word document itself. Right now it's taking the first image in the folder and embedding it multiple times. I think it's an issue with the loop logic but I'm pretty new to VBA and having trouble fixing it.
Option Explicit
Dim msPath As String
Dim msPictures() As String
Dim mlPicturesCnt As Long
Public Sub ImportJPGFiles()
On Error GoTo Err_ImportJPGFiles
Dim lngCount As Long
Dim lngPicture As Long
Dim strMsg As String
Dim sngBEGTime As Single
Dim sngENDTime As Single
'Assume JPG files are in same directory as
'as the Word document containing this macro.
msPath = Application.ActiveDocument.Path & "\"
lngCount = LoadPicturesArray
'Let user browse to correct folder if pictures aren't in the same
'folder as Word document
While lngCount < 0
strMsg = "Unable to find any JPG files in the following" & vbCrLf & _
"directory:" & vbCrLf & vbCrLf & _
msPath & vbCrLf & vbCrLf & _
"Press the 'OK' button if you want to browse to" & vbCrLf & _
"the directory containing your JPG files. Press" & vbCrLf & _
"the 'Cancel' button to end this macro."
If (MsgBox(strMsg, vbOKCancel + vbInformation, "Technical Difficulties")) = vbOK Then
With Application
.WindowState = wdWindowStateMinimize
msPath = BrowseForDirectory
.WindowState = wdWindowStateMaximize
End With
If LenB(msPath) <> 0 Then
If Right$(msPath, 1) <> "\" Then
msPath = msPath & "\"
End If
lngCount = LoadPicturesArray
Else
Exit Sub
End If
Else
Exit Sub
End If
Wend
Application.ScreenUpdating = False
sngBEGTime = Timer
For lngPicture = 0 To lngCount
Application.StatusBar = "Importing picture " & _
CStr(lngPicture + 1) & " of " & _
CStr(lngCount + 1) & " pictures..."
With Selection
.EndKey Unit:=wdStory
.MoveUp Unit:=wdLine, Count:=21, Extend:=wdExtend
.Copy
.EndKey Unit:=wdStory
.InsertBreak Type:=wdPageBreak
.Paste
.MoveUp Unit:=wdLine, Count:=24
.InlineShapes.AddPicture FileName:=msPath & msPictures(lngPicture), _
LinkToFile:=False, _
SaveWithDocument:=True
End With
Next lngPicture
sngENDTime = Timer
strMsg = "Import Statistics: " & vbCrLf & vbCrLf & _
"Pictures Imported: " & CStr(lngCount + 1) & vbCrLf & _
"Total Seconds: " & Format((sngENDTime - sngBEGTime), "###0.0") & vbCrLf & _
"Seconds/Picture: " & Format((sngENDTime - sngBEGTime) / (lngCount + 1), "###0.00")
MsgBox strMsg, , "Finished"
Exit_ImportJPGFiles:
With Application
.StatusBar = "Ready"
.ScreenUpdating = True
End With
Exit Sub
Err_ImportJPGFiles:
MsgBox Err.Number & " - " & Err.Description, , "ImportJPGFiles"
Resume Exit_ImportJPGFiles
End Sub
Public Function LoadPicturesArray() As Long
On Error GoTo Err_LoadPicturesArray
Dim strName As String
strName = Dir(msPath)
mlPicturesCnt = 0
ReDim msPictures(0)
Do While strName <> ""
If strName <> "." And strName <> ".." _
And strName <> "pagefile.sys" Then
If UCase(Right$(strName, 3)) = "JPG" Then
msPictures(mlPicturesCnt) = strName
mlPicturesCnt = mlPicturesCnt + 1
ReDim Preserve msPictures(mlPicturesCnt)
'Debug.Print strName
End If
End If
strName = Dir
Loop
Call QSort(msPictures, 0, mlPicturesCnt - 1)
' Dim i As Integer
' Debug.Print "----AFTER SORT----"
' For i = 0 To mlPicturesCnt - 1
' Debug.Print msPictures(i)
' Next i
LoadPicturesArray = mlPicturesCnt - 1
Exit_LoadPicturesArray:
Exit Function
Err_LoadPicturesArray:
MsgBox Err.Number & " - " & Err.Description, , "LoadPicturesArray"
Resume Exit_LoadPicturesArray
End Function
Public Sub QSort(ListArray() As String, lngBEGOfArray As Long, lngENDOfArray As Long)
Dim i As Long
Dim j As Long
Dim strPivot As String
Dim strTEMP As String
i = lngBEGOfArray
j = lngENDOfArray
strPivot = ListArray((lngBEGOfArray + lngENDOfArray) / 2)
While (i <= j)
While (ListArray(i) < strPivot And i < lngENDOfArray)
i = i + 1
Wend
While (strPivot < ListArray(j) And j > lngBEGOfArray)
j = j - 1
Wend
If (i <= j) Then
strTEMP = ListArray(i)
ListArray(i) = ListArray(j)
ListArray(j) = strTEMP
i = i + 1
j = j - 1
End If
Wend
If (lngBEGOfArray < j) Then QSort ListArray(), lngBEGOfArray, j
If (i < lngENDOfArray) Then QSort ListArray(), i, lngENDOfArray
End Sub

Get selected item from listview and change the color of selected item

User will select one of the person in the listview to assign as a Team Leader, and the selected item will change to specific color.
Below is my coding so far, but I got an error:
InvalidArgument=Value of '1' is not valid for 'index'.
Private Sub lvLBSkillsetSEL_DoubleClick(sender As Object, e As EventArgs) Handles lvLBSkillsetSEL.DoubleClick
If lvLBSkillsetSEL.SelectedItems.Count < 1 Then
MessageBox.Show("Please select a Team Leader.", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
End If
Dim _strCLID As ListViewItem
Dim _strCLName As ListViewItem
Dim _reply As Integer
Dim bSkip As Boolean = False
'Get CLID from selected listview
With lvLBSkillsetSEL.SelectedItems
If .Count > 0 Then
_strCLID = .Item(0)
_strCLName = .Item(1)
_reply = _
MsgBox("You've choosen " & _strCLName.Text & " as their Team Leader." & vbLf & _
"" & vbLf & vbLf & _
String.Format("Labour: {0} | {1}", _strCLID.Text, _strCLName.Text), _
MsgBoxStyle.YesNo + MsgBoxStyle.Exclamation, _
Application.ProductName)
If _reply = MsgBoxResult.No Then
Exit Sub
Else
bSkip = True
End If
Else
Exit Sub
End If
End With
End Sub

Change Text Font within Same Textbox in VBA

I have multiple subs within VBA that all have their output within the same text box (WarningData) in a PPT slide. For example, Sub 1 takes a user selection (a selection they made from a drop down menu within a GUI) and inserts that at the top of the text box. Sub 2 inserts another line of text below that line. Sub 3 inserts additional text below that. I need Sub 1 and 2 to have the same font style, but Sub 3 needs to have a different font.
Here is what Sub 1 and Sub 2 look like:
Private Sub 1() 'Sub 2 is very similar.
Call Dictionary.WindInfo
'Sets the font for the warning information text.
With ActiveWindow.Selection.SlideRange.Shapes("WarningData").TextFrame2.TextRange.Font
.Size = 24
.Name = "Calibri"
.Bold = msoTrue
.Shadow.Visible = True
.Glow.Radius = 10
.Glow.Color = RGB(128, 0, 0)
End With
ComboBoxList = Array(CStr(ComboBox3), CStr(ComboBox4))
For Each Ky In ComboBoxList
On Error Resume Next
'If nothing is selected in ComboBox4, do nothing and exit this sub.
If ComboBox4 = "" Then
Exit Sub
ElseIf ComboBox3 = "" Then
ActiveWindow.Selection.SlideRange.Shapes("WarningData").TextFrame2.TextRange = _
ActiveWindow.Selection.SlideRange.Shapes("WarningData").TextFrame2.TextRange & dict3.Item(Ky)(0)
'Otherwise, if it has a selection, insert selected text.
ElseIf ComboBox3 <> "" Then
ActiveWindow.Selection.SlideRange.Shapes("WarningData").TextFrame2.TextRange = _
ActiveWindow.Selection.SlideRange.Shapes("WarningData").TextFrame2.TextRange & vbCrLf & vbCrLf & dict3.Item(Ky)(0)
End If
Next
Set dict3 = Nothing
End Sub
The following sub is the one that I need to have a different font style:
Private Sub 3()
Call Dictionary.Call2Action
ComboBoxList = Array(CStr(ComboBox7))
For Each Ky In ComboBoxList
On Error Resume Next
'If nothing is selected in ComboBox7 and TextBox9, do nothing and exit this sub.
If ComboBox7 = "" And TextBox9 = "" Then
Exit Sub
'Otherwise, if either has a selection, insert selected text.
ElseIf ComboBox7 <> "" And TextBox9 = "" Then
ActiveWindow.Selection.SlideRange.Shapes("WarningData").TextFrame2.TextRange = _
ActiveWindow.Selection.SlideRange.Shapes("WarningData").TextFrame2.TextRange & vbCrLf & vbCrLf & dict7.Item(Ky)(0)
ElseIf ComboBox7 = "" And TextBox9 <> "" Then
ActiveWindow.Selection.SlideRange.Shapes("WarningData").TextFrame2.TextRange = _
ActiveWindow.Selection.SlideRange.Shapes("WarningData").TextFrame2.TextRange & vbCrLf & vbCrLf & TextBox9
End If
Next
Set dict7 = Nothing
End Sub
Any idea if this is possible?
Thanks!!
I simplified the code using a With statement and added 2 x font lines to show how to set the Font name. Other properties are also available in the Font2 object e.g. .Size, .Bold, .Fill etc.
Private Sub Three()
Call Dictionary.Call2Action
ComboBoxList = Array(CStr(ComboBox7))
For Each Ky In ComboBoxList
On Error Resume Next
With ActiveWindow.Selection.SlideRange.Shapes("WarningData").TextFrame2
'If nothing is selected in ComboBox7 and TextBox9, do nothing and exit this sub.
If ComboBox7 = "" And TextBox9 = "" Then
Exit Sub
'Otherwise, if either has a selection, insert selected text.
ElseIf ComboBox7 <> "" And TextBox9 = "" Then
.TextRange = .TextRange & vbCrLf & vbCrLf & dict7.Item(Ky)(0)
.TextRange.Font.Name = "Calibri"
ElseIf ComboBox7 = "" And TextBox9 <> "" Then
.TextRange = .TextRange & vbCrLf & vbCrLf & TextBox9
.TextRange.Font.Name = "Calibri"
End If
End With
Next
Set dict7 = Nothing
End Sub
Using the TextRange.Paragraphs method I was able to accomplish this task:
Private Sub 3()
Call Dictionary.Call2Action
ComboBoxList = Array(CStr(ComboBox7))
For Each Ky In ComboBoxList
On Error Resume Next
With ActiveWindow.Selection.SlideRange.Shapes("WarningData").TextFrame2
'If nothing is selected in ComboBox7 and TextBox9, do nothing and exit this sub.
If ComboBox7 = "" And TextBox9 = "" Then
Exit Sub
'Otherwise, if either has a selection, insert selected text.
ElseIf ComboBox7 <> "" And TextBox9 = "" Then
.TextRange = .TextRange & vbCrLf & vbCrLf & dict7.Item(Ky)(0)
.TextRange.Paragraphs(3).Font.Size = 18
.TextRange.Paragraphs(3).Font.Name = "Calibri"
.TextRange.Paragraphs(3).Font.Fill.ForeColor.RGB = vbWhite
.TextRange.Paragraphs(3).Font.Bold = msoTrue
.TextRange.Paragraphs(3).Font.Glow.Transparency = 1
ElseIf ComboBox7 = "" And TextBox9 <> "" Then
.TextRange = .TextRange & vbCrLf & vbCrLf & TextBox9
.TextRange.Paragraphs(3).Font.Size = 18
.TextRange.Paragraphs(3).Font.Name = "Calibri"
.TextRange.Paragraphs(3).Font.Fill.ForeColor.RGB = vbWhite
.TextRange.Paragraphs(3).Font.Bold = msoTrue
End If
End With
Next
Set dict7 = Nothing
End Sub

VBA - msgbox when file not found

I want a msgbox to show "File not found" when the file TestData.xlsx is not found. Thanks
Sub check()
Dim i As Long
'~~> From Row 5 to row 10
'~~> Chnage as applicable
For i = 5 To 10
Sheets("Sheet1").Range("F" & i).Formula = _
"=VLookup((CONCATENATE(C1,"" "",C" & i & _
")),'C:\Documents[TestData.xlsx]Sheet1'!$A$2:$G$28,7, FALSE)"
Sheets("Sheet1").Range("F" & i).Value = Sheets("Sheet1").Range("F" & i).Value
Next i
End Sub
Do a check for the file before your for loop:
If Dir$("C:\Documents\TestData.xlsx") = "" Then
MsgBox "File not found"
Exit Sub
End If
Add a reference to "Microsoft Scripting Runtime"
and then:
Dim fso As New FileSystemObject
If Not fso.FileExists("C:\Documents\TestData.xlsx") Then MsgBox "File Not Found."
This will work.
Sub test()
sPath = "C:\Documents\TestData.xlsx"
'Test if directory or file exists
If File_Exists(sPath) Then
MsgBox sPath & " exists!"
Else
MsgBox sPath & " does not exist."
End If
End Sub
Private Function File_Exists(ByVal sPathName As String,
Optional Directory As Boolean) As Boolean
'Returns True if the passed sPathName exist
'Otherwise returns False
On Error Resume Next
If sPathName <> "" Then
If IsMissing(Directory) Or Directory = False Then
File_Exists = (Dir$(sPathName) <> "")
Else
File_Exists = (Dir$(sPathName, vbDirectory) <> "")
End If
End If
End Function
This is from the second google result of "vba test if file exists" http://vbadud.blogspot.com/2007/04/vba-function-to-check-file-existence.html