Sunteți pe pagina 1din 47

Attribute VB_Name = "stdLibrary"

'--------------------stdLibrary-----------------------------------------------------' Module
: stdLibrary by Jaime Diaz
' Author
: Jaime Diaz (c) 2016
' Created : 12-01-2016
' Purpose : Collects all general purpose functions
'--------------------------------------------------------------------------'Copy needed procedures to a Code Module to the Workbook and be sure to add the
references as listed below
'Ensure
'
'
'
'
'
'
'
'
'
-

the following references have been added


Visual Basic For Applications
OLE Automation
Microsoft Excel 15.0 Object Library
Microsoft Office 15.0 Object Library
Microsoft Forms 2.0 Object Library
Microsoft Visual Basic for Applications Extensibility 5.3
Microsoft Scripting Runtime
Microsoft ActiveX Data Objects 6.1 Library
Microsoft ActiveX Data Objects Recordset 6.0 Library

'In this library are the following subroutines / functions


' Sub AddReference()
'
Programatically add a reference necessary to run the program, see routin
e for additional information
' Sub AddCodeModule(ByVal wbMain As Workbook, Optional ByVal strModule As Stri
ng)
'
Add a code module to a different worksheet, the module must exist in the
current workbook, it will be exported and imported in to the new workbook
' Function SelectFileToOpen() As String()
'
Displays a file picker to allow user to browse and select a file
' Function BrowseForFolder(Optional OpenAt As Variant, Optional Title As Strin
g) As Variant
'
Displays a file picker to allow user to browse and select a folder start
ing at a given location
' Function GetWorkSheetsFromClosedFile(ByVal sPath As String, ByVal sFile As V
ariant) As String()
'
Get the sheets from an Excel file, the file is opened as a DB, and there
fore is not fully loaded and does not burden the system
' Function getColumnHeaders(ByVal strPath As String, ByVal strFile As String,
ByVal strWorksheet As String, Optional ByVal test As Boolean) As Variant()
'
Get Column Headers for the selected Worksheet, the file is opened as a D
B, and therefore is not fully loaded and does not burden the system
' Function IsIn(vCollection As Variant, ByVal sName As String) As Boolean
'
Determines if object is in collection
' Function IsAppRunning(ByVal sAppName) As Boolean
'
Generalized Function to Check if an Instance of Application
' Sub CreateHyperlink(wsWorksheet As Worksheet, rngTargetCell As Range, sAddre
ss As String, sTextToDisplay As String, Optional sSubAddress As String)
'
Creates a hyperlink at a specified address
' Function GetHyperlinkAddress(HyperlinkCell As Range) As String
'
Retrieves the address from a hyperlink
' Sub addBordersToRange(ByRef ws As Worksheet, ByVal rngRange As Range)
'
General purpose function to add all borders (internal as well)
' Sub addSamuelGreentoRange(ByRef ws As Worksheet, ByVal rngRange As Range)
'
Set the color of the Range to light green
' Function ArrayDim(v As Variant) As Long
'
Returns number of dimensions of an array or 0 for an undimensioned array

or -1 if no array at all.
Function RemoveUpperEqLowerDim(Var As Variant) As Variant
Var must be a variant redimensioned to hold a 2D array.
If the dimensions are (M To N, P To P) or (P to P, M to N), a variant
will be returned with the dimension with equal lower and upper bounds
removed. That is the returned array has dimensions (M to N).
If neither dimension has equal lower and upper bounds, the original
array will be returned.
Function Cnv2XLSM(wbProcess As cWbProcess, ByVal workFolder As String, ByVal
sFileName As String, ByVal KeepOpen As Boolean) As Workbook
'
Saves an open Excel File to XLSM
' Function strArray2varArray(myArr() As String) As Variant()
'
Converts a String Array to a Variant Array
' Function safeUBound(myArr() As Variant) As Long
'
Safely get Upper Bound of array, returns -1 if invalid
' Function SafeToDouble(ByVal strTemp As Variant) As Double
'
Safely converts to Double, and returns -999999 as invalid
' Function SafeToSingle(ByVal strTemp As Variant) As Single
'
Safely converts to Single, and returns -999999 as invalid
' Function SafeToLong(ByVal strTemp As Variant) As Long
'
Safely converts to Long, and returns -999999 as invalid
' Function SafeToInt(ByVal strTemp As Variant) As Integer
'
Safely converts to Integer, and returns 0 when invalid
' Function SafeToDate(ByVal strTemp As Variant) As String
'
Safely validates a date, and returns "" when invalid
' Function openCSVasADO(ByVal directory As String, ByVal fileName As String, B
yVal bHasHeaders As Boolean) As ADODB.Connection
'
Opens a CSV file as a DB, and retuns the handle through the cn variable
provided
' Function openXLSXasADO(ByVal directory As String, ByVal fileName As String,
ByVal bHasHeaders As Boolean) As ADODB.Connection
'
Opens a XLSX file as a DB, and retuns the handle through the cn variable
provided
' Function AddChartObject(ByVal wbMain As Workbook, ByVal wsMain As Worksheet,
ByVal rngRange As Range, ByVal strChartSheetName As String, ByVal strChartTitle
As String, ByVal vSeriesName As Variant) As Object
'
Create initial line chart and move to a separate sheet
'
If the range has multiple columns then there are multiple
'
series, provide a name for them, or a standard name will
'
be used
' Sub addButtonToChartObject(ByVal wsSheet As Object, ByVal btnName As String,
ByVal btnText As String, ByVal btnOnAction As String, ByVal dLeft As Double, By
Val dTop As Double, ByVal dWidth As Double, ByVal dHeight As Double)
'
Add a button to a chart object
' Function OrificeCalc(dStaticPress As Double, dDiffPress As Double, dPipeDia
As Double, dOrificeDia As Double, strDiffPressLoc As String, dTemperature As Dou
ble, vElevationZone As Variant, sGasZone As Single) As Double
'
Provides Orifice Calculation, calculated flow per NX19 extension to AGA3
' Function FreqMeterCalc(dPulseRatio As Double, dPulseCount As Double, dStatic
Press As Double, dTemperature As Double, zElev As Double, vElevationZone As Vari
ant, sGasZone As Single) As Double
'
Provides Frequency Meter Flow Calculation, calculated flow per NX19 exte
nsion to AGA3
' Function GasRegConst(p, t, SG, Mn, Mc, zElev)
'
Supercompressibility (Fpv) NX-19 for Gas Register Constant Project (Calc
ulation of supercompressibility Fpv is based on the NX19 extension to AGA3)
' Function NX19Z(p, t, SG, Mn, Mc, zElev)
'
Supercompressibility (Fpv) NX-19 for Gas Register Constant Project (Calc
ulation of supercompressibility Fpv is based on the NX19 extension to AGA3)
' Function LinePackCalc(ByVal dSegLength As Double, dSegDiameter As Double, By
'
'
'
'
'
'
'
'

Val dUpstreamPressure As Double, ByVal dDownstreamPressure As Double, ByVal dTem


perature As Double, ByVal LineGasZone As Single) As Double
'
Calculates line inventory as a function of Pv=nRT*Fpv, using a conversio
n factor of 1 Nm^3 = 37.326 SCF
' Function ArraySort(ByRef strArray() As String)
'
Performs a Bubble Sort on the given array
' Function RedlichKwongACI(ByVal dSegLength As Double, ByVal dSegDiameter As D
ouble, ByVal dUpstreamPressure As Double, ByVal dDownstreamPressure As Double, B
yVal dTemperature As Double, ByVal SG As Double) As Double()
'
Calculate Inventory based on Redlich-Kwong ACI, Good for Natural Gas, NO
T iterative, must know Ax/Bx constants prior to entering
' Sub SaveAll()
'
Saves all open workbooks
' Function chkFileExists(ByVal sPath As String, ByVal sFileName As String, ByV
al wbWorkbook As Workbook) As Boolean
'
Verify the existance of a file, if no path is provided, use the workbook
's path
' Function GetExcelColumnLetter(lngCol As Long) As String
'
Convert a column number to column letter for use in Excel
'Support functions needed by other routines in this library
' Private Function Sign(a As Single, b As Single) As Single
' Private Function Atan2(y As Single, x As Single)
'
Emulate Fortran's ATAN2 function
'Examples for button and dropdown functions to be used with a graph
' Sub ShowHideGraphSeries(ByVal sSeriesName As String, ByVal sBtnName As Strin
g, ByVal sBtnLine1Text As String)
'
Change status of the selected series line chart visibility
' Sub cmbChartDD_Change(ByVal sDropDownName As String)
'
Process Drop Down List changes
' Private Sub ReconfigureChart(ByVal sDropDownName As String)
'
The following subm takes the current chart and changes the series based
on the input, so on the same chart you can select the data
'
from different sheets, and also change the Text on the buttons.
'
Change Series and button visibility as determined by Drop Down List
'Example of Regular Exporessions and how to use
' Sub getFileInfo()
'
Demonstrate the power of Regular Expressions in VBA, will process submat
ches
'Examples of using Word to create reports from Excel data, based on a template.
The template can have fields which are populated from Excel
'furtermore once the Word codument is created it is PDFd for distribution
' Sub CreateReport()
'
Creation of results based on Dash Board Data
' Sub ProcessMeterReports(wdApp As Word.Application, ByVal currRow As Long)
'
Creation of results based on Dash Board Data
' Sub ProcessLineReports(wdApp As Word.Application, ByVal currRow As Long)
'
Creation of results based on Dash Board Data
' Sub SaveDoc2PDF(wdDoc As Word.Document)
'
Converts Word Document to PDF
' Sub selectDesiredGraph(xlWB As Workbook, sGraphName As String)
'
Updates Graph on Analysis report to the desider one
' Sub wdAddSignatureBlock(wdApp As Word.Application, wdDoc As Word.Document, w
dSelection As Word.Selection)
'
Add the notes and signature block to the document

' Sub addTestResultGroup(wdSelection As Word.Selection, sTitle As String, sRes


