Userform VBA Select Printer before printing - vba

I have created a userform and have become stuck on the final stage and was wondering if somebody could assist or point me in the right direction.
I have the user selecting checkboxes for the sheets they require to print, however, due to the printers being on a network I need them to select a printer so ideally would need a popup box or print preview.
Private Sub CommandButton1_Click()
'OK = MsgBox("Printing", vbExclamation + vbOKOnly, "Sucsess")
If Me.CheckBox1 = 0 And Me.CheckBox2 = 0 And Me.CheckBox3 = 0 And Me.CheckBox4 = 0 And Me.CheckBox5 = 0 And Me.CheckBox6 = 0 And Me.CheckBox7 = 0 And Me.CheckBox8 = 0 And Me.CheckBox9 = 0 And Me.CheckBox10 = 0 Then
MsgBox "You need to select at least 1 form", vbCritical + vbOKOnly, "Error"
Else
If Me.CheckBox2 = 1 And Me.ComboBox3 = Null Then
MsgBox "Please select the number of witness statements required!", vbCritical + vbOKOnly, "Witness Staements"
Else
OK = MsgBox("Printing", vbExclamation + vbOKOnly, "Sucsess")
'Print the First Page everytime
ActiveDocument.ActiveWindow.PrintOut Range:=wdPrintRangeOfPages, Item:= _
wdPrintDocumentContent, Pages:="1" & p
'Inserting Pre info Code into the form
Dim Pg1Name As Range
Set Pg1Name = ActiveDocument.Bookmarks("Pg1Name").Range
Pg1Name.Text = Me.TextBox3.Value
Dim S1Name As Range
Set S1Name = ActiveDocument.Bookmarks("S1Name").Range
S1Name.Text = Me.TextBox3.Value
Dim S5Name As Range
Set S5Name = ActiveDocument.Bookmarks("S5Name").Range
S5Name.Text = Me.TextBox3.Value
Dim S6Name As Range
Set S6Name = ActiveDocument.Bookmarks("S6Name").Range
S6Name.Text = Me.TextBox3.Value
Dim Pg1Date As Range
Set Pg1Date = ActiveDocument.Bookmarks("Pg1Date").Range
Pg1Date.Text = Me.TextBox1.Value
Dim S1Date As Range
Set S1Date = ActiveDocument.Bookmarks("S1Date").Range
S1Date.Text = Me.TextBox1.Value
Dim Pg1Time As Range
Set Pg1Time = ActiveDocument.Bookmarks("Pg1Time").Range
Pg1Time.Text = Me.TextBox2.Value
Dim S1Time As Range
Set S1Time = ActiveDocument.Bookmarks("S1Time").Range
S1Time.Text = Me.TextBox2.Value
Dim Pg1Dept As Range
Set Pg1Dept = ActiveDocument.Bookmarks("Pg1Dept").Range
Pg1Dept.Text = Me.ComboBox2.Value
Dim S5Dept As Range
Set S5Dept = ActiveDocument.Bookmarks("S5Dept").Range
S5Dept.Text = Me.ComboBox2.Value
Dim S6Dept As Range
Set S6Dept = ActiveDocument.Bookmarks("S6Dept").Range
S6Dept.Text = Me.ComboBox2.Value
Dim Pg1Site As Range
Set Pg1Site = ActiveDocument.Bookmarks("Pg1Site").Range
Pg1Site.Text = Me.ComboBox1.Value
'Print Section 1 Immediate Response
If Accident_Incident_Form_Creator.CheckBox1.Value = True Then
ActiveDocument.ActiveWindow.PrintOut Range:=wdPrintRangeOfPages, Item:=wdPrintDocumentContent, Pages:="2" & p
End If
'Print Section 2 Witness Statement
If Accident_Incident_Form_Creator.CheckBox2.Value = True Then
ActiveDocument.ActiveWindow.PrintOut Range:=wdPrintRangeOfPages, Item:=wdPrintDocumentContent, Copies:=Me.ComboBox3.Value, Pages:="3" & p
End If
'Print Section 3 Information Gathering
If Accident_Incident_Form_Creator.CheckBox3.Value = True Then
ActiveDocument.ActiveWindow.PrintOut Range:=wdPrintRangeOfPages, Item:=wdPrintDocumentContent, Pages:="4" & p
End If
'Print Section 4 First Aid
If Accident_Incident_Form_Creator.CheckBox4.Value = True Then
ActiveDocument.ActiveWindow.PrintOut Range:=wdPrintRangeOfPages, Item:=wdPrintDocumentContent, Pages:="5" & p
End If
'Print Section 5 Damage Report
If Accident_Incident_Form_Creator.CheckBox5.Value = True Then
ActiveDocument.ActiveWindow.PrintOut Range:=wdPrintRangeOfPages, Item:=wdPrintDocumentContent, Pages:="6" & p
End If
'Print Section 6 Environmental Report
If Accident_Incident_Form_Creator.CheckBox6.Value = True Then
ActiveDocument.ActiveWindow.PrintOut Range:=wdPrintRangeOfPages, Item:=wdPrintDocumentContent, Pages:="7" & p
End If
'Print Section 7 & 8 Manual Handling & MHE
If Accident_Incident_Form_Creator.CheckBox7.Value = True Then
ActiveDocument.ActiveWindow.PrintOut Range:=wdPrintRangeOfPages, Item:=wdPrintDocumentContent, Pages:="8" & p
End If
'Print Section 9 Root Cause Investigation
If Accident_Incident_Form_Creator.CheckBox8.Value = True Then
ActiveDocument.ActiveWindow.PrintOut Range:=wdPrintRangeOfPages, Item:=wdPrintDocumentContent, Pages:="9" & p
End If
'Print Section 10 Root Cause Corrective Actions
If Accident_Incident_Form_Creator.CheckBox9.Value = True Then
ActiveDocument.ActiveWindow.PrintOut Range:=wdPrintRangeOfPages, Item:=wdPrintDocumentContent, Pages:="9" & p
End If
'Print Section 11 Safety Signoff
If Accident_Incident_Form_Creator.CheckBox10.Value = True Then
ActiveDocument.ActiveWindow.PrintOut Range:=wdPrintRangeOfPages, Item:=wdPrintDocumentContent, Pages:="11" & p
End If
If OK = 1 Then
'Close and don't save
Application.DisplayAlerts = False
ActiveDocument.Close
ActiveWindow.Close
Application.DisplayAlerts = True
End If
End If
End If
End Sub

