PipelineStudio Gas Simulator Module Excel_English

Embed Size (px)

Citation preview

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    1/19

    GAS NETWORK TRAINING

    MODULE : EXCEL

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    2/19

    Gas Network Training

    i

    PipelineStudio Training: Module Excel ............................................................................................ IThe Module ......................................................................................................................................... IThe User .............................................................................................................................................. I

    The Training ........................................................................................................................................ IPipelineStudio as a component in an Integrated System ............................................................ 11. PipelineStudio Configuration ........................................................................................................ 12. Command line arguments ............................................................................................................. 4

    2.1 Examples .................................................................................................................................. 63. Control Options .............................................................................................................................. 8

    3.1. Export of Transient Scenario.............................................................................................. 83. 2. Addition of fluid data in Import/Export of Initial Data ....................................................... 8

    4. PipelineStudio import and export file formats .............................................................................. 95. Creating simple VBA macros ...................................................................................................... 10

    5.1. VBA Example 1 ................................................................................................................. 116. Case Study: Using Microsoft Excel to automate an integrated PipelineStudio system .......... 117. Example Macro Code .................................................................................................................. 14

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    3/19

    Gas Network Training

    I

    PipelineStudio Training: Module Excel

    The Module

    The module contains a series of examples about how to interactpipel inestudio and Excel.

    The case will illustrate input and output data in Excel environment.

    The User

    This pipel inestudioTraining Class is intended to the users of the product orsomeone who wants to become more productive usingpipel inestudio.

    The goal of the pipel inestudiotraining class is to provide a pipeline engineer,technician or professional with all of the skills and familiarity with the productneeded to allow them to begin making productive and efficient use of the product.

    The Training

    pipel inestudioTraining is being provided in a laboratory-type environment withthe intent to provide the trainee with an interactive and high-ratio of hands onexperience. The purpose of this is to keep things interesting and provide betteroverall retention by the student.

    pipel inestudiotraining is divided into ordered and methodical labs to allow theuser to build on skills obtained from the previous lab and maximize the retentionof knowledge associated with this training. Lecture and discussion will beincorporated into the labs themselves.

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    4/19

    Gas Network Training

    1

    PipelineStudio as a component in an Integrated System

    Introduction

    pipel inestudiois a powerful product permitting both steady-state and transient analysis of verycomplex gas or liquid pipeline networks. Typically pipel ines tud iois applied as a stand aloneproduct by engineering, operational and marketing end users.

    However, pipel inestudioalso has some very powerful features that permit it to be used as acomponent in a larger scale system. When integrated as a component, a system callspipel inestudiofrom a command line, together appropriate arguments permitting the import ofboundary conditions, scenario and simulation options, and executes a simulation. This data maythen be read back into the parent application (normally from trend plot files).

    Further manipulation of the output data may also be performed automatically to present the datain a format that the end user feels more comfortable with.

    The ultimate goal of such an application is to present an end user who has no knowledge ofhydraulic simulation with a tool that makes is easier for them to operate and profit the pipeline in asafe manner, therefore minimising the need for them to have a detailed understanding ofhydraulics and simulation technology.

    This guidance program investigates the features of pipel inestudiowhich permit this integrationto take place; the input and output file formats which pipel inestudiorequires and the use of aparent application (Microsoft Excel) to create files, drivepipel ines tud ioand ultimately read thedata back into the application.

    1. PipelineStudio Configuration

    The foundation of this program is the investigation of the integration of pipel inestudiowith otherapplications; hence a relatively simple point to point pipel ines tud ioGas configuration consistingof 20 pipeline sections of one mile length and 12internal diameter will be used as the baseline.The purpose of the number of leg segments is that it permits us to trend pressure and flow atmore intervals than simply the ends of the pipe. A supply will be connected to the upstream and avolumetric delivery to the downstream points of the pipeline configuration.

    In general default pipel inestudioproperties should be used to prevent excessive timeconstructing the model.

    The input fluid will be the default Gulf Coast Gas from the TGNET Library; this should be

    available from the drop down menu on the supply dialogue. To reflect this choice a compositionalequation should be selected, to determine the fluid density and compressibility, from thesimulation options (BWRS recommended), though this is not essential as the default SAREMequation can calculate the required fluid properties from the fluid composition (though a warningmessage is presented on model validation this would be ultimately hidden from an end user if thecorrect arguments are used).

    Ultimately with this model the inlet and outlet flow boundaries will be varied over time, howeverthis does not preclude the fact that for an initial steady state solution an initial pressure boundaryset point is required. The model will be run initially as a PQ model; i.e. initial control pressureupstream and flow downstream. An upstream flow constraint and a downstream pressureconstraint will also be provided. The upstream flow constraint permits variance of the upstream

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    5/19

    Gas Network Training

    2

    flow set point, the downstream pressure constraint prevents the pressure from backing into subambient pressure conditions.

    An upstream mode of control of Maximum Pressure, with a Maximum Pressure set point of 1000psig, and an upstream Maximum Flow constraint of 75 MMSCFD will be used; and downstream aMaximum Flow control with a Maximum Flow set point of 50 MMSCFD and a downstream aMinimum Pressure constraint of 900 psig will be used.

    As this configuration is relatively straightforward the default naming convention may be used.

    The following data items should be trended for each device:

    SUPPLY:Flow, Pressure, Mode

    DELIVERY:Flow, Pressure, Mode

    PIPE:Upstream Flow, Downstream Flow, Upstream Pressure, Downstream Pressure, UpstreamVelocity, Downstream Velocity, Inventory (you can use the!Apply to Allbutton to apply the trendsettings to all pipes).

    In this configuration this gives us 140 trended data items, or 141 columns in the output file we willbe using to import data back in to Excel. Excel can only support a maximum of 256 columns in asingle worksheet without wrapping data around, in which case further data processing may berequired. It is advised that the capabilities of the parent application are checked to ensure theycan deal with the data processing required without too much further work. Additionally Excelsupports 65536 rows of data in a single worksheet, whilst this is unlikely to be breached in normalsimulations, in the cases where trending occurs at small time intervals (such as when theminimum time step is used by pipel inestudiofor long periods of time, due to, for example,excessive mode swapping or depressurization of the pipeline in the simulation, with trending set

    to maximum).

    This, of course, is simply a suggested configuration and components may be added or removedas required, but the presented material is based solely on this configuration. The theorypresented is essentially the same whether you are looking at liquid or gas, or other equipmentelements such as valves, compressors or pumps.

    It is important to make a note at this stage that a successful implementation of an integratedpipel inestudioapplication is highly dependant on a robust model. That is to say, as far aspossible, errors need to be hidden from an end user. Errors can include such things as validationfailure, steady-state failure, or a slow transient due to continuous use of the minimum time step.Many of these problems may be avoided by careful use of the constraint logic withinpipel inestudio, and rudimentary error checking in the parent application.

    Once the configuration has been developed save it in a sensible directory structure, such as!C:\Studio_Integration\Configurations, with a sensible filename, such as!Baseline_Configuration.tgw. Generally the shorter the file path the better as it reduces thelikelihood of input errors when developing integrated applications.

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    6/19

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    7/19

    Gas Network Training

    4

    2. Command line arguments

    The primary feature this course will concentrate on will be the use of command line argumentsand appropriate input and output files.

    Prior to investigation of the arguments which may be used to initiate apipel inestudioinstancefrom a command line, it is important to find out how to start a pipel inestudioinstance form acommand line.

    There are several ways this may be done. The first way is to use the direct address topipel inestudio; the default for this would be:

    C:\> C:\Program Files\Energy Solutions\PipelineStudio (version) \Plstudio\Plstudio.exe

    Try entering this at a command prompt (HINT: Use Start | Run and type cmdin the open

    dialogue box).

    Alternatively you can add the path to thepipel inestudioexecutable file to the main environmentpath. This can be done permanently by selecting the advanced option from the system propertiesdialogue and then selecting the environment variables button.

    Alternatively it can be added temporarily until a command prompt is closed by the followingcommand in a command prompt:

    C:\> PATH = %PATH%; :\> C:\Program Files\Energy Solutions\PipelineStudio (version)\Plstudio\

    Note in this case Plstudio.exe is not added to the end of the path.

    pipel inestudiomay now be started from the command prompt thus:

    C:\> Plstudio

    Or

    C:\> Plstudio.exe

    Remember if the path is added temporarily to a command window that when you close thecommand window new path will be lost.

    Finally it is possible to initiate apipel ines tud iosession from a command window using thefollowing command:

    C:\> start Plstudio

    The start command normally has knowledge of the path to pipel inestudioand will initiate apipel inestudiosession.

    Because this session looks at the command line arguments available in pipel ines tud iosomeadditional files need to be created to import into. This may done very simply using Notepad, Excelor another text editing program. The files that will be created will be a simple setpoint file and asimple scenario file. The formats of these files and the requirements for these files will bediscussed in more detail during this training session.

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    8/19

    Gas Network Training

    5

    The setpoint file should be named !setpoints.csvand saved in the same directory as thepipel inestudioconfiguration. It should include the following line:

    Delivery,Deliv0001,FLMX,40

    The scenario file should be named !scenario.csvand be saved in the same directory as thepipel inestudioconfiguration file. It should include the following lines:

    Device Type,Device Name,Setpoint,1,2,3,4,5,6Delivery,Deliv0001,FLMX,45,50,55,50,45,50

    Once these files have been created the investigation of the available command may now begin.

    The following commands are available for TGNET or TLNET.

    PLStudio xyz.tgw Open xyz.tgw (gas model only)

    PLStudio xyz.tlw Open xyz.tlw (liquid model only)PLStudio xyz.kw Import xyz.kw

    PLStudio xyz.kws Import xyz.kws

    PLStudio /ImportKeywordFile xyz.kw Import xyz.kw

    PLStudio /ExportKeywordFile xyz.tgw Export the keyword file for thepipel inestud ioconfiguration xyz. (gas model only)

    PLStudio /ExportKeywordFile xyz.tlw Export the keyword file for thepipel inestud ioconfiguration xyz. (liquid model only)

    PLStudio /importdata abc.csv xyz.tgw Open the specified file and immediately import Initial

    Data from abc.csv

    PLStudio /? Display help for command line flags (by opening a helpfile on this topic)

    PLStudio /p xyz.tgw Print default network view of a file to default printer and

    closes pipel inestud ioautomatically after printingcompletes.PLStudio /pt name xyz.tgw Print default network view of a file to specified

    printer/driver/port

    PLStudio /scenariodata abc.csv xyz.tgw Specifies a file from which to read scenario data. You

    can do this using batch (BAT/CMD) files or via the Runitem on the Windows Start menu.

    PLStudio /RunSteady xyz.tgw Requests that a steady-state simulation be runautomatically upon program startup (after any import of

    data).

    PLStudio /RunTransient xyz.tgw Requests that a transient simulation be run automaticallyupon program startup (after any import of data)

    PLStudio /RunSteady /CloseWhenFinished xyz.tgw

    PLStudio /RunTransient /CloseWhenFinished xyz.tgw

    Requests that pipel inestud iobe closed automaticallywhen a steady-state or transient simulation finishes.

    NOTE: This command line argument can only be used inconjunction with either -RunSteady or -RunTransient.

    PLStudio /RunSteady /StartMinimized

    /CloseWhenFinished xyz.tgw

    PLStudio /RunTransient /StartMinimized

    /CloseWhenFinished xyz.tgw

    Requests that pipel inestud iobe started up minimizedand closed automatically when a steady-state ortransient simulation finishes. NOTE: This command lineargument can only be used in conjunction with either -RunSteady or -RunTransient.

    PLStudio /importKeywordfile abc.kw /SaveConfigxyz.tgw /CloseWhenFinished

    Requests that pipel inestud iobe started up and closedautomatically when the keyword file is imported and

    saved as a pipel inestud ioconfiguration.

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    9/19

    Gas Network Training

    6

    2.1 Examples

    In each example, we give the command line that you would enter (in a DOS window or in the

    "Open" box displayed by choosing Run"from the Windows Start menu). Following the commandline, we describe of what would happen.

    Note:You do not need a command line flag before the tgw/tlw/ file name, but it must be

    specified as the last item on the command line.

    Otherwise, the order of command line flags is unimportant (except that file names mustimmediately follow flags which require them)

    The followings are examples of using the commands/scenariodata,

    /RunSteady,/RunTransientand/CloseWhenFinished.

    These examples refer to gas (.tgw) files, but these features will also work with liquid (.tlw) files.

    2.1.1. Example 1

    C:\Program Files\Energy Solutions\PLStudio\plstudio.exe C:\data\demo.tgw

    This would, in order:

    start pipel ines tud io

    open the demo.tgw file from the c:\data folder

    2.1.2. Example 2

    start plstudio /RunTransient C:\data\demo.tgw

    This would, in order:

    start pipel ines tud io

    open the demo.tgw file from the c:\data folder

    run a transient simulation

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    10/19

    Gas Network Training

    7

    2.1.3. Example 3a

    C:\Program Files\Energy Solutions\PLStudio\plstudio.exe /scenariodata

    C:\data\demoscen.csv C:\data\demo.tgw

    This would, in order:

    start pipel ines tud io

    open the demo.tgw file from the c:\data folder

    import scenario data from the demoscen.csv file in the c:\data\ folder.

    2.1.4. Example 3b

    C:\Program Files\Energy Solutions\PLStudio\plstudio.exe /scenariodataC:\data\demoscen.csv/RunSteady C:\data\demo.tgw

    This would do the same as the previous example and then run a steady-state simulation.

    2.1.5. Example 4

    C:\Program Files\Energy Solutions\PLStudio\plstudio.exe /importdata C:\data\demoinit.csv/scenariodata C:\data\demoscen.csv C:\data\demo.tgw

    This example shows the /scenariodata flag combined with the /importdata flag.

    This would, in order:

    start pipel ines tud io

    open the demo.tgw file from the c:\data folder

    import initial data from the demoinit.csv file in the c:\data\ folder

    import scenario data from the demoscen.csv file in the c:\data\ folder.

    2.1.6. Example 5

    C:\Program Files\Energy Solutions\PLStudio\plstudio.exe /RunTransient /CloseWhenFinishedC:\data\demo.tgw

    This would, in order:

    start pipel ines tud io

    open the demo.tgw file from the c:\data folder

    run a transient simulation

    close pipel inestudio

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    11/19

    Gas Network Training

    8

    2.1.7. Example 6

    C:\Program Files\Energy Solutions\PLStudio\plstudio.exe /RunTransient /StartMinimized

    /CloseWhenFinished C:\data\demo.tgw

    This would, in order:

    start pipel ines tud iominimized

    open the demo.tgw file from the c:\data folder

    run a transient simulation

    close pipel inestudio

    3. Control Options

    The Control Options are a subset of values that are normally set via the Simulation | Optionsmenu. Using the File | Export | Option Datamenu option causes a Control Options file to bewritten to the selected folder. This (plain text) file will contain the options along with their currentvalue in the selected configuration. When the Control Options are imported any number of thecontrol options can be omitted from the import file. The import file can contain one, a selection, orall the control options that are exported. The format of the Control Options file is CommaSeparated Value (CSV) so it can be easily edited either in a text editor or any other applicationthat supports the CSV file format such as Microsoft Excel.

    Control options can be imported and exported either by the menu option File | Export | OptionDataand File | Import | Options Dataor from the command line using the flags

    /ImportOptions options_data_file_name.csvor/ExportOptions options_data_file_name.csv.See the online help file in pipel inestudiofor more information on working with pipel inestudiofrom the command line.

    3.1. Export of Transient Scenario

    The Transient Scenario can now be exported either via the menu File | Export | ScenarioDataor the command line using the flag /ExportScenario scenario_data.csv.

    The format of the scenario data file is Comma Separated Value (CSV) so it can be easily editedeither in any text editor or other application that supports the CSV file format such as MicrosoftExcel.

    See the online help file in pipel inestudiofor more information on working with pipel inestudio

    from the command line.

    3. 2. Addition of fluid data in Import/Export of Initial Data

    Data for supply fluids is now exported with initial data export. When importing initial data for fluids,only the currently used properties for existing fluids can be altered i.e. for a compositional fluid,only the fraction of a constituent component can be altered.

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    12/19

    Gas Network Training

    9

    4. PipelineStudio import and export file formats

    The main file type used for import and export by pipel inestudiois the comma separated value

    (CSV) file.

    This file has the format:

    Data 1, Data 2, Data3

    The comma indicates a field separator.

    There are several different import and export options available for pipel inestudio. These optionsare:

    Import/Export

    Keyword file#The file format describes the configuration of the pipeline network to be studiedin a formatted paragraph file. It is used primarily for processing purpose though some olderconfigurations may be stored in this file format.

    Initial data#This file format describes the pipeline configuration in terms of a CSV file. This fileis used to import boundary condition changes into pipel inestudio. The file does not have tocontain a full description of the network, only the parts which should be changed.

    Scenario data#This file describes a transient scenario in terms of a CSV file which may beexported into pipel inestudio.

    Options data#This file describes the simulation options in a CSV file format. Not all options maybe changed with this file.

    Library file#An archived library may be imported. The file is in a binary file format.

    The files which are normally used for an integrated pipel inestudioapplication are the Initial Datafile, the Scenario file and perhaps the Options file.

    The initial data is normally used to describe any steady set point and constraint changes to thedefaults configuration, the scenario file describes any changes to the default transient scenarioand the options file may describe any changes to the base options.

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    13/19

    Gas Network Training

    10

    5. Creating simple VBA macros

    Visual Basic for Applications is Microsoft$s common application programming language. This isoften called a macro language. A macro is a series of instructions designed to simplify repetitivetasks within a program.

    VBA shares some commonality with Visual Basic, particularly in its syntax, however it is designedspecifically to drive features of a software package, not create a software package in its own right.

    This program uses VBA for Excel as the programming resource, and this section is intended todevelop some basic knowledge of the VBA language to allow us at the end of the session to puttogether a complete application.

    Whilst no attempt is made to !teachhow to or inform of every feature in VBA it is concentratedon developing applications for end users who are not experts and predicated on design from the

    top done but implementation from the bottom up approach.

    Essentially VBA may be considered as a true programming language with a few distinctions fromstand alone Visual Basic, the main one being that VBA cannot be executed outside of it$s parentapplication (in this case Microsoft Excel).

    VBA is a way to write Windows code without having to consider jargon such as API$s and threads,thereby simplifying the development process. It is also a way to use Excel as a formatting andlayout tool so that coding effort is expended on getting the job done not building the graphicaluser interface.

    There are two ways to create VBA macros for Excel. Familiarity with both is advantageous.

    The primary way, and the way most advanced Excel users are familiar with, is to create a macrousing the macro record function. Selecting this function permits a set of repetitive functions to beundertaken in Excel (such as complex formatting to make an imported file type more readableand usable). A user can then play this function back at any time required by selecting the functionfrom the available macros.

    The second way of macro editing is to edit the code in the Visual Basic Editor. This may beaccessed from the menu options or by using !Alt-F11. The Visual Basic Editor is a developmentenvironment which provides the user with access to projects, functions and code contained withinan Excel worksheet (though access to this can be password protected if required).

    During this program both methods may be used at various times, however as editing code is apriority this is the first area that should be concentrated on.

    Initiate a Microsoft Excel session and enter the Microsoft Visual Basic editor (either from Tools |Macro | Visual Basic Editor; or by using Alt-F11).

    When programming it is often the case that you rely on other external resources. Additionalresources to the standard Excel VBA resources may be loaded from the Tools | Referencesoption, however for this program the standard resources should be sufficient.

    Code may be created by simply developing a new macro function and typing the code in. Tocreate the macro function you may simply double click on !Sheet 1in the VBA Project tree,which will initiate a new macro.

    Cells within an Excel worksheet, and the worksheet itself, are !objectsto manipulate. Some codemay be created, thus, to populate some cells with some values:

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    14/19

    Gas Network Training

    11

    Option ExplicitPublic Sub fill_some_cells()

    Worksheets(!Sheet1).Range(!A2:C7).Value = !Hi!End Sub

    This macro may then be run, using the play button from the Visual Basic editor.

    So what this piece of code does is:

    Option Explici Forces explicit declaration of all variables

    Public Sub fill_some_cells() Creates a subroutine called fill_some_cells

    Worksheets(!Sheet1).Range(!A2:C7).Value=Hi! Selects worksheet Sheet1, selects thecells in the rangeA2to C7and populatesthese cells with the value Hi.

    End Sub Closes the sub routine

    5.1. VBA Example 1

    Write a macro which populates cells A2 to C7 with the value !Hi!and then pauses for 10 seconds.

    Continue developing the macro such that then clears cells A2 to C7, and fills cells A1 to A9 with

    values 1 to 9. Perform a calculation on the cells on B1 to B9 which uses the values from A1 to A9;the calculation should be B x=Ax*Ax.

    Finally in the cells C1 to C9, take the value from B1 to B9 and take the cube root of the value.Format the cells such that they are REDif the value in the C column is greater than 3.

    HINT: the hard work can often be done by using the record function to right a lot of a macro foryou. All you need to do then is take the code created and implement it in your new macro.

    File handling may be performed using VBA as well. You can:

    Open a text file

    Write to a text fileDelete a fileOpen a file for writing the command

    6. Case Study: Using Microsoft Excel to automate an integratedPipelineStudio system

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    15/19

    Gas Network Training

    12

    An integrated system where pipel inestudiois used as a component requires the following:

    pipel inestudio

    A FIXED pipel ines tud ionetwork configuration fileA parent application which can:- Generate a Setpoint file- Generate a Scenario file- Generate a Batch file from which to drive pipel inestudio- Has the ability to execute the batch file from the parent application- Has the ability to read data from text files and format to user requirements

    With the application to be developed the following tasks should be performed:

    The code to perform this set of functions is relatively straightforward, selecting data from an Excelworksheet, copying the data in a file (one for set points and one for the scenario); creating a

    Generate set point

    data

    Generate scenario

    data

    Generate batch file

    Execute batch file

    Import trend file

    Develop a trend plot

    using Excel

    Set point file

    Scenario file

    Batch file

    pipel inestudio

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    16/19

    Gas Network Training

    13

    batch file which run steady-state and transient pipel inestudiosimulations using the set point andscenario data that has been created; and finally importing the output trend file into Excel andpresenting a trend plot.

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    17/19

    Gas Network Training

    14

    7. Example Macro Code

    The following section of macro is an example of how the application may be implemented.

    OptionExplicit

    ' Declaring public means the macro will be available to any other spreadsheets,' private means it can only be used in this spreadsheet

    PublicSubCreateSetpointFile()

    'With VBA you need to declare an variables you use in a macro

    DimFileNumAsIntegerDimsSetpointFileNameWithPathAsString

    ' This piece of code creates the setpoint file in the correct location

    sSetpointFileNameWithPath=ThisWorkbook.Path&"\"&"setpoint.csv"

    ' This line makes it a l ittle easier to work with files, we are assigning a free file number' to the variable FileNum

    FileNum=FreeFile

    ' This line permits us to allow read/write access to the setpoints file

    OpensSetpointFileNameWithPathForOutputAccessWriteAs#FileNumClose#FileNum

    ' This section of code copies data from the workbook to the setpoint file

    Worksheets("Setpoints").ActivateWorksheets("Setpoints").UsedRange.SelectSelection.Copy

    Workbooks.OpenFilename:=sSetpointFileNameWithPathSelection.PasteSpecialPaste:=xlValues,operation:=xlNone,SkipBlanks:=_

    False,Transpose:=FalseActiveWorkbook.SaveAsFilename:=sSetpointFileNameWithPath_

    ,FileFormat:=xlCSV, CreateBackup:=False

    EndSub

    PublicSubCreateScenarioFile()

    DimFileNumAsIntegerDimsScenarioFileNameWithPathAsString

    sScenarioFileNameWithPath=ThisWorkbook.Path&"\"&"scenario.csv"

    FileNum=FreeFile

    OpensScenarioFileNameWithPathForOutputAccessWriteAs#FileNumClose#FileNum

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    18/19

    Gas Network Training

    15

    Worksheets("Scenario").ActivateWorksheets("Scenario").UsedRange.SelectSelection.Copy

    Workbooks.OpenFilename:=sScenarioFileNameWithPathSelection.PasteSpecialPaste:=xlValues,operation:=xlNone,SkipBlanks:=_

    False,Transpose:=FalseActiveWorkbook.SaveAsFilename:=sScenarioFileNameWithPath_

    ,FileFormat:=xlCSV, CreateBackup:=False

    EndSub

    PublicSubCreateBatchFileAndRun()

    DimFileNumAsInteger

    DimsBatchFileWithPath,sStudioCommand,sStudioPath,sPLSIDAsString

    ' Here we create the batch file

    sBatchFileWithPath=ThisWorkbook.Path&"\"&"pls.bat"

    FileNum=FreeFile

    ' This is the command we use to run pipel inestudio, note in this case we are using a direct path to each

    file

    sStudioCommand="cmd /k Start Plstudio /importdata "&ThisWorkbook.Path&"\setpoints.csv/scenariodata "&ThisWorkbook.Path&"\scenario.csv /StartMinimized /CloseWhenFinished/RunTransient "&ThisWorkbook.Path&"\Simulation_base.tgw"

    OpensBatchFileWithPathForOutputAs#FileNum

    Write#FileNum,sStudioCommand

    Close#FileNum

    ' This piece of code runs the batch file

    sPLSID=(ThisWorkbook.Path&"\pls.bat")

    OnErrorResumeNextAppActivate(Shell(sPLSID))

    EndSub

  • 8/14/2019 PipelineStudio Gas Simulator Module Excel_English

    19/19

    Gas Network Training

    16

    PublicSubImportWTGFile()

    ' This code opens the WTG file, copies the data and pastes it inot our worksheet

    Workbooks.OpenTextFilename:=ThisWorkbook.Path &"\"&"Simulation_Base.wtg"Workbooks( "Simulation_Base.wtg").Worksheets("Simulation_Base").ActivateWorkbooks( "Simulation_Base.wtg").Worksheets("Simulation_Base").UsedRange.SelectSelection.CopyWorkbooks( "Application.xls").Worksheets("Results").Activate

    ActiveWorkbook.Worksheets("Results").Range("A1").SelectActiveWorkbook.Worksheets("Results").Paste

    EndSub

    PublicSubGraphInventory()

    ' This code creates a graph of inventory

    Workbooks( "Application.xls").Worksheets("Results").Activate

    ActiveWindow.SmallScrollToRight:=137Range("ER1").Select

    ActiveCell.FormulaR1C1 ="Inv Sum"Range("ER7").Select

    ActiveCell.FormulaR1C1 ="MMSCF"Range("ER8").Select

    ActiveCell.FormulaR1C1 =_"=SUM(RC[-140]+RC[-133]+RC[-126]+RC[-119]+RC[-112]+RC[-105]+RC[-98]+RC[-91]+RC[-

    84]+RC[-77]+RC[-70]+RC[-63]+RC[-56]+RC[-49]+RC[-42]+RC[-35]+RC[-28]+RC[-21]+RC[-

    14]+RC[-7])"Range("ER8").SelectSelection.AutoFill Destination:=Range("ER8:ER68"),Type:=xlFillDefaultRange("ER8:ER68").SelectCharts.Add

    ActiveChart.ChartType=xlXYScatterSmoothNoMarkersActiveChart.LocationWhere:=xlLocationAsNewSheet,Name:="Inventory"WithActiveChart

    .HasTitle=True

    .ChartTitle.Characters.Text="Inventory Vs Time"

    .Axes(xlCategory,xlPrimary).HasTitle=True

    .Axes(xlCategory,xlPrimary).AxisTitle.Characters.Text="Time"

    .Axes(xlValue,xlPrimary).HasTitle=True

    .Axes(xlValue,xlPrimary).AxisTitle.Characters.Text="Inventory"EndWith

    ActiveChart.HasLegend=FalseApplication.CommandBars("Chart").Visible=False

    EndSub