ultCol As String, currRow As Long, Optional ByVal isLine As Boolean = False)
'
Add a test result group of lines with corresponding formatting
' Sub wdAddSamuelHeader(wdApp As Word.Application, wdDoc As Word.Document, wdS
election As Word.Selection)
'
Adds a standard Samuel Engineering Header on the fly, Not used, instead
of creating a header a template was used, and fields added for rapid modificatio
n
' Sub wdUseBullets(wdApp As Word.Application, wdDoc As Word.Document, wdSelect
ion As Word.Selection, ByVal ContinuePrevList As Boolean)
'
Changes current paragraph formating to use bullets
' Sub wdEndBullets(wdSelection As Word.Selection)
'
Terminates the use bullets
'Example PowerShell script to dump all files in directory (recursive), PATH, FIL
ENAME, LastWriteTime as CSV,
'needs to be run in PowerShell, placed here for reference
' Get-ChildItem -Path Z:\ -Filter *.docx -Recurse | Select-Object directorynam
e, name, LastWriteTime | Export-Csv -Path Z:\PSDump_1.csv -Encoding ASCII -NoTyp
eInformation
Option Explicit
Sub AddReference()
'------------------------------------------------------------------------' Procedure : AddAnalysisSheet Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Create and format an Analysis Sheet
' Notes
: But first these are 3 things you need to take care of
'
a) Macros should be enabled
'
b) In Security settings, ensure that "Trust Access To Visual Bas
ic Project" is checked
'
c) You have manually set a reference to `Microsoft Visual Basic
for Applications Extensibility" object
'
Not really useful as you need to have your references before compi
ling the code, left for general purposes
'------------------------------------------------------------------------Dim VBAEditor As VBIDE.VBE
Dim vbProj As VBIDE.VBProject
Dim chkRef As VBIDE.Reference
Dim BoolExists As Boolean
Dim Ref As VBIDE.Reference
Set VBAEditor = Application.VBE
Set vbProj = ActiveWorkbook.VBProject
'~~> Check if "Microsoft VBScript Regular Expressions 5.5" is already added
For Each chkRef In vbProj.References
If chkRef.Name = "VBScript_RegExp_55" Then
BoolExists = True
GoTo Cleanup
End If
Next
vbProj.References.AddFromFile "C:\WINDOWS\system32\vbscript.dll\3"
Cleanup:
If BoolExists = True Then

MsgBox "Reference already exists"


Else
MsgBox "Reference Added Successfully"
End If
For Each Ref In vbProj.References
Debug.Print Ref.Name, Ref.GUID
Next Ref
Set vbProj = Nothing
Set VBAEditor = Nothing
End Sub
Sub AddCodeModule(ByVal wbMain As Workbook, Optional ByVal strModule As String)
'------------------------------------------------------------------------' Procedure : AddCodeModule Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Copy code module to target Workbook
'------------------------------------------------------------------------Dim VBProjSRC As VBIDE.VBProject, VBProjTGT As VBIDE.VBProject
Dim vbComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
'Copy Module with Graph Functions to WB to ensure correct operation
'Delete copy of Graph Functions if it exists
On Error Resume Next
'Use this line to remove the Temp file used to export and import the Code Mo
dule
Kill ("C:\Temp\" & strModule & ".bas")
'Use this line to remove the Code Module from the workbook, before adding it
ActiveWorkbook.VBProject.VBComponents.Remove ActiveWorkbook.VBProject.VBComp
onents(strModule)
On Error GoTo errHandler
'Export module containing Graph Functions
Set VBProjTGT = ActiveWorkbook.VBProject
Set VBProjSRC = wbMain.VBProject
VBProjSRC.VBComponents("GraphFunctions").Export fileName:="C:\Temp\" & strMo
dule & ".bas"
VBProjTGT.VBComponents.Import fileName:="C:\Temp\" & strModule & ".bas"
Kill ("C:\Temp\" & strModule & ".bas")
Cleanup:
On Error Resume Next
Set VBProjSRC = Nothing
Set VBProjTGT = Nothing
Set CodeMod = Nothing
Exit Sub
errHandler:
MsgBox "Error: " & Err.Number & vbCrLf & Err.Description & vbCrLf & "Line: s
tdLibrary-AddCodeModule " & Erl & vbCrLf, vbCritical + vbOKOnly, "Error"
Resume Cleanup
End Sub
Function SelectFileToOpen(dlgTitle As String) As String()
'------------------------------------------------------------------------' Procedure : SelectFileToOpen Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016

' Purpose : Open a File Selection Dialog


'------------------------------------------------------------------------Dim directory As String, fileName As String, fullName As String
Dim sheet As Worksheet
Dim total As Integer
Dim fd As Office.FileDialog
Dim ButtonText As Object
Dim Result() As String
'Results returned in a 2 item string array, first is file name, second is fu
ll path
'To set and use the filters add the following in the calling macro
' Dim fdfs As FileDialogFilters
' Set fdfs = Application.FileDialog(msoFileDialogSaveAs).Filters
' fdfs.Clear
' fdfs.Add "Excel", "*.xls;*.xlsm;*.xlsx;*.xlsm;*.csv", 1
' fdfs.Add "Text", "*.txt;*.tsv;*.csv", 2
'Create file picker dialog object
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'Set options and display
With fd
.AllowMultiSelect = False
.Title = dlgTitle
'.Filters.Clear
If .Show = True Then
'Get selected file
fullName = .SelectedItems(1)
End If
End With
'Separate full path, in to path and file name
fileName = Right(fullName, Len(fullName) - InStrRev(fullName, "\"))
directory = Left(fullName, InStrRev(fullName, "\"))
ReDim Result(1 To 2)
'Place on screen for further use
Result(1) = fileName
Result(2) = directory
Set fd = Nothing
Set ButtonText = Nothing
SelectFileToOpen = Result
End Function
Function BrowseForFolder(Optional OpenAt As Variant, Optional Title As String) A
s Variant
'------------------------------------------------------------------------' Procedure : BrowseForFolder Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Opens a Folder Selection Dialog
'------------------------------------------------------------------------'Function purpose: To Browser for a user selected folder.
'If the "OpenAt" path is provided, open the browser at that directory
'NOTE: If invalid, it will open at the Desktop level
Dim ShellApp As Object
If Len(Title) = 0 Then Title = "Please choose a folder"
'Create a file browser window at the default folder
Set ShellApp = CreateObject("Shell.Application").BrowseForFolder(0, Title, 0
, OpenAt)

'Set the folder to that selected. (On error in case cancelled)


On Error Resume Next
BrowseForFolder = ShellApp.self.Path
On Error GoTo errHandler
'Destroy the Shell Application
Set ShellApp = Nothing
'Check for invalid or non-entries and send to the Invalid error
'handler if found
'Valid selections can begin L: (where L is a letter) or
'\\ (as in \\servername\sharename. All others are invalid
Select Case Mid(BrowseForFolder, 2, 1)
Case Is = ":"
If Left(BrowseForFolder, 1) = ":" Then GoTo Invalid
Case Is = "\"
If Not Left(BrowseForFolder, 1) = "\" Then GoTo Invalid
Case Else
GoTo Invalid
End Select
Exit Function
Invalid:
'If it was determined that the selection was invalid, set to False
BrowseForFolder = False
Exit Function
errHandler:
MsgBox ("Error: " & Err.Number & vbCrLf & Err.Description & vbCrLf & "Line N
umber: stdLibrary-BrowseForFolder " & Erl), vbCritical + vbOKOnly, "ERROR"
End Function
Function GetWorkSheetsFromClosedFile(ByVal sPath As String, ByVal sFile As Varia
nt) As String()
'------------------------------------------------------------------------' Procedure : GetWorkSheetsFromClosedFile Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Returns an array with the Spread Sheet names
'------------------------------------------------------------------------'This function usus ADO in order to access in a faster way the files.
Dim cn As ADODB.Connection
Dim rsT As ADODB.Recordset
Dim cmd As ADODB.Command
Dim intSheetCnt As Integer, colCNTR As Integer
Dim cols As Long
Dim x As Integer, y As Integer
Dim wsSheets() As String, strTemp As String
Dim vTempArr() As Variant
Dim vTemp As Variant, vTemp1 As Variant, vVariant As Variant
On Error GoTo errHandler
'Create the connection object
Set cn = New ADODB.Connection
'Setup the connection string and open
On Error Resume Next
With cn
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & s
Path & sFile & ";" & "Extended Properties=" & Chr(34) & "Excel 8.0;HDR=No;" & Ch
r(34)
.CursorLocation = adUseClient

.Open
End With
On Error GoTo errHandler
ReDim wsSheets(1)
If cn.State = adStateClosed Then
'Supose a CSV file
wsSheets(1) = Mid(sFile, 1, InStr(1, sFile, ".") - 1)
Else
'Get the record set from the connection, in this case we are specificall
y getting the SCHEMA
'The array provided for the Query is as follows (Table_Catalog, Table_Sc
hema, Table_Name, Table_Type)
Set rsT = cn.OpenSchema(adSchemaTables) ', Array(Empty, Empty, Empty, "T
ABLE"))
'Get the record count (number of tabs)
intSheetCnt = rsT.RecordCount
rsT.MoveFirst
ReDim wsSheets(intSheetCnt)
For x = 1 To intSheetCnt
strTemp = rsT.Fields("TABLE_NAME").value
'Clean the single quotes from the table names
If Left(strTemp, 1) = "'" Then strTemp = Mid(strTemp, 2)
If Right(strTemp, 1) = "'" Then strTemp = Left(strTemp, Len(strTemp)
- 1) 'Else If Right(strTemp, 1) = "$" Then strTemp = Left(strTemp, Len(strTemp)
- 1)
rsT.MoveNext
'Add the trimmed name to the array
wsSheets(x) = strTemp
Next
End If
x = 0
If VarType(wsSheets) = vbArray + vbString Then vTempArr = strArray2varArray(
wsSheets)
If safeUBound(vTempArr) = 0 Then Exit Function
'Go through the obtained array, which includes named tables as well as sheet
s and delete from the array any object that is not a sheet
Do While x <= UBound(wsSheets)
For y = x + 1 To UBound(wsSheets)
'The way that the table names are formatted in excel is as follows:
' Sheets end with "$"
' Non-Dependant Named tables do not end with a "$"
' Dependant tables have the [sheet name]$[table name]
'Therefore if the position of "$" equals the length of the string th
is is a table
'trim the "$" and conserve
If InStr(wsSheets(y), "$") > 1 And Len(wsSheets(y)) = InStr(wsSheets
(y), "$") Then
wsSheets(x) = Left(wsSheets(y), Len(wsSheets(y)) - 1)
wsSheets(y) = "$"
Exit For
End If
Next y
If y >= UBound(wsSheets) Then Exit Do
x = x + 1
Loop
'Keep only the relevant records
ReDim Preserve wsSheets(0 To x)
Cleanup:
On Error Resume Next
'Close the record set

rsT.Close
'Close the connection
cn.Close
'Pass the String array containing the tab names
'NOTE: that this is a horizontal array if you want to make it vertical you c
an use the next line and comment out the line after that
'GetWorkSheetsFromClosedFile = Application.Transpose(wSheets)
GetWorkSheetsFromClosedFile = wsSheets
Exit Function
errHandler:
MsgBox "Error: " & Err.Number & vbCrLf & Err.Description & vbCrLf & "Line Nu
mber: stdLibrary-GetWorkSheetsFromClosedFile " & Erl, vbCritical + vbOKOnly, "ER
ROR"
Resume Cleanup
End Function
Function getColumnHeaders(ByVal strPath As String, ByVal strFile As String, ByVa
l strWorksheet As String, Optional ByVal test As Boolean) As Variant()
'------------------------------------------------------------------------' Procedure : getFieldHeaders Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Get Column Headers for the selected Worksheet
'
Each Workbook is treated as a Database, and the Worksheets are t
hen considered tables
'
while the columns are exactly that columns. Therefore we treat t
he structure of a
'
workbook as a structure of a RDB, and correlate the correspondin
g parts as described
'
above
'------------------------------------------------------------------------Dim results() As Variant, vTmpResults As Variant
Dim cn As ADODB.Connection
'Table variables
Dim rsT As ADODB.Recordset
Dim intTblCnt As Integer
Dim strTbl As String
'Column Variables
Dim rsC As ADODB.Recordset
Dim intColCnt As Integer
Dim strCol As String, strIndex As String
Dim t As Integer, c As Integer, f As Integer
On Error GoTo errHandler
Set cn = New ADODB.Connection
If Right(strPath, 1) <> "\" Then strPath = strPath & "\"
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & s
trPath & strFile & ";Extended Properties=" & Chr(34) & "Excel 8.0;HDR=Yes;" & Ch
r(34) & ";"
.CursorLocation = adUseClient
.Open
End With
Set rsT = cn.OpenSchema(adSchemaTables)
intTblCnt = rsT.RecordCount
For t = 0 To intTblCnt - 1
strTbl = rsT.Fields("TABLE_NAME").value
'Validate the requested sheet exists in the workbook

If strTbl = strWorksheet & "$" Then


'Get the columns from the requested sheet
'The array provided for the Query is as follows (Table_Catalog, Tabl
e_Schema, Table_Name, Column_Name)
Set rsC = cn.OpenSchema(adSchemaColumns, Array(Empty, Empty, strTbl,
Empty))
intColCnt = rsC.RecordCount
ReDim results(0 To intColCnt - 1)
'Preserve the order of the columns by inserting them in the array us
ing their ordinal position
For c = 0 To intColCnt - 1
strCol = rsC.Fields("COLUMN_NAME").value
strIndex = rsC.Fields("ORDINAL_POSITION").value
results(CInt(strIndex) - 1) = strCol
rsC.MoveNext
Next
rsC.Close
End If
rsT.MoveNext
Next
Cleanup:
On Error Resume Next
rsT.Close
cn.Close
Set rsT = Nothing
Set rsC = Nothing
Set cn = Nothing
'Return results
getColumnHeaders = results
If test Then
For t = 1 To UBound(results)
Debug.Print results(t)
Next t
End If
Exit Function
errHandler:
MsgBox "Error: " & Err.Number & vbCrLf & Err.Description & vbCrLf & "Line: s
tdLibrary-getFileHeaders " & Erl & vbCrLf, vbCritical + vbOKOnly, "Error"
Resume Cleanup
End Function
Function IsIn(vCollection As Variant, ByVal sName As String) As Boolean
'------------------------------------------------------------------------' Procedure : IsIn Created by Jan Karel Pieterse
' Company : JKP Application Development Services (c) 2005
' Author
: Jan Karel Pieterse
' Created : 28-12-2005
' Purpose : Determines if object is in collection
'------------------------------------------------------------------------Dim oObj As Object
On Error Resume Next
Set oObj = vCollection(sName)
If oObj Is Nothing Then
IsIn = False
Else
IsIn = True
End If
If IsIn = False Then
sName = Application.Substitute(sName, "'", "")

Set oObj = vCollection(sName)


If oObj Is Nothing Then
IsIn = False
Else
IsIn = True
End If
End If
'How to use
''Check if worksheet ToC exists, if not, insert one
''If Not IsIn(Worksheets, "ToC") Then
End Function
Function IsAppRunning(ByVal sAppName) As Boolean
'------------------------------------------------------------------------' Procedure : Check_If_Application_Is_Open
' Company :
' Author
:
' Created :
' Purpose : Generalized Function to Check if an Instance of Application
'
is running in the machine
'
http://vbadud.blogspot.com/2007/04/generic-function-to-check-if.htm
l#0vyQsy3s6OAYilzg.99
'------------------------------------------------------------------------Dim oApp As Object
On Error Resume Next
Set oApp = GetObject(, sAppName)
If Not oApp Is Nothing Then
Set oApp = Nothing
IsAppRunning = True
End If
End Function
Sub CreateHyperlink(wsWorksheet As Worksheet, rngTargetCell As Range, sAddress A
s String, sTextToDisplay As String, Optional sSubAddress As String)
'------------------------------------------------------------------------' Procedure : GetAddress Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 09-01-2016
' Purpose : Creates a hyperlink at a specified address
'------------------------------------------------------------------------'If using a subaddress it should be in the format 'SheetName!address'
If Len(sTextToDisplay) < 1 Then sTextToDisplay = sAddress
If Len(sSubAddress) > 1 Then
wsWorksheet.Hyperlinks.Add Anchor:=rngTargetCell, Address:=sAddress, Sub
Address:=sSubAddress, TextToDisplay:=sTextToDisplay
Else
wsWorksheet.Hyperlinks.Add Anchor:=rngTargetCell, Address:=sAddress, Tex
tToDisplay:=sTextToDisplay
End If
End Sub
Function GetHyperlinkAddress(HyperlinkCell As Range) As String
'------------------------------------------------------------------------' Procedure : GetAddress Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 09-01-2016
' Purpose : Retrieves the address from a hyperlink

'------------------------------------------------------------------------On Error GoTo Cleanup


If Len(HyperlinkCell.Hyperlinks(1).SubAddress) > 1 Then
GetHyperlinkAddress = Replace(HyperlinkCell.Hyperlinks(1).Address & "#"
& HyperlinkCell.Hyperlinks(1).SubAddress, "mailto:", "")
Else
GetHyperlinkAddress = Replace(HyperlinkCell.Hyperlinks(1).Address, "mail
to:", "")
End If
Exit Function
Cleanup:
GetHyperlinkAddress = ""
End Function
Sub addBordersToRange(ByRef ws As Worksheet, ByVal rngRange As Range)
'------------------------------------------------------------------------' Procedure : addBordersToRange Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : General purpose function to add all borders (internal as well)
'------------------------------------------------------------------------With rngRange
.Borders(xlDiagonalDown).LineStyle = xlNone
.Borders(xlDiagonalUp).LineStyle = xlNone
With .Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlThin
End With
With .Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlThin
End With
With .Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlThin
End With
With .Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlThin
End With
With .Borders(xlInsideVertical)
.LineStyle = xlContinuous
.Weight = xlThin
End With
With .Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.Weight = xlThin
End With
End With
End Sub
Sub addSamuelGreentoRange(ByRef ws As Worksheet, ByVal rngRange As Range)
'------------------------------------------------------------------------' Procedure : addSamuelGreentoRange Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Set the color of the Range to light green
'-------------------------------------------------------------------------

With rngRange.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent6
.TintAndShade = 0.799981688894314
.PatternTintAndShade = 0
End With
End Sub
Function ArrayDim(v As Variant) As Long
'------------------------------------------------------------------------' Procedure : ArrayDim
' Company :
' Author
: Reverse("moc.LiborPlus.www") V0.1 PB
' Created : 10-May-2010
' Purpose : Returns number of dimensions of an array or 0 for
'
an undimensioned array or -1 if no array at all.
'------------------------------------------------------------------------Dim i As Long, tmp As Integer
i = 0
ArrayDim = 0
If Not IsArray(v) Then Exit Function
On Error GoTo errHandler
Do While True
i = i + 1
tmp = UBound(v, i)
Loop
errHandler:
ArrayDim = i - 1
End Function
Function RemoveUpperEqLowerDim(Var As Variant) As Variant
'------------------------------------------------------------------------' Procedure : ArrayDim
' Company :
' Author
: Reverse("moc.LiborPlus.www") V0.1 PB
' Created : 10-May-2010
' Purpose : Var must be a variant redimensioned to hold a 2D array
'
-If the dimensions are (M To N, P To P) or (P to P, M to N), a v
ariant
'
will be returned with the dimension with equal lower and upp
er bounds
'
removed. That is the returned array has dimensions (M to N)
.
'
-If neither dimension has equal lower and upper bounds, the orig
inal
'
array will be returned.
'------------------------------------------------------------------------Dim NewVar As Variant
Dim InxCrnt As Long
If ArrayDim(Var) <> 2 Then
' There is no code to handle this situation
Debug.Assert False
RemoveUpperEqLowerDim = Var
Exit Function
End If
If LBound(Var, 1) = UBound(Var, 1) Then

' The first dimension has equal bounds


ReDim NewVar(LBound(Var, 2) To UBound(Var, 2))
For InxCrnt = LBound(Var, 2) To UBound(Var, 2)
NewVar(InxCrnt) = Var(LBound(Var, 2), InxCrnt)
Next
RemoveUpperEqLowerDim = NewVar
ElseIf LBound(Var, 2) = UBound(Var, 2) Then
' The second dimension has equal bounds
ReDim NewVar(LBound(Var, 1) To UBound(Var, 1))
For InxCrnt = LBound(Var, 1) To UBound(Var, 1)
NewVar(InxCrnt) = Var(InxCrnt, LBound(Var, 1))
Next
RemoveUpperEqLowerDim = NewVar
Else
' Neither dimension has equal bounds
RemoveUpperEqLowerDim = Var
End If
End Function
Function Cnv2XLSM(ByVal workFolder As String, ByVal sFileName As String, ByVal K
eepOpen As Boolean) As Workbook
'------------------------------------------------------------------------' Procedure : Cnv2XLSM Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 09-13-2016
' Purpose : Saves an Excel File to XLSM
'------------------------------------------------------------------------Dim xWB As Workbook
On Error Resume Next
Set xWB = Workbooks(sFileName)
If xWB Is Nothing Then Set xWB = Workbooks.Open(workFolder & "\" & sFileName
, True, False, notify:=False)
'Make sure the workbook is an excel macro enabled workbook
If Right(xWB.Name, 5) <> ".xlsm" Then
'if the file name is not .xlsm, save as an xlsm
xWB.SaveAs fileName:=workFolder & "\" & Mid(xWB.Name, 1, InStr(xWB.Name,
".") - 1) & ".xlsm", FileFormat:=Excel.xlOpenXMLWorkbookMacroEnabled
'close the old .xlsx file
Workbooks(sFileName).Close
'delete the old file
Kill (workFolder & "\" & sFileName)
Else
'if it has the correct extension, simply perform a save as to ensure the
proper format
xWB.SaveAs fileName:=workFolder & "\" & xWB.Name, FileFormat:=Excel.xlOp
enXMLWorkbookMacroEnabled
End If
If KeepOpen Then
Set Cnv2XLSM = xWB
Else
xWB.Close
End If
End Function
Function strArray2varArray(myArr() As String) As Variant()
'------------------------------------------------------------------------' Procedure : strArray2varArray Created by Jaime Diaz
' Company :

' Author
: Jaime Diaz
' Created : 09-13-2016
' Purpose : Converts a String Array to a Variant Array
'------------------------------------------------------------------------On Error GoTo errHandler
strArray2varArray = WorksheetFunction.Index(myArr, 1, 0)
Exit Function
errHandler:
ReDim strArray2varArray(0)
End Function
Function safeUBound(myArr() As Variant) As Long
'------------------------------------------------------------------------' Procedure : safeUBound Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Safely get Upper Bound of array, returns -1 if invalid
'------------------------------------------------------------------------On Error GoTo errHandler
safeUBound = UBound(myArr)
Exit Function
errHandler:
safeUBound = -1
End Function
Function SafeToDouble(ByVal strTemp As Variant) As Double
'------------------------------------------------------------------------' Procedure : SafeToDouble Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Safely converts to Double, and returns -999999 as invalid
'------------------------------------------------------------------------On Error GoTo errHandler
If strTemp = vbNullString Or strTemp = "" Then GoTo errHandler
SafeToDouble = strTemp
Exit Function
errHandler:
SafeToDouble = -999999
End Function
Function SafeToSingle(ByVal strTemp As Variant) As Single
'------------------------------------------------------------------------' Procedure : SafeToSingle Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Safely converts to Single, and returns -999999 as invalid
'------------------------------------------------------------------------On Error GoTo errHandler
If strTemp = vbNullString Or strTemp = "" Then GoTo errHandler
SafeToSingle = strTemp
Exit Function
errHandler:
SafeToSingle = -999999
End Function
Function SafeToLong(ByVal strTemp As Variant) As Long
'-------------------------------------------------------------------------

' Procedure : SafeToLong Created by Jaime Diaz


' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Safely converts to Long, and returns -999999 as invalid
'------------------------------------------------------------------------On Error GoTo errHandler
If strTemp = vbNullString Or strTemp = "" Then GoTo errHandler
SafeToLong = strTemp
Exit Function
errHandler:
SafeToLong = -999999
End Function
Function SafeToInt(ByVal strTemp As Variant) As Integer
'------------------------------------------------------------------------' Procedure : SafeToInt Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 10-26-2016
' Purpose : Safely converts to Integer, and returns 0 when invalid
'------------------------------------------------------------------------On Error GoTo errHandler
If strTemp = vbNullString Or strTemp = "" Then GoTo errHandler
SafeToInt = strTemp
Exit Function
errHandler:
SafeToInt = 0
End Function
Function SafeToDate(ByVal strTemp As Variant) As String
'------------------------------------------------------------------------' Procedure : SafeToDate Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 10-27-2016
' Purpose : Safely validates a date, and returns "" when invalid
'------------------------------------------------------------------------Dim myDate As Date
On Error GoTo errHandler
If strTemp = vbNullString Or strTemp = "" Then GoTo errHandler
myDate = strTemp
SafeToDate = myDate
Exit Function
errHandler:
SafeToDate = ""
End Function
Function openCSVasADO(ByVal directory As String, ByVal fileName As String, ByVal
bHasHeaders As Boolean) As ADODB.Connection
'------------------------------------------------------------------------' Procedure : openCSVasADO Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 10-27-2016
' Purpose : Opens a CSV file as a DB, and retuns the handle through the cn var
iable provided
'------------------------------------------------------------------------Dim cn As ADODB.Connection

Dim
Dim
Dim
Dim

AppCalcMode As Long
AppScreenUpdating As Boolean
fso As Scripting.FileSystemObject
oFile As Object

On Error GoTo errHandler


'record original values for use upon exiting the function
AppCalcMode = Application.Calculation
AppScreenUpdating = Application.ScreenUpdating
'Change calculation mode to manual to avoid issues with re-calculating pages
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
'Separate Path and Filename
directory = Left(directory, InStrRev(directory, "\"))
fileName = Right(fileName, Len(fileName) - InStrRev(fileName, "\"))
If Not cn Is Nothing Then
'If cn is not closed, then close and release handle
If cn.State <> adStateClosed Then cn.Close
Set cn = Nothing
End If
'Create handle
Set cn = CreateObject("ADODB.Connection")
'Verify that the connection to the CSV is closed
If cn.State = adStateClosed Then
'Prepare the record set to read it, there has to exist a schema.ini in t
he folder with the file that tells the driver how to handle it,
'verify existance and create if needed
'[_all.csv]
'Format = CSVDelimited
'ColNameHeader = False
If Len(Dir(directory & "schema.ini")) = 0 Then
'Schema.ini does not exist, create it
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.CreateTextFile(directory & "schema.ini")
oFile.WriteLine "[" & fileName & "]"
'Create entry in schema.
ini for the CSV file
oFile.WriteLine "Format = CSVDelimited"
'Specify the format of t
he file, valid values are
' TabDelimited
' CSVDelimited
' Delimited(custom cha
racter) -or- With no delimiter specified: Delimited()
' FixedLength
If bHasHeaders Then oFile.WriteLine "ColNameHeader = True" Else oFil
e.WriteLine "ColNameHeader = False"
'Indicate if the file has headers, valid
values are True, False
'The next entry designates fields in a table by using the column num
ber (Coln) option,
'which is optional for character-delimited files and required for fi
xed-length files.
'The example shows the Schema.ini entries for two fields, a 10-chara
cter CustomerNumber
'text field and a 30-character CustomerName text field:
' Col1=CustomerNumber Text Width 10
' Col2=CustomerName Text Width 30
'
'n=ColumnName type
[Width #]
'Valid data types are:
' Microsoft Jet data types:
'
Bit

'
Byte
'
Short
'
Long
'
Currency
'
Single
'
Double
'
DateTime
'
Text
'
Memo
' ODBC data types Char (same as Text)
'
Float (same as Double)
'
Integer (same as Short)
'
LongChar (same as Memo)
'
Date date format
'Width:
' The literal string value Width. Indicates that the following num
ber designates
' the width of the column (optional for character-delimited files;
required for fixed-length files).
'#:
' The integer value that designates the width of the column (requi
red if Width is specified).
oFile.Close
Set fso = Nothing
Set oFile = Nothing
End If
'Open CSV File
With cn
.ConnectionString = "Driver={Microsoft Text Driver (*.txt; *.csv)};D
bq=" & directory & ";Extensions=asc,csv,tab,txt;HDR=NO;" ' & Chr(34) & "text" &
Chr(34) & ";" 'FMT=Delimited" & Chr(34) & ";"
.Open
End With
'Following some examples of SQL statements to open the Record Set:
' Dim RS As ADODB.Recordset
' Set RS = CreateObject("ADODB.Recordset")
' RS.Open "Select DISTINCT F1 FROM [" & fileName & "]", cn, adOpenStat
ic, adLockOptimistic, adCmdText
' RS.Open "Select F1, F2 FROM [" & fileName & "]", cn, adOpenStatic, a
dLockOptimistic, adCmdText
'You can copy all data in the record set to a variant array as follows:
' vTemp = RS.GetRows
'Or you can iterate through the Record Set by:
' Do While Not RS.EOF
'
Some processing with current record
'
RS.Fields(zero based number).Value
'
RS.MoveNext
' Loop
'This data can be pasted to a worksheet, but it must be transposed first
' vTemp = Application.Transpose(vTemp)
' totalRecs = RS.RecordCount
'Ensure that the area to be pasted matches the area copied to the array,
following we have a 2 column, by x rectangle area
' Worksheets("Sheet1").Range("A1:B" & CStr(1 + totalRecs)).Value = vTe
mp
If cn.State <> adStateOpen Then Set cn = Nothing
End If
Cleanup:
On Error Resume Next
openCSVasADO = cn

Set cn = Nothing
Exit Function
errHandler:
MsgBox "Error: " & Err.Number & vbCrLf & Err.Description & vbCrLf & "Line: s
tdLibrary-openCSVasADO " & Erl & vbCrLf, vbCritical + vbOKOnly, "Error"
Resume Cleanup
End Function
Function openXLSXasADO(ByVal directory As String, ByVal fileName As String, ByVa
l bHasHeaders As Boolean) As ADODB.Connection
'------------------------------------------------------------------------' Procedure : openCSVasADO Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 10-27-2016
' Purpose : Opens a XLSX file as a DB, and retuns the handle through the cn va
riable provided
'------------------------------------------------------------------------Dim cn As ADODB.Connection
Dim AppCalcMode As Long
Dim AppScreenUpdating As Boolean
Dim sHeader As String
On Error GoTo errHandler
'record original values for use upon exiting the function
AppCalcMode = Application.Calculation
AppScreenUpdating = Application.ScreenUpdating
'Change calculation mode to manual to avoid issues with re-calculating pages
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
'Separate Path and Filename
directory = Left(directory, InStrRev(directory, "\"))
fileName = Right(fileName, Len(fileName) - InStrRev(fileName, "\"))
If Not cn Is Nothing Then
'If cn is not closed, then close and release handle
If cn.State <> adStateClosed Then cn.Close
Set cn = Nothing
End If
'Create handle
Set cn = CreateObject("ADODB.Connection")
'Verify that the connection to the files is closed
If cn.State = adStateClosed Then
If bHasHeaders Then sHeader = "YES" Else sHeader = "NO"
'Indicate if
the file has headers, valid values are True, False
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & director
y & fileName & ";" & "Extended Properties=" & Chr(34) & "Excel 8.0;HDR=" & sHead
er & ";" & Chr(34) & ";"
'The following two lines are needed to access the data ince a valid hand
le is returned
'Dim objRecSet As Object
'Set objRecSet = CreateObject("ADODB.Recordset")
'objRecSet.Open "SELECT * FROM [" & sDesiredTab & "$] WHERE [FieldName]=
'" & Condition & "'", objCn, adOpenStatic, adLockOptimistic, adCmdText
End If
Cleanup:
On Error Resume Next
Set openXLSXasADO = cn
Set cn = Nothing
Exit Function
errHandler:

MsgBox "Error: " & Err.Number & vbCrLf & Err.Description & vbCrLf & "Line: s
tdLibrary-openXLSXasADO " & Erl & vbCrLf, vbCritical + vbOKOnly, "Error"
Resume Cleanup
End Function
Function AddChartObject(ByVal wbMain As Workbook, ByVal wsMain As Worksheet, ByV
al rngRange As Range, ByVal strChartSheetName As String, ByVal strChartTitle As
String, ByVal vSeriesName As Variant) As Object
'------------------------------------------------------------------------' Procedure : AddChartObject Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Create initial line chart and move to a separate sheet
'
If the range has multiple columns then there are multiple
'
series, provide a name for them, or a standard name will
'
be used
'------------------------------------------------------------------------Dim wbAnalysis As Workbook
Dim dPrimaryAxisDivision As Double
Dim wsChartSheet As Object, cmbChartDD As Object
Dim strTemp As String
Dim x As Integer, y As Integer
On Error GoTo errHandler
wsMain.Activate
rngRange.Select
ActiveSheet.Shapes.AddChart2(227, xlLine).Select
With ActiveChart
.ChartTitle.Caption = strChartTitle
If ArrayDim(vSeriesName) < 1 Then
If VarType(vSeriesName) = vbString Then
.FullSeriesCollection(1).Name = vSeriesName
Else
.FullSeriesCollection(1).Name = "Series 1"
End If
.FullSeriesCollection(1).ChartType = xlLine
.FullSeriesCollection(1).AxisGroup = 1
Else
For x = LBound(vSeriesName) To UBound(vSeriesName)
y = x - LBound(vSeriesName) + 1
If y <= .FullSeriesCollection.Count Then
If VarType(vSeriesName(x)) = vbString Then
.FullSeriesCollection(y).Name = vSeriesName(x)
Else
.FullSeriesCollection(y).Name = "Series " & CStr(y)
End If
.FullSeriesCollection(y).ChartType = xlLine
.FullSeriesCollection(y).AxisGroup = 1
End If
Next x
End If
'use these lines if a secondary axis is added
'.Axes(xlValue, xlSecondary).MinimumScale = -10
'.Axes(xlValue, xlSecondary).MaximumScale = 1
'.Axes(xlValue, xlSecondary).TickLabelPosition = xlNone
dPrimaryAxisDivision = (.Axes(xlValue).MaximumScale - .Axes(xlValue).Min
imumScale) / 10
.Axes(xlValue).MaximumScale = .Axes(xlValue).MaximumScale + dPrimaryAxis
Division * 3

Set wsChartSheet = .Location(Where:=xlLocationAsNewSheet)


Dim objSheet As Object
If IsIn(ActiveWorkbook.Sheets, strChartSheetName) Then
Application.DisplayAlerts = False
ActiveWorkbook.Sheets(strChartSheetName).Delete
Application.DisplayAlerts = True
End If
ActiveSheet.Name = strChartSheetName
ActiveSheet.Move After:=Sheets(wsMain.Name)
End With
'To add buttons to the chart use the following lines of code
'these are full examples of how to use a fully referenced sub/func with or w
ithout parameters
'addButtonToChartObject ActiveSheet, "btnName1", "Line 1" & vbCrLf & "Line 2
", "'Personal.xlsb'!SelectFileToOpen", 30, 30, 80, 35
'addButtonToChartObject wsChart, "btnLineUp", "Line Up" & vbCrLf & "Off", "B
ook2.xlsm!'ShowHideGraphSeries " & Chr(34) & "Line Up" & Chr(34) & "," & Chr(34)
& "btnLineUp" & Chr(34) & "," & Chr(34) & "Line Up" & Chr(34) & "'", 30, 30, 80
, 35
'these are generic calls
'addButtonToChart ActiveSheet, "btnName2", "Line 1" & vbCrLf & "Line 2", "RE
PLACE{sub or func name}", LEFT, TOP, WIDTH, HEIGHT
'addButtonToChart ActiveSheet, "btnName3", "Line 1" & vbCrLf & "Line 2", "RE
PLACE{sub or func name}", LEFT, TOP, WIDTH, HEIGHT
'addButtonToChart ActiveSheet, "btnName3", "Line 1" & vbCrLf & "Line 2", "RE
PLACE{sub or func name}", LEFT, TOP, WIDTH, HEIGHT
'Add a drop down for selecting between different series
'Set cmbChartDD = ActiveSheet.DropDowns.Add(6, 8, 150, 20)
'With cmbChartDD
'
.Name = "cmbChartDD"
'
.AddItem "Name 1"
'
.AddItem "Name 2"
'
.AddItem "..."
'
.AddItem "Name x"
'
.OnAction = "REPLACE{sub or func name}"
'This is triggered when the
DropDown changes value
'End With
Set AddChartObject = wsChartSheet
'Add the Module for the Functions that are referenced in the buttons, otherw
ise this line is not needed
'AddCodeModule wbMain
Cleanup:
On Error Resume Next
Set wbAnalysis = Nothing
Set wsChartSheet = Nothing
'Set cmbChartDD = Nothing
Exit Function
errHandler:
If Err.Number <> 0 Then MsgBox "Sub: AddChartObject()" & vbCrLf & _
"Line Number: stdLibrary-AddChartObject " & Erl & vbCrLf & _
"Error: " & Err.Number & vbCrLf & _
Err.Description, vbCritical + vbOKOnly, "ERROR"
If Not AddChartObject Is Nothing Then AddChartObject.Delete
Set AddChartObject = Nothing
Resume Cleanup
End Function
Sub addButtonToChartObject(ByVal wsSheet As Object, ByVal btnName As String, ByV
al btnText As String, ByVal btnOnAction As String, ByVal dLeft As Double, ByVal
dTop As Double, ByVal dWidth As Double, ByVal dHeight As Double)

'------------------------------------------------------------------------' Procedure : addButtonToChart Created by Jaime Diaz


' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Add a button to a chart object
'------------------------------------------------------------------------Dim btnButton1 As Button
Set btnButton1 = wsSheet.Buttons.Add(dLeft, dTop, dWidth, dHeight)
With btnButton1
.Text = btnText
.Name = btnName
If InStr(1, btnOnAction, "!", vbTextCompare) Then
'if the name of the sub/function to execute is referencing a workboo
k then no need to re-reference it
'An exmaple of BookName!'ProcedureName Param1,Param2,..."
'Book2.xlsm!'ShowHideGraphSeries "Line Up","btnLineUp","Line Up"'
.OnAction = btnOnAction
Else
'Otherwise use the active workbook as the referenced workbook
.OnAction = "'" & wsSheet.Parent.Name & "'!" & btnOnAction
End If
.Font.size = 8
End With
Set btnButton1 = Nothing
End Sub
Function OrificeCalc(dStaticPress As Double, dDiffPress As Double, dPipeDia As D
ouble, dOrificeDia As Double, strDiffPressLoc As String, dTemperature As Double,
vElevationZone As Variant, dSpecGravity As Double, dN2MolePercent As Double, dC
02MolePercent As Double, dATM_Press As Double) As Double
'------------------------------------------------------------------------' Procedure : OrificeCalc Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Provides Orifice Calculation
'------------------------------------------------------------------------'Perform Orifice Calculation and return value
' Input:
'
dStaticPress
'
dDiffPress
'
dPipeDia
'
dOrificeDia
'
strDiffPressLoc(ation of pressure meter "u"pstream or "d"ownstream)
'
dTemperature
'
sElevationZone
'
dSpecGravity
'
dN2MolePercent
'
dC02MolePercent
'
dATM_Press
' Returns:
'
Calculated flow per NX19 extension to AGA3
Dim Beta As Double, FG As Double, Fpv As Double, FTF As Double, b As Double,
e As Double, x As Double, y As Double, f As Double, KE As Double, c As Double
' for SCFH
Dim Fp As Double, Ft As Double, tau As Double, pi1 As Double, m As Double, N
As Double, BB As Double, b1 As Double, d1 As Double, KO As Double, FB As Double
, E1 As Double

Dim
Dim
Dim
Dim

dFirstResult As Double, dSecondResult As Double, CalcPressPSIG As Double


lCntr As Long
dRankinFOffset As Double: dRankinFOffset = 459.67
dRefPressPSIA As Double: dRefPressPSIA = 14.73

On Error GoTo errHandler


'Fpv Orifice Page Calcs
Fp = Round((156.47 / (160.8 - 7.22 * dSpecGravity + dC02MolePercent - 0.392
* dN2MolePercent)) * dStaticPress, 1)
Ft = Round((dTemperature + dRankinFOffset) * (226.29 / (99.15 + 211.9 * dSpe
cGravity - dC02MolePercent - 1.681 * dN2MolePercent)) - dRankinFOffset, 1)
tau = (Ft + dRankinFOffset) / 500
pi1 = (Fp + dRefPressPSIA) / 1000
On Error Resume Next
dFirstResult = 1 - 0.00075 * pi1 ^ 2.3 * (2 - 1 / 2.7182818 ^ (20 * (1.09 tau))) - 1.317 * (1.09 - tau) ^ 4 * pi1 * (1.69 - pi1 ^ 2)
dSecondResult = 1 - 0.00075 * pi1 ^ 2.3 * (2.7182818 ^ -(20 * (tau - 1.09)))
- 0.0011 * (tau - 1.09) ^ 0.5 * pi1 ^ 2 * (2.17 + 1.4 * (tau - 1.09) ^ 0.5 - pi
1) ^ 2
On Error GoTo errHandler
m = 0.0330378 / tau ^ 2 - 0.0221323 / tau ^ 3 + 0.0161353 / tau ^ 5
N = (0.265827 / tau ^ 2 + 0.0457697 / tau ^ 4 - 0.133185 / tau) / m
BB = (3 - m * N ^ 2) / (9 * m * pi1 ^ 2)
If dTemperature > 85 Then E1 = dSecondResult Else E1 = dFirstResult
b1 = (9 * N - 2 * m * N ^ 3) / (54 * m * pi1 ^ 3) - E1 / (2 * m * pi1 ^ 2)
d1 = (b1 + (b1 ^ 2 + BB ^ 3) ^ 0.5) ^ (1 / 3)
Fpv = (BB / d1 - d1 + N / (3 * pi1)) ^ 0.5 / (1 + (0.00132 / tau ^ 3.25))
'Orifice Calculation Page Calcs
If LCase(strDiffPressLoc) = "d" Then CalcPressPSIG = dStaticPress Else CalcP
ressPSIG = dStaticPress - dDiffPress / 27.7
Beta = dOrificeDia / dPipeDia
FG = (1 / dSpecGravity) ^ 0.5
'Fpv
FTF = (519.67 / (dTemperature + 459.67)) ^ 0.5
b = 530 / dPipeDia ^ 0.5
e = dOrificeDia * (830 - 5000 * Beta + 9000 * Beta ^ 2 - 4200 * Beta ^ 3 + b
)
x = dDiffPress / (27.7 * (CalcPressPSIG + dATM_Press))
y = (1 + x) ^ 0.5 - (0.41 + 0.35 * Beta ^ 4) * x / (1.3 * (1 + x) ^ 0.5)
f = 0.5993 + 0.007 / dPipeDia + (0.364 + 0.076 / (dPipeDia ^ 0.5)) * Beta ^
4
If (0.07 + 0.5 / dPipeDia - Beta) > 0 Then
KE = f + 0.4 * (1.6 - 1 / dPipeDia) ^ 5 * ((0.07 + 0.5 / dPipeDia) - Bet
a) ^ 2.5
ElseIf (0.5 - Beta) > 0 Then
KE = f - (0.009 + 0.034 / dPipeDia) * (0.5 - Beta) ^ 1.5
ElseIf (Beta - 0.7 > 0) Then
KE = f + (65 / (dPipeDia ^ 2) + 3) * (Beta - 0.7) ^ 2.5
Else
KE = f
End If
KO = KE / (1 + 15 * e / (1000000 * dOrificeDia))
FB = 338.17 * dOrificeDia ^ 2 * KO
c = FB * y
OrificeCalc = Round(0.000001 * FB * y * FTF * FG * Fpv * (dDiffPress * (Calc
PressPSIG + dRefPressPSIA)) ^ 0.5, 4)
Cleanup:
Exit Function
errHandler:

If Err.Number <> 0 Then MsgBox "OrificeCalc(): " & _


"Line Number: GasCalcs-OrificeCalc " & Erl & vbCrLf & _
"Error: " & Err.Number & vbCrLf & _
Err.Description & vbCrLf, vbCritical + vbOKOnly, "ERROR"
OrificeCalc = 0
Resume Cleanup
End Function
Function FreqMeterCalc(dPulseRatio As Double, dPulseCount As Double, dStaticPres
s As Double, dTemperature As Double, zElev As Double, vElevationZone As Variant,
dSpecGravity As Double, dN2MolePercent As Double, dC02MolePercent As Double, dA
TM_Press As Double) As Double
'------------------------------------------------------------------------' Procedure : FreqMeterCalc Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Provides Frequency Meter Flow Calculation
'------------------------------------------------------------------------'Perform Frequency Meter Flow Calculation and return value
' Input:
'
K, pulse/ft^3, Pulse Ratio
'
F, pulses/sec, Pulse Count
'
dStaticPress
'
dTemperature
'
sElevationZone
'
dSpecGravity
'
dN2MolePercent
'
dC02MolePercent
'
dATM_Press
' Returns:
'
Calculated flow per NX19 extension to AGA3
Dim k As Double, f As Double, p As Double, t As Double, N As Double, CO As D
ouble, ACFH As Double, Fpv As Double, z As Double
Dim Fp As Double, Ff As Double, Ft As Double, a As Double, Pr As Double, Tr
As Double, Pc As Double, Tc As Double, Qhour As Double, Qday As Double
Dim dFirstResult As Double, dSecondResult As Double, CalcPressPSIG As Double
Dim lCntr As Long
Dim dRankinFOffset As Double: dRankinFOffset = 459.67
Dim dRefPressPSIA As Double: dRefPressPSIA = 14.73
On Error GoTo errHandler
k = dPulseRatio
f = dPulseCount
p = dStaticPress
t = dTemperature
ACFH = (f * k * 3600 / 1000) * 1000000
N = dN2MolePercent / 100
CO = dC02MolePercent / 100
Fp = (p + 14.73) / 14.73
Ff = f
Ft = 520 / (t + 460)
z = NX19Z(p, t, dSpecGravity, dN2MolePercent, dC02MolePercent, zElev)
Fpv = 1 / z ^ 0.5
Pc = 685.8 - 23.1 * dSpecGravity - 171.4 * N + 422.5 * CO
Tc = 152.5 + 345.4 * dSpecGravity - 272.2 * N - 170.3 * CO
Pr = p / Pc
Tr = (t + 460) / Tc
a = Exp(1.163 - 2.328 * Tr)
Qhour = (f * (3600 / k) * (Fpv) ^ 2 * Ft * Fp) / 1000000

Qday = Qhour * 24
FreqMeterCalc = Qhour
Cleanup:
Exit Function
errHandler:
If Err.Number <> 0 Then MsgBox "FreqMeterCalc(): " & _
"Line Number: GasCalcs-FreqMeterCalc " & Erl & vbCrLf & _
"Error: " & Err.Number & vbCrLf & _
Err.Description & vbCrLf, vbCritical + vbOKOnly, "ERROR"
FreqMeterCalc = 0
Resume Cleanup
End Function
Function GasRegConst(p, t, SG, Mn, Mc, zElev)
'------------------------------------------------------------------------' Procedure : GasRegConst
' Company : PG&E
' Author
:
' Created :
' Purpose : Supercompressibility (Fpv) NX-19, modified by Jaime Diaz
'
to create a function that accepts parameters vs a procedure
'
that scans a spreadsheet
'------------------------------------------------------------------------'Supercompressibility (Fpv) NX-19 for Gas Register Constant Project
'(Calculation of supercompressibility Fpv is based on the NX19 extension to
AGA3)
' Input Values
' SG = Specific Gravity
' p = Pressure in psig
' T = Temperature in deg F
' Mc = mole percent of CO2 from SCADA
' Mn = mole percent of N2 from SCADA
' zelev = elevation in feet
Dim Kp As Double, Kt As Double, Fp As Double, Ft As Double, Pa As Double, p1
As Double, Padj As Double, Tadj As Double, pi1 As Double, tau As Double
Dim e As Double, m As Double, N As Double, BB As Double, b1 As Double, d1 As
Double, FPV1 As Double, Zs As Double, Tm As Double, Pm As Double, GasRc As Doub
le
On Error GoTo errHandler
'SCADA NX-19 calculation of Z
Kp = Mc - 0.392 * Mn
Kt = Mc + 1.681 * Mn
Fp = 156.47 / (160.8 - 7.22 * SG + Kp)
Ft = 226.29 / (99.15 + 211.9 * SG - Kt)
'calculate atmospheric pressure based on elevation
Pa = 14.73 * (1 - 0.00000687559 * zElev) ^ 5.25587
p1 = p + Pa - 14.7
Padj = p1 * Fp
Tadj = ((t + 460) * Ft) - 460
pi1 = (Padj + 14.7) / 1000
tau = (Tadj + 460) / 500
If tau >= 1.09 Then
e = 1 - 0.00075 * pi1 ^ 2.3 * (2.7182818 ^ (-20 * (tau - 1.09))) - 0.001
1 * (tau - 1.09) ^ 0.5 * pi1 ^ 2 * (2.17 + 1.4 * (tau - 1.09) ^ 0.5 - pi1) ^ 2
Else
e = 1 - 0.00075 * pi1 ^ 2.3 * (2 - 1 / 2.7182818 ^ (20 * (1.09 - tau)))
- 1.317 * (1.09 - tau) ^ 4 * pi1 * (1.69 - pi1 ^ 2)
End If

m = 0.0330378 * tau ^ (-2) - 0.0221323 * tau ^ (-3) + 0.0161353 * tau ^ (-5)


N = (0.265827 * tau ^ (-2) + 0.0457697 * tau ^ (-4) - 0.133185 * tau ^ (-1))
/ m
BB =
b1 =
d1 =
FPV1

(3 - m * N ^ 2) / (9 * m * pi1 ^ 2)
(9 * N - 2 * m * N ^ 3) / (54 * m * pi1 ^ 3) - e / (2 * m * pi1 ^ 2)
(b1 + (b1 ^ 2 + BB ^ 3) ^ 0.5) ^ (1 / 3)
= ((BB / d1) - d1 + N / (3 * pi1)) ^ 0.5 / (1 + (0.00132 / tau ^ 3.25))

'Calculate multipliers
Zs = 1 / FPV1 ^ 2 'supercompressibility
Tm = 519.67 / (t + 459.67) 'temperature multiplier
Pm = (p + Pa) / 14.73 'pressure multiplier
GasRc = FPV1 ^ 2 * Pm * Tm 'Gas Register Constant
' output
GasRegConst = GasRc 'GasRC factor
Cleanup:
Exit Function
errHandler:
If Err.Number <> 0 Then MsgBox "GasRegConst(): " & _
"Line Number: GasCalcs-GasRegConst " & Erl & vbCrLf & _
"Error: " & Err.Number & vbCrLf & _
Err.Description & vbCrLf, vbCritical + vbOKOnly, "ERROR"
GasRegConst = 0
Resume Cleanup
End Function
Function NX19Z(p, t, SG, Mn, Mc, zElev)
'------------------------------------------------------------------------' Procedure : NX19Z
' Company : PG&E
' Author
:
' Created :
' Purpose : Supercompressibility (Fpv) NX-19
'------------------------------------------------------------------------'Supercompressibility (Fpv) NX-19 for Gas Register Constant Project
'(Calculation of supercompressibility Fpv is based on the NX19 extension to
AGA3)
' Input Values
' SG = Specific Gravity
' p = Pressure in psig
' T = Temperature in deg F
' Mc = mole percent of CO2 from SCADA
' Mn = mole percent of N2 from SCADA
' zelev = elevation in feet
Dim Kp As Double, Kt As Double, Fp As Double, Ft As Double, Pa As Double, p1
As Double, Padj As Double, Tadj As Double, pi1 As Double, tau As Double
Dim e As Double, m As Double, N As Double, BB As Double, b1 As Double, d1 As
Double, FPV1 As Double, Zs As Double
On Error GoTo errHandler
'SCADA NX-19 calculation of Z
Kp = Mc - 0.392 * Mn
Kt = Mc + 1.681 * Mn
Fp = 156.47 / (160.8 - 7.22 * SG + Kp)
Ft = 226.29 / (99.15 + 211.9 * SG - Kt)
'calculate atmospheric pressure based on elevation
Pa = 14.73 * (1 - 0.00000687559 * zElev) ^ 5.25587
p1 = p + Pa - 14.7

Padj = p1 * Fp
Tadj = ((t + 460) * Ft) - 460
pi1 = (Padj + 14.7) / 1000
tau = (Tadj + 460) / 500
If tau >= 1.09 Then
e = 1 - 0.00075 * pi1 ^ 2.3 * (2.7182818 ^ (-20 * (tau - 1.09))) - 0.001
1 * (tau - 1.09) ^ 0.5 * pi1 ^ 2 * (2.17 + 1.4 * (tau - 1.09) ^ 0.5 - pi1) ^ 2
Else
e = 1 - 0.00075 * pi1 ^ 2.3 * (2 - 1 / 2.7182818 ^ (20 * (1.09 - tau)))
- 1.317 * (1.09 - tau) ^ 4 * pi1 * (1.69 - pi1 ^ 2)
End If
m = 0.0330378 * tau ^ (-2) - 0.0221323 * tau ^ (-3) + 0.0161353 * tau ^ (-5)
N = (0.265827 * tau ^ (-2) + 0.0457697 * tau ^ (-4) - 0.133185 * tau ^ (-1))
/ m
BB = (3 - m * N ^ 2) / (9 * m * pi1 ^ 2)
b1 = (9 * N - 2 * m * N ^ 3) / (54 * m * pi1 ^ 3) - e / (2 * m * pi1 ^ 2)
d1 = (b1 + (b1 ^ 2 + BB ^ 3) ^ 0.5) ^ (1 / 3)
FPV1 = ((BB / d1) - d1 + N / (3 * pi1)) ^ 0.5 / (1 + (0.00132 / tau ^ 3.25))
'Calculate multipliers
Zs = 1 / FPV1 ^ 2 'supercompressibility
'Tm = 519.67 / (T + 459.67) 'temperature multiplier
'Pm = (p + Pa) / 14.73 'pressure multiplier
'GasRC = FPV1 ^ 2 * Pm * Tm 'Gas Register Constant
' output
NX19Z = Zs 'NX19Z factor
Cleanup:
Exit Function
errHandler:
If Err.Number <> 0 Then MsgBox "NX19Z(): " & _
"Line Number: GasCalcs-NX19Z " & Erl & vbCrLf & _
"Error: " & Err.Number & vbCrLf & _
Err.Description & vbCrLf, vbCritical + vbOKOnly, "ERROR"
NX19Z = 0
Resume Cleanup
End Function
Function LinePackCalc(ByVal dSegLength As Double, dSegDiameter As Double, ByVal
dUpstreamPressure As Double, ByVal dDownstreamPressure As Double, ByVal dTempera
ture As Double, ByVal LineGasZone As Single, SG As Double, Mn As Double, Mc As D
ouble, dAtmPressure As Double) As Double
'------------------------------------------------------------------------' Procedure : LinePackCalc Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Calculates line inventory as a function of Pv=nRT*Fpv, using a
'
conversion factor of 1 Nm^3 = 37.326 SCF
'------------------------------------------------------------------------Dim Pavg As Double, p As Double, v As Double, r As Double, t As Double, N As
Double, PI As Double, Patm As Double, Fpv As Double, dBasePressure As Double
Const Nm3_SCF = 37.326
dBasePressure = 14.73
dUpstreamPressure = dUpstreamPressure + dAtmPressure
dDownstreamPressure = dDownstreamPressure + dAtmPressure
PI = 4 * Atn(1) 'Calculate PI
Pavg = 2 / 3 * (dUpstreamPressure + dDownstreamPressure - (dUpstreamPressure
* dDownstreamPressure) / (dUpstreamPressure + dDownstreamPressure))

Fpv = NX19Z(Pavg, dTemperature, SG, Mn, Mc, 0)


p = Pavg * 0.0689475729 'Convert to bars
v = PI * (dSegDiameter * 2.54 / 200) ^ 2 * dSegLength * 1609 'Convert length
and diameter to meters for calculation
r = 8.3144598 * 10 ^ -5
t = (dTemperature - 32) * 5 / 9 + 273.15
N = (p * v) / (r * t * Fpv)
LinePackCalc = (N / 1000 * 22.441) * Nm3_SCF / 1000000 'Line Pack in MMSCF
End Function
Sub ArraySort(ByRef strArray() As String)
'------------------------------------------------------------------------' Procedure : ArraySort Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Performs a Bubble Sort on the given array
'------------------------------------------------------------------------Dim strTemp As String
Dim i As Long
Dim j As Long
Dim lngMin As Long
Dim lngMax As Long
lngMin = LBound(strArray)
lngMax = UBound(strArray)
For i = lngMin To lngMax - 1
For j = i + 1 To lngMax
If (strArray(i) > strArray(j)) And strArray(i) <> "" And strArray(j)
<> "" Then
strTemp = strArray(i)
strArray(i) = strArray(j)
strArray(j) = strTemp
End If
If strArray(j) = "" Then Exit For
Next j
Next
End Sub
Function RedlichKwongACI(ByVal dSegLength As Double, ByVal dSegDiameter As Doubl
e, ByVal dUpstreamPressure As Double, ByVal dDownstreamPressure As Double, ByVal
dTemperature As Double, ByVal SG As Double) As Double()
'------------------------------------------------------------------------' Procedure : RedlichKwongACI
' Company :
' Author
: PG&E
' Created :
' Purpose :
'------------------------------------------------------------------------' Good for Natural Gas, NOT iterative, must know Ax/Bx constants prior to en
tering
Dim Ax As Single, Bx As Single
Dim ab As Single, b1 As Single, a1 As Single, q As Single
Dim r As Single, a As Single, D As Single, d1 As Single
Dim rmd1 As Single, rpd1 As Single, Zfact As Single
Dim Psuc As Double, Tsuc As Double, Pdis As Double, Tdis As Double, TCrit As
Double, PCrit As Double, Zs As Double, Zd As Double
Dim Psa As Double, Tsa As Double, Pda As Double, Tda As Double, GasPressureA
bs As Double, GasTempR As Double, RedlichKwongZ2 As Double

Dim Zavg As Double, zmean As Double, Pmean As Double, leng As Double, dia As
Double, PI As Double, pipevolu As Double, Inv As Double
Dim dResults() As Double
Dim i As Integer
Const Onethird As Single = 1 / 3
Const OneNinth As Single = 1 / 9
Const One27th As Single = 1 / 27
Const MaxRKerror As Single = 0.001
'Input
'SG
Psuc =
Tsuc =
Pdis =
Tdis =

Values
dUpstreamPressure
dTemperature
dDownstreamPressure
dTemperature

'
'
'
'
'

Specific Gravity
U/S Pressure
U/S Temperature
D/S Pressure
D/S Temperature

TCrit = 170 + 313 * SG 'deg R, pseudo critical temperature from Solar Calc B
ook Pg3-3
PCrit = 700 - 48.3 * SG 'psia, pseudo critical pressure from Solar Calc Book
Pg3-3
' Suction Pressure
Psa = Psuc + 14.73

' Convert to Absolute

' Suction Temperature


Tsa = Tsuc + 460

' Convert to Absolute, Tsa

' Discharge Pressure


Pda = Pdis + 14.73

' Convert to Absolute

' Discharge Temperature


Tda = Tdis + 460
' Convert to Absolute Tda
'Redlich-Kwong calculation of Z
For i = 1 To 2
If i = 1 Then
'U/S side
GasPressureAbs = Psa
GasTempR = Tsa
Else
'D/S side
GasPressureAbs = Pda
GasTempR = Tda
End If
Ax = Sqr(0.42748022 * TCrit ^ 2.5 / PCrit)
Bx = 0.08664035 * TCrit / PCrit
ab = Ax * Ax / Bx
b1 = Bx * GasPressureAbs / GasTempR
a1 = b1 * ab / GasTempR ^ 1.5
q = (a1 - b1 - b1 * b1) * Onethird
r = One27th + (a1 * b1 - q) * 0.5
a = q - OneNinth
D = a ^ 3 + r * r
Select Case D
Case Is > 0
d1 = Sqr(D)
rmd1 = Abs(r - d1)
rpd1 = Abs(r + d1)
Zfact = Sign(rmd1 ^ Onethird, r - d1) + Sign(rpd1 ^ Onethird, r
+ d1)

If Zfact < 0 And a < 0 Then Zfact = Zfact + Sqr(Abs(1 - 9 * q))


Zfact = Zfact + Onethird
If Zfact > 0.254 Then RedlichKwongZ2 = Zfact Else RedlichKwongZ2
= 0.254
Case Is < 0
d1 = 0
RedlichKwongZ2 = 2 * Sqr(-a) * Cos(Atan2(Sqr(-D), r - d1) * Onet
hird) + Onethird
Case Else
If a >= 0 Then
RedlichKwongZ2 = 2 * Abs(r) ^ Onethird + Onethird
Else
RedlichKwongZ2 = 2 * Sqr(-r) + Onethird
End If
End Select
If i = 1 Then
' U/S Z
Zs = RedlichKwongZ2
Else
' D/S Z
Zd = RedlichKwongZ2
End If
Next i
'Zavg - Z AVERAGE
Zavg = (Zs + Zd) / 2

' (Zs + Zd)/2

zmean = 2 / 3 * (Zs + Zd - (Zs * Zd) / (Zs + Zd))


'Inventory Calcs
Psa = Psuc + 14.73
Pda = Pdis + 14.73
Pmean = 2 / 3 * (Psa + Pda - (Psa) * (Pda) / (Psa + Pda)) 'mean pressure
leng = dSegLength 'Section Length in miles
dia = dSegDiameter 'Section diameter inches
PI = 4 * Atn(1) 'Calculate PI used to be PI = 3.14159265358979 modified by J
aime Diaz
pipevolu = (dia / 2 / 12) ^ 2 * PI * leng * 5280 'pipe volume in ft3
Inv = pipevolu * Pmean / 1000000 / 14.73 / zmean
skip1:
ReDim dResults(1 To 8)
dResults(1) = pipevolu
dResults(2) = Zs
dResults(3) = Zd
dResults(4) = Zavg
dResults(5) = zmean
dResults(6) = Pmean
dResults(7) = Inv
RedlichKwongACI = dResults
End Function
Sub SaveAll()
'------------------------------------------------------------------------' Procedure : SaveAll Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Saves all open workbooks

'------------------------------------------------------------------------Dim xWB As Workbook


For Each xWB In Application.Workbooks
If Not xWB.ReadOnly And Windows(xWB.Name).Visible Then
xWB.Save
End If
Next
End Sub
Function chkFileExists(ByVal sPath As String, ByVal sFileName As String, ByVal w
bWorkbook As Workbook) As Boolean
'------------------------------------------------------------------------' Procedure : chkFileExists Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Verify the existance of a file, if no path is provided,
'
use the workbook's path
'------------------------------------------------------------------------chkFileExists = False
'Check to make sure the path is valid or provided or no path with a valid wo
rkbook otherwise return false
If InStr(1, sPath, "/", vbTextCompare) > 0 Or (Len(sPath) < 1 And wbWorkbook
Is Nothing) Then Exit Function
If Len(sPath) < 1 Then
sPath = wbWorkbook.Path
End If
'Validate that the workbook's path is valid (local not web document)
If InStr(1, sPath, "/", vbTextCompare) > 0 Then Exit Function
If Right(sPath, 1) <> "\" Then
sPath = sPath & "\"
End If
chkFileExists = False
If Len(Dir(sPath & sFileName)) > 0 And Len(sFileName) > 0 Then
chkFileExists = True
End If
End Function
Function GetExcelColumnLetter(lngCol As Long) As String
'------------------------------------------------------------------------' Procedure : GetExcelColumnLetter Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 12-14-2016
' Purpose : Convert a column number to column letter for use in Excel
'------------------------------------------------------------------------Dim vArr
On Error GoTo errHandler
vArr = Split(Cells(1, lngCol).Address(True, False), "$")
GetExcelColumnLetter = vArr(0)
Exit Function
errHandler:
MsgBox "Error: " & Err.Number & vbCrLf & Err.Description & vbCrLf & "Line: s
tdLibrary-getFileHeaders " & Erl & vbCrLf, vbCritical + vbOKOnly, "Error"
End Function

'*************************************************************************
'*************************************************************************
'*************************************************************************
'*************************************************************************
'
'
Support Functions needed by RedlichKwongACI
'
'*************************************************************************
'*************************************************************************
'*************************************************************************
'*************************************************************************
Private Function Sign(a As Single, b As Single) As Single
'------------------------------------------------------------------------' Procedure : Sign
' Company :
' Author
: PG&E
' Created :
' Purpose :
'------------------------------------------------------------------------If b >= 0 Then Sign = Abs(a) Else Sign = -Abs(a)
End Function
Private Function Atan2(y As Single, x As Single)
'------------------------------------------------------------------------' Procedure : Atan2
' Company :
' Author
: PG&E
' Created :
' Purpose : Emulate Fortran's ATAN2 function
'------------------------------------------------------------------------Atan2 = Sgn(y) * Atn(y / x)
End Function

'*************************************************************************
'*************************************************************************
'*************************************************************************
'*************************************************************************
'
'
Drop Down and Button for Graphs Routine Exmaples
'
'*************************************************************************
'*************************************************************************
'*************************************************************************
'*************************************************************************
Sub ShowHideGraphSeries(ByVal sSeriesName As String, ByVal sBtnName As String, B
yVal sBtnLine1Text As String)
'------------------------------------------------------------------------' Procedure : ShowHideGraphSeries Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Change status of the selected series line chart visibility
'------------------------------------------------------------------------On Error GoTo errHandler
ActiveChart.SeriesCollection(sSeriesName).Format.Line.Visible = Not ActiveCh
art.SeriesCollection(sSeriesName).Format.Line.Visible

If ActiveChart.SeriesCollection(sSeriesName).Format.Line.Visible Then
ActiveSheet.Buttons(sBtnName).Text = sBtnLine1Text & vbCrLf & "OFF"
Else
ActiveSheet.Buttons(sBtnName).Text = sBtnLine1Text & vbCrLf & "ON"
End If
Exit Sub
errHandler:
If Err.Number <> 0 Then MsgBox "Sub: ShowHideGraphSeries()" & vbCrLf & _
"Line Number: stdLibrary-ShowHideGraphSeries " & Erl & vbCrLf & _
"Error: " & Err.Number & vbCrLf & _
Err.Description, vbCritical + vbOKOnly, "ERROR"
End Sub
Sub cmbChartDD_Change(ByVal sDropDownName As String)
'------------------------------------------------------------------------' Procedure : cmbChartDD_Change Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Process Drop Down List changes
'------------------------------------------------------------------------If ActiveSheet.DropDowns(sDropDownName).List(ActiveSheet.DropDowns(sDropDown
Name).value) = "Delete DropDown" Then
ActiveSheet.DropDowns(sDropDownName).Delete
Else
With ActiveChart
ReconfigureChart sDropDownName
End With
End If
End Sub
'The following subm takes the current chart and changes the series based on the
input, so on the same chart you can select the data
'from different sheets, and also change the Text on the buttons.
Private Sub ReconfigureChart(ByVal sDropDownName As String)
'------------------------------------------------------------------------' Procedure : ReconfigureChart Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Change Series and button visibility as determined by Drop Down Lis
t
'------------------------------------------------------------------------Dim wsWork As Worksheet
Dim strTemp As String
Dim lastRow As Long
Dim dMax As Double, dMin As Double, dRange As Double, dPrimaryAxisDivision A
s Double
Dim bIsMeter As Boolean
On Error GoTo errHandler
bIsMeter = False
With ActiveChart
.ChartTitle.Caption = ActiveSheet.DropDowns(sDropDownName).List(ActiveSh
eet.DropDowns(sDropDownName).value) & " Data"
'I used a case statement instead of an if due to the length of the line
Select Case ActiveSheet.DropDowns(sDropDownName).List(ActiveSheet.DropDo
wns(sDropDownName).value)
Case Is = "Option5", "Option6"
.SeriesCollection("Calculated").Format.Line.Visible = True

ActiveSheet.Buttons("btnCalculated").Visible = True
Case Else
.SeriesCollection("Calculated").Format.Line.Visible = False
ActiveSheet.Buttons("btnCalculated").Visible = False
End Select
End With
Select Case ActiveSheet.DropDowns(sDropDownName).List(ActiveSheet.DropDowns(
sDropDownName).value)
Case Is = "Option1"
Set wsWork = ActiveChart.Parent.Worksheets("Sheet1")
Case Is = "Option2"
Set wsWork = ActiveChart.Parent.Worksheets("Sheet2")
Case Is = "Option3"
Set wsWork = ActiveChart.Parent.Worksheets("Sheet3")
Case Is = "Option4"
Set wsWork = ActiveChart.Parent.Worksheets("Sheet4")
End Select
lastRow = wsWork.UsedRange.SpecialCells(xlCellTypeLastCell).Row
With ActiveChart
.FullSeriesCollection("Citect").Formula = "=SERIES(" & Chr(34) & "Citect
" & Chr(34) & ",," & wsWork.Name & "!$A$8:$A$" & lastRow & ",1)"
.FullSeriesCollection("Telvent").Formula = "=SERIES(" & Chr(34) & "Telve
nt" & Chr(34) & ",," & wsWork.Name & "!$B$8:$B$" & lastRow & ",2)"
If bIsMeter Then
.FullSeriesCollection("PASS/FAIL").Formula = "=SERIES(" & Chr(34) &
"PASS/FAIL" & Chr(34) & ",," & wsWork.Name & "!$M$8:$M$" & lastRow & ",3)"
Else
.FullSeriesCollection("PASS/FAIL").Formula = "=SERIES(" & Chr(34) &
"PASS/FAIL" & Chr(34) & ",," & wsWork.Name & "!$E$8:$E$" & lastRow & ",3)"
End If
If Application.Max(.SeriesCollection("Citect").Values) > Application.Max
(.SeriesCollection("Telvent").Values) Then
dMax = Application.Max(ActiveChart.SeriesCollection("Citect").Values
)
Else
dMax = Application.Max(.SeriesCollection("Telvent").Values)
End If
If Application.Min(.SeriesCollection("Citect").Values) < Application.Min
(.SeriesCollection("Telvent").Values) Then
dMin = Application.Min(.SeriesCollection("Citect").Values)
Else
dMin = Application.Min(.SeriesCollection("Telvent").Values)
End If
dRange = dMax - dMin
dPrimaryAxisDivision = dRange / 10
.Axes(xlValue).MaximumScale = dMax + dPrimaryAxisDivision * 3
.Axes(xlValue).MinimumScale = dMin
End With
Cleanup:
Set wsWork = Nothing
Exit Sub
errHandler:
If Err.Number <> 0 Then MsgBox "Sub: ReconfigureChart()" & vbCrLf & _
"Line Number: stdLibrary-ReconfigureChart " & Erl & vbCrLf & _
"Error: " & Err.Number & vbCrLf & _
Err.Description, vbCritical + vbOKOnly, "ERROR"
Resume Cleanup
End Sub

'*************************************************************************
'*************************************************************************
'*************************************************************************
'*************************************************************************
'
'
Regular Expressions Exmaple
'
'*************************************************************************
'*************************************************************************
'*************************************************************************
'*************************************************************************
Sub getFileInfo()
'------------------------------------------------------------------------' Procedure : getFileInfo Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Demonstrate the power of Regular Expressions in VBA,
'
will process submatches
'------------------------------------------------------------------------Dim lastRow As Long, x As Long, y As Long, iStart As Long, iLength As Long
Dim firstHyphen As Integer, firstUnderscore As Integer, secondSpace As Integ
er
Dim firstSpace As Boolean
Dim currDocument As String
Dim strPtrnTranRTU As String, strPtrnDistRTU As String, strPtrnGeneral As St
ring, strTemplateRev As String, strDocumentRev As String, strNotAllDigits As Str
ing
Dim strPtrnERX As String
Dim regExTranRTU As RegExp, regExDistRTU As RegExp, regExGeneral As RegExp,
regExTemplateRev As RegExp, regExDocumentRev As RegExp, regExNotAllDigits As Reg
Exp
Dim regExERX As RegExp
Dim matchesTran As Object, matchesDist As Object, matches As Object, matches
NotAllDigits As Object, matchesERX As Object
Dim matchTran As Object, matchDist As Object, match As Object, matchNotAllDi
gits As Object, matchERX As Object
Dim sht As Worksheet
Set sht = ActiveSheet
ActiveSheet.UsedRange 'Refresh UsedRange
lastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, Searc
hDirection:=xlPrevious).Row
strPtrnTranRTU = "\w*\s\d{1,3}\.\d{1,3}\.\d{1,3}\sTran\sRTU"
strPtrnDistRTU = "\w*\s\d{1,3}\.\d{1,3}\.\d{1,3}\sDist\sRTU"
strPtrnERX = "[A-Za-z][A-Za-z0-9]{0,1}[_]\w*\s\d{2}[\.\s]\d{3}[\.\s]\d{2}\sD
ist ERX"
strPtrnGeneral = "[A-Za-z0-9]*[_]\w*"
strTemplateRev = "\d{2}[\.\s]\d{3}[\.\s]\d{2}"
strDocumentRev = "Rev\s\d[\d|A-Za-z]{0,2}"
strNotAllDigits = "[^0-9_]"
Set regExTranRTU = New RegExp
Set regExDistRTU = New RegExp
Set regExERX = New RegExp
Set regExGeneral = New RegExp
Set regExTemplateRev = New RegExp
Set regExDocumentRev = New RegExp
Set regExNotAllDigits = New RegExp

regExTranRTU.Pattern = strPtrnTranRTU
regExDistRTU.Pattern = strPtrnDistRTU
regExGeneral.Pattern = strPtrnGeneral
regExTemplateRev.Pattern = strTemplateRev
regExDocumentRev.Pattern = strDocumentRev
regExNotAllDigits.Pattern = strNotAllDigits
regExERX.Pattern = strPtrnERX
'From the start of the string search for an underscore or a hyphen
'If the underscore ocurrs first in a contigous group of characters, this is
the identifier
'If the hyphen ocurrs first, the next group of contigous charactres containi
ng underscore(s) are the identifier
For x = 2 To lastRow
currDocument = sht.Range("B" & x)
'Template Rev
Set matches = regExTemplateRev.Execute(currDocument)
If matches.Count > 0 Then
sht.Range("G" & x) = matches.Item(0)
End If
'Document Rev
Set matches = regExDocumentRev.Execute(currDocument)
If matches.Count > 0 Then
strPtrnGeneral = "\d.*"
'Get the first
regExGeneral.Pattern = strPtrnGeneral
Set matches = regExGeneral.Execute(matches.Item(0))
If matches.Count > 0 Then
sht.Range("H" & x) = matches.Item(0)
End If
End If
'Identifer
strPtrnGeneral = "(([\w]|^-){5,})\s\d{2}[\.\s]\d{3}[\.\s]\d{2}\s.*"
'Identifer naming convention is composed of a group of alphanumeric char
acters excluding hyphen, minimum length of 5
' followed by a space, then the template rev, which is composed of 2 dig
its, 3 digits and finally 2 digits, due to
' differences amongst our group, the template rev can be separated by a
period or a space, finally the template rev
' can be followed by a random succession of characters
regExGeneral.Pattern = strPtrnGeneral
Set matches = regExGeneral.Execute(currDocument)
If matches.Count > 0 Then
'Get the first SubMatch which will be the identifer (first word)
sht.Range("F" & x) = matches.Item(0).SubMatches(0)
End If
Next x
End Sub

'*************************************************************************
'*************************************************************************
'*************************************************************************
'*************************************************************************
'
'
Report Creation Routine Exmaples
'
'*************************************************************************
'*************************************************************************
'*************************************************************************

'*************************************************************************
Sub CreateReport()
'------------------------------------------------------------------------' Procedure : CreateReport
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Creation of results based on Dash Board Data
'------------------------------------------------------------------------Dim x As Integer
Dim lastRow As Long, currRow As Long
Dim sApp As String, sFileName As String, sPath As String, xlPath As String
Dim wdApp As Word.Application, wdDoc As Word.Document, wdSelection As Word.S
election, wdPara As Word.Paragraph
Dim xlWB As Workbook, xlSH As Object, xlChart As Chart
'Esure the workbook is saved before starting a macro, this will prevent a lo
ss of data
'and programming time as well as the dashboard sheets if they have not been
saved
ThisWorkbook.Sheets("Start Here").Range("I50").value = "Start Time: " & Form
at(Now(), "yyyy-MM-dd hh:mm:ss")
ThisWorkbook.Sheets("Start Here").Range("I51").value = "End Time: Not comple
ted"
ThisWorkbook.Save
'If MS Word is not open, open Word
sApp = "Word.Application"
If Not IsAppRunning(sApp) = True Then
' Open Word, and get instance
Set wdApp = CreateObject(sApp)
Else
Set wdApp = GetObject(, sApp)
End If
'Word Application does not need to be visible for this to run.
'wdApp.Visible = True
' Data begins on line 3
currRow = 3
If IsIn(ThisWorkbook.Sheets, "Dash Board") Then ProcessMeterReports wdApp:=w
dApp, currRow:=currRow
If IsIn(ThisWorkbook.Sheets, "Line Dash Board") Then ProcessLineReports wdAp
p:=wdApp, currRow:=currRow
On Error Resume Next
ThisWorkbook.Sheets("Start Here").Range("I51").value = "End Time: " & Format
(Now(), "yyyy-MM-dd hh:mm:ss")
wdApp.Quit
Set wdPara = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing
Set xlWB = Nothing
Set wdSelection = Nothing
Set xlChart = Nothing
End Sub
Sub ProcessMeterReports(wdApp As Word.Application, ByVal currRow As Long)
'------------------------------------------------------------------------' Procedure : CreateReport
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016

' Purpose : Creation of results based on Dash Board Data


'------------------------------------------------------------------------Dim x As Integer
Dim lastRow As Long
Dim sApp As String, sFileName As String, sPath As String, xlPath As String
Dim wdDoc As Word.Document, wdSelection As Word.Selection, wdPara As Word.Pa
ragraph
Dim xlWB As Workbook, xlSH As Object, xlChart As Chart
'Status bar varibles
Dim Progress As Single
Dim Progress_Char As String, Space_Char As String, Start_Char As String, End
_Char As String
Dim CompletedSteps As Long, RemainingSteps As Long
' MaxWidth sets the width of the progress bar, on the status bar
Const MaxWidth = 40
Start_Char = "[ "
End_Char = " ] "
Progress_Char = "|" ' [|||| ]
Space_Char = " "
lastRow = ThisWorkbook.Sheets("Dash Board").UsedRange.SpecialCells(xlCellTyp
eLastCell).Row
For currRow = 3 To lastRow
'Process Status Bar updates for user information
If currRow > 3 Then Progress = (currRow - 3) * 100 / (lastRow - 3) Else
Progress = 0
CompletedSteps = Progress / 100 * MaxWidth
RemainingSteps = MaxWidth - CompletedSteps
DoEvents
Application.StatusBar = Start_Char & WorksheetFunction.Rept(Progress_Cha
r, Round(CompletedSteps, 0)) & WorksheetFunction.Rept(Space_Char, Round(Remainin
gSteps, 0)) & End_Char & " - Processing Meter Set Reports " & Progress & "% Comp
lete"
'If there is no Document named as the Set (Meter/Line) column A, create
one
sFileName = ThisWorkbook.Sheets("Dash Board").Range("A" & currRow).value
sPath = GetHyperlinkAddress(ThisWorkbook.Sheets("Dash Board").Range("A"
& currRow))
xlPath = Application.ThisWorkbook.Path
'Verify if file was processed
'Cross reference file name on log sheet and verify if processed, if it a
ppears on the Dash Board, it should be procesed
If Application.WorksheetFunction.IfError(Application.WorksheetFunction.V
Lookup(ThisWorkbook.Sheets("Dash Board").Range("A" & currRow).value, ThisWorkboo
k.Sheets("Dash Board").Range("A:B"), 2, False), 0) = 0 Then
GoTo SkipMeterLoop
End If
'Check if excel doc is open, if not open it
If Not IsIn(Workbooks, sFileName) Then
Set xlWB = Workbooks.Open(xlPath & "\" & sPath, False, True)
Else
Set xlWB = Workbooks(sFileName)
End If
'Search for report doc, if not create it
If Not IsIn(wdApp.Documents, Mid(sFileName, 1, InStr(sFileName, ".") - 1
) & ".docx") Then
'Open Template and popualte the header, the example document templat
e has all header and footer items needed and 2 fields, one for the Title and one
for the date
Set wdDoc = wdApp.Documents.Open(ThisWorkbook.Path & "\PGE Template.

dotx", False, True)


wdDoc.SelectContentControlsByTitle("Title")(1).Range.Text = Mid(sFil
eName, 1, InStr(sFileName, ".") - 1)
wdDoc.SelectContentControlsByTitle("Date")(1).Range.Text = Format(No
w, "MMMM dd, yyyy")
wdDoc.SaveAs2 fileName:=xlPath & "\Reports\" & Mid(sFileName, 1, InS
tr(sFileName, ".") - 1) & ".docx", FileFormat:=Word.wdFormatXMLDocument
Else
Set wdDoc = wdApp.Documents(Mid(sFileName, 1, InStr(sFileName, ".")
- 1) & ".docx")
End If
Set wdSelection = wdApp.Selection
wdSelection.TypeParagraph
'Add the title and skip two lines
wdSelection.Style = wdDoc.Styles("Title")
wdSelection.TypeText Mid(sFileName, 1, InStr(sFileName, ".") - 1) & " Re
sults"
wdSelection.TypeParagraph
wdSelection.TypeParagraph
'Begin by Stating the Overall results of the tested Set
wdSelection.Font.Name = "Arial"
wdSelection.Font.size = 10
wdSelection.TypeText "Overall analysis results are as follows:"
wdSelection.TypeParagraph
wdUseBullets wdApp, wdDoc, wdSelection, False
wdSelection.TypeText Text:="Net Result:" & vbTab & ThisWorkbook.Sheets("
Dash Board").Range("AB" & currRow).value
wdSelection.TypeParagraph
wdEndBullets wdSelection
wdSelection.TypeParagraph
'Add a TabStop at 3"
wdSelection.ParagraphFormat.TabStops.Add Position:=wdApp.InchesToPoints(
3.01), Alignment:=Word.wdAlignTabLeft, Leader:=Word.wdTabLeaderSpaces
wdSelection.TypeText "Results per Test Performed:"
wdSelection.TypeParagraph
wdUseBullets wdApp, wdDoc, wdSelection, False
addTestResultGroup wdSelection, "Instant Flow", "E", currRow
addTestResultGroup wdSelection, "Current Hour", "H", currRow
addTestResultGroup wdSelection, "Current Day", "K", currRow
addTestResultGroup wdSelection, "Current Month", "N", currRow
addTestResultGroup wdSelection, "Previous Hour", "Q", currRow
addTestResultGroup wdSelection, "Previous Day", "T", currRow
'addTestResultGroup wdSelection, "Previous Month", "W", currRow
addTestResultGroup wdSelection, "Planned Day", "Z", currRow
wdEndBullets wdSelection
'Remove the TabStop at 3"
wdSelection.ParagraphFormat.TabStops.ClearAll
wdDoc.DefaultTabStop = wdApp.InchesToPoints(0.5)
'Create a signature area
wdAddSignatureBlock wdApp, wdDoc, wdSelection
wdSelection.HomeKey Unit:=wdStory
wdSelection.EndKey Unit:=wdStory
'to copy a chart sheet object from excel
'set the chart sheet active
xlWB.Charts("Analysis Chart").Activate
'Export Instant Flow Graph as image, change graph
' to Current Day, and also export to image.
For x = 1 To 2
If x = 1 Then
wdSelection.TypeText "Instant Flow Chart:"

wdSelection.TypeParagraph
selectDesiredGraph xlWB, "Instant Flow"
Else
wdSelection.TypeText "Current Day Chart:"
wdSelection.TypeParagraph
selectDesiredGraph xlWB, "Current Day"
End If
Set xlChart = xlWB.Charts("Analysis Chart")
xlChart.ChartArea.Copy
'Continue by adding the charts images to the document
wdSelection.PasteSpecial Link:=False, DataType:=Word.wdPasteEnhanced
Metafile, Placement:=wdInLine, DisplayAsIcon:=False 'Works
wdSelection.TypeParagraph
wdSelection.InsertBreak Type:=Word.wdPageBreak
wdSelection.MoveDown
Next x
'Create an appendix for the raw data for the Set validated (Citect / Tel
vent)
'Create a PDF file for distribution
SaveDoc2PDF wdDoc:=wdDoc
'Close & Save the Document
wdDoc.Close SaveChanges:=True
'Close Excel Workbook
xlWB.Close SaveChanges:=False
SkipMeterLoop:
Next currRow
Application.StatusBar = vbNullString
End Sub
Sub ProcessLineReports(wdApp As Word.Application, ByVal currRow As Long)
'------------------------------------------------------------------------' Procedure : CreateReport
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Creation of results based on Dash Board Data
'------------------------------------------------------------------------Dim x As Integer
Dim lastRow As Long
Dim sApp As String, sFileName As String, sPath As String, xlPath As String
Dim wdDoc As Word.Document, wdSelection As Word.Selection, wdPara As Word.Pa
ragraph
Dim xlWB As Workbook, xlSH As Object, xlChart As Chart
'Status bar varibles
Dim Progress As Single
Dim Progress_Char As String, Space_Char As String, Start_Char As String, End
_Char As String
Dim CompletedSteps As Long, RemainingSteps As Long
' MaxWidth sets the width of the progress bar, on the status bar
Const MaxWidth = 40
Start_Char = "[ "
End_Char = " ] "
Progress_Char = "|" ' [|||| ]
Space_Char = " "
lastRow = ThisWorkbook.Sheets("Line Dash Board").UsedRange.SpecialCells(xlCe
llTypeLastCell).Row
For currRow = 3 To lastRow

'Process Status Bar updates for user information


If currRow > 3 Then Progress = (currRow - 3) * 100 / (lastRow - 3) Else
Progress = 0
CompletedSteps = Progress / 100 * MaxWidth
RemainingSteps = MaxWidth - CompletedSteps
DoEvents
Application.StatusBar = Start_Char & WorksheetFunction.Rept(Progress_Cha
r, Round(CompletedSteps, 0)) & WorksheetFunction.Rept(Space_Char, Round(Remainin
gSteps, 0)) & End_Char & " - Processing Line Set Reports " & Progress & "% Compl
ete"
'If there is no Document named as the Set (Meter/Line) column A, create
one
sFileName = ThisWorkbook.Sheets("Line Dash Board").Range("A" & currRow).
value
sPath = GetHyperlinkAddress(ThisWorkbook.Sheets("Line Dash Board").Range
("A" & currRow))
xlPath = Application.ThisWorkbook.Path
'Verify if file was processed
'Cross reference file name on log sheet and verify if processed, if it a
ppears on the Dash Board, it should be procesed
If Application.WorksheetFunction.IfError(Application.WorksheetFunction.V
Lookup(ThisWorkbook.Sheets("Dash Board").Range("A" & currRow).value, ThisWorkboo
k.Sheets("Dash Board").Range("A:B"), 2, False), 0) = 0 Then
GoTo SkipLineLoop
End If
'Check if excel doc is open, if not open it
If Not IsIn(Workbooks, sFileName) Then
Set xlWB = Workbooks.Open(xlPath & "\" & sPath, False, True)
Else
Set xlWB = Workbooks(sFileName)
End If
'Search for report doc, if not create it
If Not IsIn(wdApp.Documents, Mid(sFileName, 1, InStr(sFileName, ".") - 1
) & ".docx") Then
'Open Template and popualte the header
Set wdDoc = wdApp.Documents.Open(ThisWorkbook.Path & "\PGE Template.
dotx", False, True)
wdDoc.SelectContentControlsByTitle("Title")(1).Range.Text = Mid(sFil
eName, 1, InStr(sFileName, ".") - 1)
wdDoc.SelectContentControlsByTitle("Date")(1).Range.Text = Format(No
w, "MMMM dd, yyyy")
wdDoc.SaveAs2 fileName:=xlPath & "\Reports\" & Mid(sFileName, 1, InS
tr(sFileName, ".") - 1) & ".docx", FileFormat:=Word.wdFormatXMLDocument
Else
Set wdDoc = wdApp.Documents(Mid(sFileName, 1, InStr(sFileName, ".")
- 1) & ".docx")
End If
Set wdSelection = wdApp.Selection
'The following block has been commented as I will be using a standard PG
&E Template
wdSelection.TypeParagraph
'Add the title and skip two lines
wdSelection.Style = wdDoc.Styles("Title")
wdSelection.TypeText Mid(sFileName, 1, InStr(sFileName, ".") - 1) & " Re
sults"
wdSelection.TypeParagraph
wdSelection.TypeParagraph
'Begin by Stating the Overall results of the tested Set
wdSelection.Font.Name = "Arial"
wdSelection.Font.size = 10

wdSelection.TypeText "Overall analysis results are as follows:"


wdSelection.TypeParagraph
wdUseBullets wdApp, wdDoc, wdSelection, False
wdSelection.TypeText Text:="Net Result:" & vbTab & ThisWorkbook.Sheets("
Line Dash Board").Range("M" & currRow).value
wdSelection.TypeParagraph
wdEndBullets wdSelection
wdSelection.TypeParagraph
'Add a TabStop at 3"
wdSelection.ParagraphFormat.TabStops.Add Position:=wdApp.InchesToPoints(
3.01), Alignment:=Word.wdAlignTabLeft, Leader:=Word.wdTabLeaderSpaces
wdSelection.TypeText "Results per Test Performed:"
wdSelection.TypeParagraph
wdUseBullets wdApp, wdDoc, wdSelection, False
addTestResultGroup wdSelection, "Inventory", "E", currRow, True
addTestResultGroup wdSelection, "Previous Inventory", "H", currRow, True
addTestResultGroup wdSelection, "Pack / Draft", "K", currRow, True
wdEndBullets wdSelection
'Remove the TabStop at 3"
wdSelection.ParagraphFormat.TabStops.ClearAll
wdDoc.DefaultTabStop = wdApp.InchesToPoints(0.5)
'Create a signature area
wdAddSignatureBlock wdApp, wdDoc, wdSelection
wdSelection.HomeKey Unit:=wdStory
wdSelection.EndKey Unit:=wdStory
'to copy a chart sheet object from excel
'set the chart sheet active
xlWB.Charts("Analysis Chart").Activate
'Export Instant Flow Graph as image, change graph
' to Current Day, and also export to image.
For x = 1 To 3
Select Case x
Case 1
wdSelection.TypeText "Inventory:"
wdSelection.TypeParagraph
selectDesiredGraph xlWB, "Inventory"
Case 2
wdSelection.TypeText "Previous Inventory:"
wdSelection.TypeParagraph
selectDesiredGraph xlWB, "Previous Inventory"
Case 3
wdSelection.TypeText "Pack / Draft:"
wdSelection.TypeParagraph
selectDesiredGraph xlWB, "Pack / Draft"
End Select
Set xlChart = xlWB.Charts("Analysis Chart")
xlChart.ChartArea.Copy
'Continue by adding the charts images to the document
wdSelection.PasteSpecial Link:=False, DataType:=Word.wdPasteEnhanced
Metafile, Placement:=wdInLine, DisplayAsIcon:=False 'Works
wdSelection.TypeParagraph
wdSelection.InsertBreak Type:=Word.wdPageBreak
wdSelection.MoveDown
Next x
'Create an appendix for the raw data for the Set validated (Citect / Tel
vent)
'Create a PDF file for distribution
SaveDoc2PDF wdDoc:=wdDoc

'Close & Save the Document


wdDoc.Close SaveChanges:=True
'Close Excel Workbook
xlWB.Close SaveChanges:=False
SkipLineLoop:
Next currRow
Application.StatusBar = vbNullString
End Sub
Sub SaveDoc2PDF(wdDoc As Word.Document)
'------------------------------------------------------------------------' Procedure : SaveDoc2PDF Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 09-01-2016
' Purpose : Converts Word Document to PDF
'------------------------------------------------------------------------With wdDoc
.ExportAsFixedFormat OutputFileName:=.Path & "\" & Mid(.Name, 1, InStr(.
Name, ".") - 1) & ".pdf", _
ExportFormat:=Word.wdExportFormatPDF, OpenAfterExport:=False, Op
timizeFor:=Word.wdExportOptimizeForPrint, _
Item:=Word.wdExportDocumentContent, CreateBookmarks:=Word.wdExpo
rtCreateHeadingBookmarks
End With
End Sub
Sub selectDesiredGraph(xlWB As Workbook, sGraphName As String)
'------------------------------------------------------------------------' Procedure : selectDesiredGraph Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 09-01-2016
' Purpose : Updates Graph on Analysis report to the desider one
'------------------------------------------------------------------------Dim x As Integer, y As Integer
For x = 1 To UBound(xlWB.Charts("Analysis Chart").DropDowns("cmbChartDD").Li
st)
If xlWB.Charts("Analysis Chart").DropDowns("cmbChartDD").List(x) = sGrap
hName Then Exit For
Next x
xlWB.Charts("Analysis Chart").DropDowns("cmbChartDD").Selected(x) = True
Application.Run xlWB.Name & "!ReconfigureChart"
End Sub
Sub wdAddSignatureBlock(wdApp As Word.Application, wdDoc As Word.Document, wdSel
ection As Word.Selection)
'------------------------------------------------------------------------' Procedure : wdAddSignatureBlock Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 09-01-2016
' Purpose : Add the notes and signature block to the document
'------------------------------------------------------------------------Dim wdCurrParaFormat As Word.ParagraphFormat, wdCurrFontSize As Single
'Get the current Paragraph format
Set wdCurrParaFormat = wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Format
wdCurrFontSize = wdSelection.Font.size

wdSelection.TypeParagraph
wdSelection.TypeParagraph
wdSelection.Font.Bold = True
wdSelection.TypeText "Notes:"
wdSelection.TypeParagraph
wdSelection.TypeParagraph
wdSelection.TypeParagraph
wdSelection.TypeParagraph
wdSelection.TypeParagraph
wdSelection.TypeParagraph
wdSelection.TypeParagraph
wdSelection.TypeParagraph
wdSelection.TypeParagraph
wdSelection.Font.Bold = False
wdSelection.Font.Underline = wdUnderlineSingle
wdSelection.Font.size = 10
wdSelection.TypeText "PROCEDURE APPROVAL:"
wdSelection.TypeParagraph
wdSelection.Font.Underline = wdUnderlineNone
wdSelection.TypeParagraph
With wdSelection.ParagraphFormat
.TabStops.Add Position:=wdApp.InchesToPoints(2.5), Alignment:=Word.wdAli
gnTabLeft, Leader:=Word.wdTabLeaderSpaces
.SpaceBefore = 0
.SpaceBeforeAuto = False
.SpaceAfter = 0
.SpaceAfterAuto = False
.LineSpacingRule = wdLineSpaceSingle
End With
wdSelection.Font.Bold = True
wdSelection.TypeText "Test Procedure Author:"
wdSelection.Font.Bold = False
wdSelection.TypeText vbTab & "______________________________________________
____"
wdSelection.TypeParagraph
wdSelection.ParagraphFormat.TabStops.ClearAll
wdDoc.DefaultTabStop = wdApp.InchesToPoints(0.5)
wdSelection.ParagraphFormat.TabStops.Add Position:=wdApp.InchesToPoints(3.5)
, Alignment:=Word.wdAlignTabLeft, Leader:=Word.wdTabLeaderSpaces
wdSelection.TypeText vbTab & "Signature / Date / LAN ID"
wdSelection.TypeParagraph
wdSelection.ParagraphFormat.TabStops.ClearAll
wdDoc.DefaultTabStop = wdApp.InchesToPoints(0.5)
wdSelection.ParagraphFormat.TabStops.Add Position:=wdApp.InchesToPoints(2.5)
, Alignment:=Word.wdAlignTabLeft, Leader:=Word.wdTabLeaderSpaces
wdSelection.TypeParagraph
wdSelection.Font.Bold = True
wdSelection.TypeText "Gas SCADA:"
wdSelection.Font.Bold = False
wdSelection.TypeText vbTab & "______________________________________________
____"
wdSelection.TypeParagraph
wdSelection.ParagraphFormat.TabStops.ClearAll
wdDoc.DefaultTabStop = wdApp.InchesToPoints(0.5)
wdSelection.ParagraphFormat.TabStops.Add Position:=wdApp.InchesToPoints(3.5)
, Alignment:=Word.wdAlignTabLeft, Leader:=Word.wdTabLeaderSpaces
wdSelection.TypeText vbTab & "Signature / Date / LAN ID"
wdSelection.InsertBreak Type:=Word.wdPageBreak
wdSelection.MoveLeft Unit:=wdCharacter, Count:=2
wdSelection.TypeBackspace

wdSelection.MoveDown
wdSelection.ParagraphFormat.TabStops.ClearAll
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Format = wdCurrParaFormat
wdSelection.Font.size = wdCurrFontSize
wdDoc.DefaultTabStop = wdApp.InchesToPoints(0.5)
Set wdCurrParaFormat = Nothing
End Sub
Sub addTestResultGroup(wdSelection As Word.Selection, sTitle As String, sResultC
ol As String, currRow As Long, Optional ByVal isLine As Boolean = False)
'------------------------------------------------------------------------' Procedure : addTestResultGroup Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 09-01-2016
' Purpose : Add a test result group of lines with corresponding formatting
'------------------------------------------------------------------------Dim xlSheet As Worksheet
If isLine Then Set xlSheet = ThisWorkbook.Sheets("Line Dash Board") Else Set
xlSheet = ThisWorkbook.Sheets("Dash Board")
With xlSheet
wdSelection.TypeText Text:=sTitle & ":" & vbTab & .Range(sResultCol & cu
rrRow).value
wdSelection.TypeParagraph
wdSelection.Range.ListFormat.ListIndent
wdSelection.TypeText Text:="Valid Samples:" & vbTab & .Range(Chr(Asc(sRe
sultCol) - 2) & currRow).value
wdSelection.TypeParagraph
wdSelection.TypeText Text:="Pass Ratio:" & vbTab & .Range(Chr(Asc(sResul
tCol) - 1) & currRow).value
wdSelection.TypeParagraph
wdSelection.Range.ListFormat.ListOutdent
End With
End Sub
Sub wdAddSamuelHeader(wdApp As Word.Application, wdDoc As Word.Document, wdSelec
tion As Word.Selection)
'------------------------------------------------------------------------' Procedure : wdAddSamuelHeader Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 09-01-2016
' Purpose : Adds a standard Samuel Engineering Header on the fly
'
Not used, instead of creating a header a template was
'
used, and fields added for rapid modification
'------------------------------------------------------------------------wdApp.ActiveWindow.ActivePane.View.SeekView = Word.wdSeekCurrentPageHeader
wdSelection.InlineShapes.AddPicture fileName:="C:\Users\jdiaz\OneDrive - Sam
uel Engineering-\Personal Documents\16108\SamuelLogo.jpg", LinkToFile:=False, Sa
veWithDocument:=True
wdSelection.MoveRight Unit:=Word.wdCharacter, Count:=1
wdSelection.TypeParagraph
wdSelection.Font.size = 9
wdSelection.TypeText Text:="8450 East Crescent Parkway, Suite 200" & vbTab &
vbTab & "Phone: 303.714.4840"
wdSelection.TypeParagraph
wdSelection.TypeText Text:="Greenwood Village, CO 80111" & vbTab & vbTab & "
FAX: 303.714.4800"

wdApp.ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End Sub
Sub wdUseBullets(wdApp As Word.Application, wdDoc As Word.Document, wdSelection
As Word.Selection, ByVal ContinuePrevList As Boolean)
'------------------------------------------------------------------------' Procedure : wdUseBullets Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 09-01-2016
' Purpose : Changes current paragraph formating to use bullets
'------------------------------------------------------------------------With wdApp.ListGalleries(Word.wdBulletGallery).ListTemplates(1).ListLevels(1
)
.NumberFormat = ChrW(61623)
.TrailingCharacter = Word.wdTrailingTab
.NumberStyle = Word.wdListNumberStyleBullet
.NumberPosition = wdApp.InchesToPoints(0.25)
.Alignment = Word.wdListLevelAlignLeft
.TextPosition = wdApp.InchesToPoints(0.5)
.TabPosition = Word.wdUndefined
.ResetOnHigher = 0
.StartAt = 1
With .Font
.Bold = Word.wdUndefined
.Italic = Word.wdUndefined
.Strikethrough = Word.wdUndefined
.Subscript = Word.wdUndefined
.Superscript = Word.wdUndefined
.Shadow = Word.wdUndefined
.Outline = Word.wdUndefined
.Emboss = Word.wdUndefined
.Engrave = Word.wdUndefined
.Allcaps = Word.wdUndefined
.Hidden = Word.wdUndefined
.Underline = Word.wdUndefined
.Color = Word.wdUndefined
.size = Word.wdUndefined
.Animation = Word.wdUndefined
.DoubleStrikeThrough = Word.wdUndefined
.Name = "Symbol"
End With
.LinkedStyle = ""
End With
wdApp.ListGalleries(Word.wdBulletGallery).ListTemplates(1).Name = ""
wdSelection.Range.ListFormat.ApplyListTemplateWithLevel ListTemplate:= _
wdApp.ListGalleries(Word.wdBulletGallery).ListTemplates(1), ContinuePrev
iousList:= _
ContinuePrevList, ApplyTo:=Word.wdListApplyToWholeList, DefaultListBehav
ior:= _
Word.wdWord10ListBehavior
End Sub
Sub wdEndBullets(wdSelection As Word.Selection)
'------------------------------------------------------------------------' Procedure : wdEndBullets Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 09-01-2016
' Purpose : Terminates the use bullets

'------------------------------------------------------------------------wdSelection.Range.ListFormat.RemoveNumbers NumberType:=wdNumberParagraph
End Sub
'Can be deleted
Sub testAddChartObject()
'------------------------------------------------------------------------' Procedure : testAddChart Created by Jaime Diaz
' Company :
' Author
: Jaime Diaz
' Created : 08-25-2016
' Purpose : Test AddChart function providing needed parameters
'------------------------------------------------------------------------Dim vSeries As Variant
Dim rngRange As Range
'For multiple series use the next lines
ReDim vSeries(1 To 3)
vSeries(1) = "This series 1"
vSeries(2) = "This series 2"
vSeries(3) = "This series 3"
Set rngRange = ActiveSheet.Range("A1:C10")
'for a single series use the next lines
'vSeries = "This series 1"
'Set rngRange = ActiveSheet.Range("A1:A10")
'For a single series names and 2 series of data use the next lines
'vSeries = "This series 1"
'Set rngRange = ActiveSheet.Range("A1:B10")
'For multiple series names and only 1 series of data use the next lines
'ReDim vSeries(1 To 3)
'vSeries(1) = "This series 1"
'vSeries(2) = "This series 2"
'vSeries(3) = "This series 3"
'Set rngRange = ActiveSheet.Range("A1:A10")
'For multiple series names and only 2 series of data use the next lines
'ReDim vSeries(1 To 3)
'vSeries(1) = "This series 1"
'vSeries(2) = "This series 2"
'vSeries(3) = "This series 3"
'Set rngRange = ActiveSheet.Range("A1:B10")
'call to function to be tested
AddChartObject ActiveSheet.Parent, ActiveSheet, rngRange, "Test Chart", "Cha
rt 1", vSeries
End Sub

S-ar putea să vă placă și