Related

Is it possible to edit the input in a UserForm in VBA?

I am creating a yard management system to keep track of open parking spots in a lot. The userform allows the user to click on a spot in the map that is open and fill out a list of information about the truck going to that spot. Right now, if I make an error in the entry I have to redo the whole form, rather than just being able to edit the information I have already entered. Is there a way to do that without having to retype everything?
Here is the code for the user form:
Private Sub cmdCancel_Click()
Unload Me
End Sub
Private Sub cmdClear_Click()
ActiveCell.ClearContents
ActiveCell.Interior.Color = vbGreen
Unload Me
End Sub
Private Sub cmdUpdate_Click()
UpdateInfo.Show
Unload Me
End Sub
Private Sub CommandButton1_Click()
UpdateInfo.Show
Unload Me
End Sub
Private Sub UserForm_Initialize()
lblInfo = ActiveCell.Value
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Set rngBDock = Range("BX7:CO7")
Set rngBulk = Range("BZ21:CG21")
Set rngTransT = Range("BF17:BY17")
Set rngTransT1 = Range("BG21:BY21")
Set rngTDock = Range("BL7:BW7")
Set rngEDock = Range("CP7:CT7")
Set rngNDock = Range("CU7:DC7")
Set rngFence = Range("CQ13:CV13")
Set rngNSide = Range("CW13:DB13")
Set rngGEO = Range("BG28:DD28")
Set rngNight = Range("CH21:DD21")
Set rngNewT = Range("DK31:DK65")
Set rngNewTl = Range("DI31:DI65")
Set rngOff = Range("BN40:CL40")
Set rngOffl = Range("BN42:CL42")
Set rng = Union(rngBDock, rngBulk, rngTransT, rngTransT1, rngTDock, rngEDock, rngNDock, rngFence, rngNSide, rngGEO, rngNight, rngNewT, rngNewTl, rngOff, rngOffl)
If Not Intersect(Target, rng) Is Nothing Then
CellInfo.Show
'ActiveCell.Value = cellFill
If Not IsEmpty(ActiveCell.Value) Then
Call RealTimeTracker
End If
End If
Private Sub cmdOkUpdate_Click()
Dim i As Integer, j As Integer
For i = 0 To lbxOption.ListCount - 1
If lbxOption.Selected(i) Then j = j + 1
Next i
If j = 0 Then
MsgBox "Please select an option. ", , "Warning"
Unload Me
UpdateInfo.Show
ElseIf j = 1 Then
NoFill = False
End If
strBOL = txtBOL.Value
strID = txtID.Value
details = txtDet.Value
opt = lbxOption.Value
currtime = time()
today = Format(Now(), "MM/DD/YYYY")
emp = TextBox1.Value
With ActiveCell
spot = .Offset(-1, 0)
If Len(spot) = 0 Then
spot = .Offset(1, 0)
Else
spot = spot
End If
End With
If NoFill = True Then
cellFill = ""
ElseIf NoFill = False Then
With Sheet5
.Range("A1").Value = "Time"
.Range("B1").Value = "Date"
.Range("C1").Value = "Location"
.Range("D1").Value = "Category"
.Range("E1").Value = "BOL"
.Range("f1").Value = "Trailer #"
.Range("g1").Value = "Details"
.Range("H1").Value = "EE Name"
.Range("A2").EntireRow.Insert
.Range("A2").Value = currtime
.Range("B2").Value = today
.Range("C2").Value = spot
.Range("D2").Value = opt
.Range("E2").Value = strBOL
.Range("F2").Value = strID
.Range("G2").Value = details
.Range("H2").Value = emp
.Columns("A:H").AutoFit
End With
If Not IsEmpty(opt) Then
cellFill = opt & " " & vbCrLf & "BOL (last 5 digits): " & strBOL & " " & vbCrLf & "Trailer # " & strID & " " & vbCrLf & details & "EE Name" & emp & " " & vbCrLf
ActiveCell.Value = cellFill
Call RealTimeTracker
End If
End If
Unload Me
Sheet1.Activate
End Sub

