Documente Academic
Documente Profesional
Documente Cultură
'--------------------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
'
'
'
'
'
'
'
'
'
-
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
'
'
'
'
'
'
'
'
.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
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
' 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
'-------------------------------------------------------------------------
Dim
Dim
Dim
Dim
AppCalcMode As Long
AppScreenUpdating As Boolean
fso As Scripting.FileSystemObject
oFile As Object
'
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
Dim
Dim
Dim
Dim
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
(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))
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
'*************************************************************************
'*************************************************************************
'*************************************************************************
'*************************************************************************
'
'
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
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
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