Excel VBA crashing due to size

I made a script in VBA that should read a very long Pivot Table with over 190,000 entries in the "Data" sheet, and according with the value in the column "J", it should write the info from that row in a sheet called "Temp".
When the value from column "A" changes, it should read from sheet "Regioner" a list of over 600 entries and check if each value is presented in the previous arrays of values.
The code I wrote works, but it takes forever to write down the expected 220,000 entries in the "Temp" sheet. In my laptop, i5 6th generation with 8Gb RAM, it simply crashes.
The current code is as per below.
Many thanks to all!
Public Sub FindWithoutOrder()
Dim DataRowCounter As Long
Dim TempRowCounter As Long
Dim RegiRowCounter As Long
Dim DataOldCounter As Long
Dim DataNewCounter As Long
Dim loopCounter As Long
Dim DataOldProd As Range
Dim DataNewProd As Range
Dim DataPurchase As Range
Dim RegiButikk As Range
Dim ButikkFlag As Boolean
'Code optimization to run faster.
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'Initialize variables.
'----------------------------------------------------------------------------------------------------------
DataRowCounter = 11
TempRowCounter = 1
DataOldCounter = 11
DataNewCounter = 11
Set DataOldProd = ActiveWorkbook.Sheets("Data").Range("A" & DataRowCounter)
Set DataNewProd = ActiveWorkbook.Sheets("Data").Range("A" & DataRowCounter)
Set DataPurchase = ActiveWorkbook.Sheets("Data").Range("J" & DataRowCounter)
'Start of loop that verifies all values inside "Data" sheet.
'----------------------------------------------------------------------------------------------------------
Do Until (IsEmpty(DataOldProd) And IsEmpty(DataNewProd))
'Verify if the product of new line is still the same or different.
'------------------------------------------------------------------------------------------------------
If DataNewProd.Value = DataOldProd.Value Then
DataNewCounter = DataNewCounter + 1
Else
'Initialize variables from "Regioner" sheet.
'------------------------------------------------------------------------------------------
ButikkFlag = False
RegiRowCounter = 11
Set RegiButikk = ActiveWorkbook.Sheets("Regioner").Range("C" & RegiRowCounter)
'Verify list of supermarkets and match them with purchases list.
'--------------------------------------------------------------------------------------------------
Do Until IsEmpty(RegiButikk)
'Check all supermarkets in the product range.
'----------------------------------------------------------------------------------------------
For loopCounter = DataOldCounter To DataNewCounter - 1
'Compare both entries and register them if it doesn't exist in the product list.
'------------------------------------------------------------------------------------------
If RegiButikk.Value = ActiveWorkbook.Sheets("Data").Range("D" & loopCounter).Value Then
ButikkFlag = True
RegiRowCounter = RegiRowCounter + 1
Set RegiButikk = ActiveWorkbook.Sheets("Regioner").Range("C" & RegiRowCounter)
Exit For
Else
ButikkFlag = False
End If
Next loopCounter
'Add to list supermarkets not present in the purchases list.
'------------------------------------------------------------------------------------------
If ButikkFlag = False Then
ActiveWorkbook.Sheets("Temp").Range("B" & TempRowCounter & ":D" & TempRowCounter).Value = ActiveWorkbook.Sheets("Regioner").Range("A" & RegiRowCounter & ":C" & RegiRowCounter).Value
ActiveWorkbook.Sheets("Temp").Range("A" & TempRowCounter).Value = ActiveWorkbook.Sheets("Data").Range("A" & DataRowCounter - 1).Value
TempRowCounter = TempRowCounter + 1
RegiRowCounter = RegiRowCounter + 1
Set RegiButikk = ActiveWorkbook.Sheets("Regioner").Range("C" & RegiRowCounter)
End If
Loop
'Reset the product range.
'--------------------------------------------------------------------------------------------------
DataOldCounter = DataNewCounter
DataNewCounter = DataNewCounter + 1
End If
'Validate if item was purchased in the defined period and copy it.
'------------------------------------------------------------------------------------------------------
If DataPurchase.Value = 0 Then
ActiveWorkbook.Sheets("Temp").Range("A" & TempRowCounter & ":D" & TempRowCounter).Value = ActiveWorkbook.Sheets("Data").Range("A" & DataRowCounter & ":D" & DataRowCounter).Value
TempRowCounter = TempRowCounter + 1
End If
'Update row counter and values for previous and new product readed.
'------------------------------------------------------------------------------------------------------
Set DataOldProd = ActiveWorkbook.Sheets("Data").Range("A" & DataRowCounter)
DataRowCounter = DataRowCounter + 1
Set DataNewProd = ActiveWorkbook.Sheets("Data").Range("A" & DataRowCounter)
Set DataPurchase = ActiveWorkbook.Sheets("Data").Range("J" & DataRowCounter)
Loop
'Code optimization to run faster.
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Instead of having this code scattered all over the place:
'Code optimization to run faster.
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Use this procedure:
Public Sub ToggleWaitMode(ByVal wait As Boolean)
Application.Cursor = IIf(wait, XlMousePointer.xlWait, XlMousePointer.xlDefault)
Application.StatusBar = IIf(wait, "Working...", False)
Application.Calculation = IIf(wait, XlCalculation.xlCalculationManual, XlCalculation.xlCalculationAutomatic)
Application.ScreenUpdating = Not wait
Application.EnableEvents = Not wait
End Sub
Like this:
Public Sub DoSomething()
ToggleWaitMode True
On Error GoTo CleanFail
'do stuff
CleanExit:
ToggleWaitMode False
Exit Sub
CleanFail:
'handle errors
Resume CleanExit
End Sub
Disabling automatic calculation and worksheet events should already help quite a lot... but it's by no means "optimizing" anything. It simply makes Excel work [much] less, whenever a cell is modified.
If your code works but is just slow, take it to Code Review Stack Exchange and present it to the VBA reviewers: they'll go out of their ways to help you actually optimize your code. I know, I'm one of them =)

Paste data from another worksheet into next row in a loop

I need to open a dialog box and select a workbook. Then copy the data placed in that workbook (which has only 1 sheet with same name all the time).
I want to do the process for many workbooks by using a loop for vbyesno.
This is the only part which is not working because I want to paste data under Range("a14"), then loop and then paste under the data pasted in a14.
Below is the macro which is being called from another macro.
Sub prompt()
Application.DisplayAlerts = False
Dim Target_Workbook As Workbook
Dim Source_Workbook As Workbook
Dim Target_Path As Range
d = MsgBox("Add record?", vbYesNoCancel + vbInformation)
If d = vbNo Then
ActiveSheet.Range("a13").value = "No data Found"
ActiveSheet.Range("a13").Font.Bold = True
ThisWorkbook.Save
ElseIf d = vbCancel Then
Sheets("MPSA").Delete
ThisWorkbook.Save
ElseIf d = vbYes Then
Sheets("MPSA").Range("a14").value = "NAME"
Sheets("MPSA").Range("b14").value = "NUMBER"
Sheets("MPSA").Range("c14").value = "AGR NUMBER"
Sheets("MPSA").Range("d14").value = "ENTITY NAME"
Sheets("MPSA").Range("e14").value = "GROUP"
Sheets("MPSA").Range("f14").value = "DELIVERABLE"
Sheets("MPSA").Range("g14").value = "DELIVERAB"
Sheets("MPSA").Range("h14").value = "IS COMPON"
Sheets("MPSA").Range("i14").value = "PACKAGE"
Sheets("MPSA").Range("j14").value = "ORDERS"
Sheets("MPSA").Range("k14").value = "LICNTITY"
Sheets("MPSA").Range("l14").value = "QUANTITY"
Sheets("MPSA").Range("m14").value = "ORDERANUMBER"
Sheets("MPSA").Range("n14").value = "ORDERAM NAME"
Sheets("MPSA").Range("o14").value = "PAC NUMBER"
Sheets("MPSA").Range("p14").value = "PACKAGAME"
Sheets("MPSA").Range("q14").value = "ITTION"
Sheets("MPSA").Range("r14").value = "LICENSE TYPE"
Sheets("MPSA").Range("s14").value = "ITEM VERSION"
Sheets("MPSA").Range("t14").value = "REAGE"
Sheets("MPSA").Range("u14").value = "CLIIT"
Sheets("MPSA").Range("v14").value = "LICEAME"
Sheets("MPSA").Range("w14").value = "ASSATE"
Sheets("MPSA").Range("x14").value = "ASSTE"
Sheets("MPSA").Range("y14").value = "ENTITTUS"
Sheets("MPSA").Range("z14").value = "ASSGORY"
Sheets("MPSA").Range("aa14").value = "PURCHAYPE"
Sheets("MPSA").Range("ab14").value = "BILLTHOD"
Sheets("MPSA").Range("ac14").value = "SALETER"
Cells.Columns.AutoFit
Target_Path = Application.GetOpenFilename
Set Target_Workbook = Workbooks.Open(Target_Path)
Set Source_Workbook = ThisWorkbook
Target_Data = Target_Workbook.Sheets(1).Range("A1").CurrentRegion.Copy
Target_Workbook.Close
Source_Workbook.Sheets("MPSA").Range("a14").End(xlDown).Offset(1, 0).PasteSpecial = Target_Data
ActiveCell.EntireRow.Delete
ThisWorkbook.Save
ThisWorkbook.Save
End If
End Sub
I was going to propose a mechanism to achieve the loop, supposing that your current code is somewhere near what you want to achieve. But I found many mistakes so I had to refactor it, hopefully it will get you a step further.
The following code will continue looping until user presses Cancel in the file dialog box:
Sub prompt()
Dim d As VbMsgBoxResult: d = MsgBox("Add record?", vbYesNoCancel + vbInformation)
If d = vbNo Then
Sheets("MPSA").Range("a13").value = "No data Found"
Sheets("MPSA").Range("a13").Font.Bold = True
ThisWorkbook.Save
Exit Sub
End If
If d = vbCancel Then
Sheets("MPSA").Delete
ThisWorkbook.Save
Exit Sub
End If
On Error GoTo Cleanup
Application.DisplayAlerts = False: Application.EnableEvents = False: Application.ScreenUpdating = False
Sheets("MPSA").Range("a14:ac14").value = Array( _
"NAME", "NUMBER", "AGR NUMBER", "ENTITY NAME", "GROUP", "DELIVERABLE", "DELIVERAB", "IS COMPON", _
"PACKAGE", "ORDERS", "LICNTITY", "QUANTITY", "ORDERANUMBER", "ORDERAM NAME", "PAC NUMBER", "PACKAGAME", _
"ITTION", "LICENSE TYPE", "ITEM VERSION", "REAGE", "CLIIT", "LICEAME", "ASSATE", "ASSTE", _
"ENTITTUS", "ASSGORY", "PURCHAYPE", "BILLTHOD", "SALETER")
Sheets("MPSA").Columns.AutoFit
Dim Target_Path: Target_Path = Application.GetOpenFilename
Do While Target_Path <> False ' <-- loop until user cancels
Dim Target_Workbook As Workbook: Set Target_Workbook = Workbooks.Open(Target_Path)
Target_Workbook.Sheets(1).Range("A1").CurrentRegion.Copy _
ThisWorkbook.Sheets("MPSA").Range("a1000000").End(xlUp).Offset(1)
Target_Workbook.Close False
ActiveCell.EntireRow.Delete
ThisWorkbook.Save
Target_Path = Application.GetOpenFilename
Loop
Cleanup:
If Err.Number <> 0 Then MsgBox "Something went wrong: " & vbCrLf & Err.Description
Application.DisplayAlerts = True: Application.EnableEvents = True: Application.ScreenUpdating = True
End Sub

VBA code to get Sharepoint document library Metadata details based on document name

I have below code to open sharepoint 2010 document library's specific document based on filename (library has only excelfiles) but I am unable to read the metadata of that file. I tried with Builtin and custom document properties but there is not luck.
Sub OpenSharePointFile(StrSharePointUrl As String, strDocLibrary As String, FileNameWithExt As String)
Application.ScreenUpdating = False
Dim SPWorkbook As Workbook
Dim this As Workbook
Dim sh As Shape
Application.DisplayAlerts = False
Set SPWorkbook = Workbooks.Open(StrSharePointUrl & strDocLibrary & "\" & FileNameWithExt)
Application.DisplayAlerts = True
Set this = ThisWorkbook
If SPWorkbook Is Nothing Then
MsgBox "This product is not available"
Exit Sub
Else
'Copy Metadata
'ThisWorkbook.Sheets(Sht_Input.Name).Range("C3").Value = SPWorkbook.BuiltinDocumentProperties("Title")
'ThisWorkbook.Sheets(Sht_Input.Name).Range("C4").Value = SPWorkbook.BuiltinDocumentProperties("Business Unit")
'ThisWorkbook.Sheets(Sht_Input.Name).Range("C5").Value = SPWorkbook.BuiltinDocumentProperties("ItemNo")
'ThisWorkbook.Sheets(Sht_Input.Name).Range("C6").Value = SPWorkbook.BuiltinDocumentProperties("ECO Type")
'ThisWorkbook.Sheets(Sht_Input.Name).Range("C7").Value = SPWorkbook.BuiltinDocumentProperties("ItemDescription")
'ThisWorkbook.Sheets(Sht_Input.Name).Range("C8").Value = SPWorkbook.BuiltinDocumentProperties("Status")
'ThisWorkbook.Sheets(Sht_Input.Name).Range("C9").Value = SPWorkbook.BuiltinDocumentProperties("CasmasUpdate")
'ThisWorkbook.Sheets(Sht_Input.Name).Range("E3").Value = SPWorkbook.BuiltinDocumentProperties("LabelData")
'ThisWorkbook.Sheets(Sht_Input.Name).Range("E4").Value = SPWorkbook.BuiltinDocumentProperties("SpqWhActive")
'ThisWorkbook.Sheets(Sht_Input.Name).Range("E5").Value = SPWorkbook.BuiltinDocumentProperties("I2of5Label")
'ThisWorkbook.Sheets(Sht_Input.Name).Range("E6").Value = SPWorkbook.BuiltinDocumentProperties("TiXHi")
'ThisWorkbook.Sheets(Sht_Input.Name).Range("E7").Value = SPWorkbook.BuiltinDocumentProperties("SpecSent")
'ThisWorkbook.Sheets(Sht_Input.Name).Range("E8").Value = SPWorkbook.BuiltinDocumentProperties("CasmasToYes")
'ThisWorkbook.Sheets(Sht_Input.Name).Range("E9").Value = SPWorkbook.BuiltinDocumentProperties("EcoOwner")
'Copy ECO Summary:
ThisWorkbook.Sheets(Sht_Input.Name).Range("B12").Value = SPWorkbook.Sheets(Sht_Input.Name).Range("B12").Value
'Copy Ref ID
ThisWorkbook.Sheets(Sht_Input.Name).Range("D14").Value = SPWorkbook.Sheets(Sht_Input.Name).Range("D14").Value
'Copy THIS ITEM
SPWorkbook.Sheets(Sht_Input.Name).Range("C14:C74" & lRow).Copy
ThisWorkbook.Sheets(Sht_Input.Name).Range("C14").PasteSpecial xlPasteValues
'Delete from this workbook if available and Copy Shape if available in Sharepoint
If ThisWorkbook.Sheets(Sht_LCEncodingInfo.Name).Shapes.Count = 2 Then
For Each sh In ThisWorkbook.Sheets(Sht_LCEncodingInfo.Name).Shapes
If sh.Name <> "Picture 1" Then
sh.Delete
End If
Next
End If
If SPWorkbook.Sheets(Sht_LCEncodingInfo.Name).Shapes.Count = 2 Then
For Each sh In SPWorkbook.Sheets(Sht_LCEncodingInfo.Name).Shapes
If sh.Name <> "Picture 1" Then
sh.Height = 150 ' 138.96 '1.93"
sh.Width = 150 ' 228.24 '3.17"
sh.Copy
Application.Goto ThisWorkbook.Sheets(Sht_LCEncodingInfo.Name).Range("F9")
ActiveSheet.Paste
End If
Next
ThisWorkbook.Sheets(Sht_LCEncodingInfo.Name).Range("G2").Select
End If
'Activate Input sheet
ThisWorkbook.Sheets(Sht_Input.Name).Activate
ThisWorkbook.Sheets(Sht_Input.Name).Range("C3").Select
Application.DisplayAlerts = False
SPWorkbook.Close
Application.DisplayAlerts = True
MsgBox "Product Details fetched."
End If
Application.ScreenUpdating = True
End Sub
Try using ActiveWorkbook.ContentTypeProperties("Your column name")
instead of SPWorkbook.BuiltinDocumentProperties("Your column name")

Subroutine unexpectedly ends when a Workbook is closed

my problem today is a part of a subroutine that inexplicably breaks its execution when a Workbook is closed.
I have written the following code:
Public Const Pi As Double = 3.14159265358979
Public Const Rad As Double = Pi / 180
Public CalcBook As Workbook
Public FilePath As String, Files() As String
Public FreqArray() As Integer
Sub Main()
Dim ChooseFolder As Object, FilePath As String, StrFile As String
Dim i As Integer, j As Integer, k As Integer, x As Integer
Dim DirNum As Integer, HNum As Integer, VNum As Integer
Dim DirColShift As Integer, HColShift As Integer, VColShift As Integer
Dim TheStart As Date, TheEnd As Date, TotalTime As Date
Set ChooseFolder = Application.FileDialog(msoFileDialogFolderPicker)
With ChooseFolder
.AllowMultiSelect = False
.Title = "Please choose a folder containing .txt files"
If .Show = -1 Then
FilePath = .SelectedItems(1) & "\"
Else
Set ChooseFolder = Nothing
Exit Sub
End If
End With
Set ChooseFolder = Nothing
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayStatusBar = False
' Stores only files containing an AntennaName + "_T" + any number of characters + "_?_?45.xls" string
' (where "?" is a single character and "*" is any number). Checks if the number of files is correct too.
StrFile = Dir(FilePath & "*_T*_?_?45.txt")
Do While Len(StrFile) > 0
ReDim Preserve Files(i)
Files(i) = FilePath & StrFile
i = i + 1
StrFile = Dir
Loop
If Not (UBound(Files) + 1) / 6 = Int((UBound(Files) + 1) / 6) Then GoTo FileError
For i = 0 To UBound(Files)
Select Case Right(Files(i), 9)
Case "D_+45.txt", "D_-45.txt"
DirNum = DirNum + 1
Case "H_+45.txt", "H_-45.txt"
HNum = HNum + 1
Case "V_+45.txt", "V_-45.txt"
VNum = VNum + 1
End Select
Next
If Not (DirNum / 2 = Int(DirNum / 2) And HNum / 2 = Int(HNum / 2) And VNum / 2 = Int(VNum / 2) And DirNum = HNum And HNum = VNum) Then
FileError:
MsgBox "Failed to properly load files. Looks like a wrong number of them is at dispose", vbCritical, "Check the import-files"
Exit Sub
End If
' Imports files in Excel for better data access
Set CalcBook = Application.Workbooks.Add
' FROM HERE ON THE DATA IS PROCESSED IN ORDER TO OBTAIN AN EXCEL WORKBOOK WITH 3 SHEETS CALLED "Directivity", "Horizontal" and "Vertical".
Application.ScreenUpdating = True
Options.Show
TheStart = Now
Application.ScreenUpdating = False
If Options.OnlyEval = False Then PolarCharts
If Options.OnlyCharts = False Then Auswertung
Application.DisplayAlerts = False
CalcBook.Close savechanges:=False
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Set CalcBook = Nothing
TheEnd = Now
TotalTime = TheEnd - TheStart
MsgBox Format(TotalTime, "HH:MM:SS"), vbInformation, "Computing Time"
Unload Options
End Sub
Options is a form which I need in order to access data for the PolarCharts and Auswertung. These Subs are correctly executed (I know that because the data they save is correct too).
I tried deleting the .ScreenUpdating and .DisplayAlerts commands, as well as the Unload thinking that they could bugging something, but the result hasn't changed.
Know also that the Workbook I'm closing contains NO CODE at all (and nothing else addresses a ".Close" so it's impossible that something is executed on the .Close event).
Below my "Options" code:
Private Sub Cancel_Click()
End
End Sub
Private Sub UserForm_Terminate()
End
End Sub
Private Sub Ok_Click()
If Me.OnlyCharts = False Then
ReDim SubFreq(4)
If Not (Me.Start1.ListIndex = -1 And Me.Stop1.ListIndex = -1) Then SubFreq(0) = Me.Start1.List(Me.Start1.ListIndex) & "-" & Me.Stop1.List(Me.Stop1.ListIndex)
If Not (Me.Start2.ListIndex = -1 And Me.Stop2.ListIndex = -1) Then SubFreq(1) = Me.Start2.List(Me.Start2.ListIndex) & "-" & Me.Stop2.List(Me.Stop2.ListIndex)
If Not (Me.Start3.ListIndex = -1 And Me.Stop3.ListIndex = -1) Then SubFreq(2) = Me.Start3.List(Me.Start3.ListIndex) & "-" & Me.Stop3.List(Me.Stop3.ListIndex)
If Not (Me.Start4.ListIndex = -1 And Me.Stop4.ListIndex = -1) Then SubFreq(3) = Me.Start4.List(Me.Start4.ListIndex) & "-" & Me.Stop4.List(Me.Stop4.ListIndex)
If Not (Me.Start5.ListIndex = -1 And Me.Stop5.ListIndex = -1) Then SubFreq(4) = Me.Start5.List(Me.Start5.ListIndex) & "-" & Me.Stop5.List(Me.Stop5.ListIndex)
If (Me.Start1 = "" And Me.Start2 = "" And Me.Start3 = "" And Me.Start4 = "" And Me.Start5 = "" And Me.Stop1 = "" And Me.Stop2 = "" And Me.Stop3 = "" And Me.Stop4 = "" And Me.Stop5 = "") _
Or Me.Start1.Value > Me.Stop1.Value Or Me.Start2.Value > Me.Stop2.Value Or Me.Start3.Value > Me.Stop3.Value Or Me.Start4.Value > Me.Stop4.Value Or Me.Start5.Value > Me.Stop5.Value _
Or (Me.Start1.ListIndex = -1 And Me.Stop1.ListIndex >= 0) Or (Me.Start2.ListIndex = -1 And Me.Stop2.ListIndex >= 0) Or (Me.Start3.ListIndex = -1 And Me.Stop3.ListIndex >= 0) Or (Me.Start4.ListIndex = -1 And Me.Stop4.ListIndex >= 0) Or (Me.Start5.ListIndex = -1 And Me.Stop5.ListIndex >= 0) _
Or (Me.Start1.ListIndex >= 0 And Me.Stop1.ListIndex = -1) Or (Me.Start2.ListIndex >= 0 And Me.Stop2.ListIndex = -1) Or (Me.Start3.ListIndex >= 0 And Me.Stop3.ListIndex = -1) Or (Me.Start4.ListIndex >= 0 And Me.Stop4.ListIndex = -1) Or (Me.Start5.ListIndex >= 0 And Me.Stop5.ListIndex = -1) Then
MsgBox("Please select correctly the frequency ranges - Maybe Start > Stop, one of those was not properly inserted, or the fields are blank", vbExclamation, "Frequency choice error")
GoTo hell
End If
For i = 0 To 4
If Not SubFreq(i) = "" Then j = j + 1
Next i
j = j - 1
ReDim Preserve SubFreq(j)
End If
Me.Hide
hell:
End Sub
Private Sub UserForm_Initialize()
Dim i As Byte
Me.StartMeas = Date
Me.StopMeas = Date
Me.Worker.AddItem "lol"
Me.Worker.AddItem "rofl"
Me.Worker.ListIndex = 0
For i = LBound(FreqArray) To UBound(FreqArray)
Me.Start1.AddItem FreqArray(i)
Me.Start2.AddItem FreqArray(i)
Me.Start3.AddItem FreqArray(i)
Me.Start4.AddItem FreqArray(i)
Me.Start5.AddItem FreqArray(i)
Me.Stop1.AddItem FreqArray(i)
Me.Stop2.AddItem FreqArray(i)
Me.Stop3.AddItem FreqArray(i)
Me.Stop4.AddItem FreqArray(i)
Me.Stop5.AddItem FreqArray(i)
Next i
Me.Start1.ListIndex = 0
Me.Stop1.ListIndex = Me.Stop1.ListCount - 1
End Sub
Apparently when I Close CalcBook, it triggers the UserForm_Terminate event from Options which Ends all the code! How do I avoid this?
Just remove the statement End bacause End causes the abrupt end of code execution.
I see End in the Cancel and Terminate event handlers. If you have it on other places, remove it es well.
If you need exit from a method then use Exit Sub.
Why: because End work that way. Read e.g. this post: http://www.vbforums.com/showthread.php?511766-Classic-VB-Why-is-using-the-End-statement-(or-VB-s-quot-stop-quot-button)-a-bad-idea.
If you need stop code from execution use If-condition or even Exit Sub but avoid using End for it.
Try
Workbooks("CalcBook").Close savechanges:=False
I suspect that both error alerts and indications of an error on the screen are being suppressed