0% found this document useful (0 votes)
260 views214 pages

New Text Document

This VBA module contains macros for initializing and interacting with an eBrowser object embedded in a worksheet. The macros initialize the eBrowser, search for objects by position ID or object ID, and activate an eBrowser sheet to view search results. Functions are also included to get position ID and object ID from cells and check if the eBrowser object is available.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
260 views214 pages

New Text Document

This VBA module contains macros for initializing and interacting with an eBrowser object embedded in a worksheet. The macros initialize the eBrowser, search for objects by position ID or object ID, and activate an eBrowser sheet to view search results. Functions are also included to get position ID and object ID from cells and check if the eBrowser object is available.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 214

Rem Attribute VBA_ModuleType=VBAModule

Option VBASupport 1
'
' eBrowser related stuff
'

Sub EbrowserInitialize(load_ebr As Boolean, incl_setup_ref As Boolean)

EbrowserInitialized = False
If Not WorksheetExists(eBrowserSheet) Then Exit Sub
Dim eb_file As String, Sh As String, cl As String, isLoaded
eb_file = arr_settings(HeaderLine8, 83)
If eb_file = "" Or File_Exists(eb_file) = False Then Exit Sub

Application.ScreenUpdating = False
Sh = ActiveSheet.Name
cl = ActiveCell.Address

If EbrowserObjectsIsAvailable(incl_setup_ref) = False Then


Call sheet_sel(Sh)
Range(cl).Select
Application.ScreenUpdating = True
Exit Sub
End If

With Sheets(eBrowserSheet).OLEObjects(eb_objname)
.Object.ptyModelFileName = "file:///" & eb_file
.Object.ptyAutoInit = False 'otherwise error when going to ebrowser
sheet! and search in ebm remains in loop
.Object.mthIsModelDataLoaded isLoaded
If isLoaded = True Then
EbrowserInitialized = True
Else
If load_ebr = True Then
Application.StatusBar = "Initializing eBrowser"
'do an Activate and InitializeAndDraw (both! and also in this
order!)
.Activate
.Object.mthInitializeAndDraw
.Object.mthEnableObjectEvents "Find Object in Report;", "xml"
Application.StatusBar = False 'Clear previous statusbar text
EbrowserInitialized = True
End If
End If
End With

Call sheet_sel(Sh)
Range(cl).Select
Application.ScreenUpdating = True
End Sub

Sub set_size_eb_object(arg As Integer)


'set size of eBrowser object to visible range of the sheet
Dim L As Integer, h As Integer, W As Integer, extra_edge As Integer,
extra_edge_W As Integer
If Sheets(eBrowserSheet).Cells(1, 1).Value = "button" Then
L = 16
Else
L = 0
End If
extra_edge_H = 6
extra_edge_W = 40 + L
h = ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Height -
extra_edge_H
W = ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Width -
extra_edge_W

With Sheets(eBrowserSheet).Buttons(1)
.Height = h
End With
With Sheets(eBrowserSheet).OLEObjects(eb_objname)
.Left = L
.Top = 0
.Height = h
.Width = W
End With

End Sub

Sub search_eb_object(arg As String)


Call EbrowserInitialize(True, False) 'initialize the connection to the
eBrowserfile

If EbrowserInitialized = False Then


Sheets(eBrowserSheet).Visible = False
Exit Sub
End If

Dim Act_Sheet As String, Act_SheetIndex As Integer, Act_Cell As String,


Act_Cell_r As Long
Dim field_vpo As String, Act_Cell_c As Integer, positionID As String, ObjectID
As String
Dim ColName As String, ObiRef As String, COL_OBIREF As Integer, col As Integer
Dim OneObi As String
Act_Sheet = ActiveSheet.Name
Act_SheetIndex = ActiveSheet.index
Act_Cell = ActiveCell.Address
Act_Cell_r = ActiveCell.row
Act_Cell_c = ActiveCell.Column
ColName = GetCurrentColumnName(Act_Cell_c)
If ColName = "" Then Exit Sub

positionID = get_positionID(Act_Cell_r)
If positionID <> "" Then
Call activate_ebrowser_sheet(Act_Sheet, Act_Cell)
Call FindPosID(positionID)
Call set_size_eb_object(1)
Exit Sub
End If

col = conv_to_number("COL_OBIREF")
If col <> 0 Then
col = arr_settings(HeaderLine2, col) + ListStartCol - 1 'get column
position
ObiRef = Act_SheetIndex & "_" & Cells(Act_Cell_r, col).Value
OneObi = ""
If FindObirefFromImportList(ObiRef, OneObi) = True Then
Call activate_ebrowser_sheet(Act_Sheet, Act_Cell)
Call ShowObirefInEbrowser(OneObi)
Call set_size_eb_object(1)
Else
' nothing found (for instance because of no obi at slaveparts)
Call sheet_sel(Act_Sheet)
Range(Act_Cell).Select
End If
Else
MsgBox "ReportGenerator debug f2" 'actually this should not occur, else:
find out what the leak is
End If

End Sub

Function get_positionID(RowNr As Long) As String


Dim field_vpo_c As Integer, field_nam_c As Integer, field_ipo_c As Integer, col
As Integer
get_positionID = ""

col = conv_to_number("COL_VPO")
If col <> 0 Then
field_vpo_c = arr_settings(HeaderLine2, col) + ListStartCol - 1
get_positionID = Cells(RowNr, field_vpo_c).Value
If get_positionID <> "" Then Exit Function
End If

col = conv_to_number("COL_NAM")
If col <> 0 Then
field_nam_c = arr_settings(HeaderLine2, col) + ListStartCol - 1
get_positionID = Cells(RowNr, field_nam_c).Value
If get_positionID <> "" Then Exit Function
End If

col = conv_to_number("COL_IPO")
If col <> 0 Then
field_ipo_c = arr_settings(HeaderLine2, col) + ListStartCol - 1
get_positionID = Cells(RowNr, field_ipo_c).Value
If get_positionID <> "" Then Exit Function
End If
End Function

Function get_objectID(RowNr As Long) As String


Dim field_obi_c As Integer, col As Integer
get_objectID = ""
col = conv_to_number("COL_OBI")
If col <> 0 Then
field_obi_c = arr_settings(HeaderLine2, col) + ListStartCol - 1
get_objectID = Cells(RowNr, field_obi_c).Value
If get_objectID <> "" Then Exit Function
End If
End Function

Sub activate_ebrowser_sheet(Act_Sheet As String, Act_Cell As String)


Sheets(eBrowserSheet).Visible = True
Sheets(eBrowserSheet).Activate
On Error Resume Next
Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthExitExamineMode ' works
from v6
On Error GoTo 0
Call set_size_eb_object(1)
Sheets(eBrowserSheet).Cells(1, 1).Value = "button"
Sheets(eBrowserSheet).Cells(1, 2).Value = Act_Sheet
Sheets(eBrowserSheet).Cells(1, 3).Value = Act_Cell
End Sub
Sub FindPosID(positionID As String)
Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthLocateByPosition
positionID, 0
Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthShowSidebar (True)
End Sub

Sub FindObjID(ObjectID As String)


Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthLocateById ObjectID
'ObjectId is now found, but in tree is still the last PositionId and also in
top of window
' there is the text about examining that PostionID. This is confusing: so
therefor we hide
'the eBrowser-mthShowSidebar
Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthShowSidebar (False)
End Sub

Function EbrowserObjectsIsAvailable(incl_setup_ref As Boolean) As Boolean


EbrowserObjectsIsAvailable = False
For Each eb_shape In Sheets(eBrowserSheet).Shapes
If eb_shape.Name = eb_objname Then
EbrowserObjectsIsAvailable = True
Exit For
End If
Next eb_shape

If EbrowserObjectsIsAvailable = True Then Exit Function


Sheets(eBrowserSheet).Visible = True
Sheets(eBrowserSheet).Select

If AddEbrowserObject(1) = True Then


EbrowserObjectsIsAvailable = True
Exit Function
End If

If incl_setup_ref = False Then


Sheets(eBrowserSheet).Visible = True
Exit Function
End If

If AddEbrowserReference(1) = False Then


Exit Function
End If

If AddEbrowserObject(1) = True Then


EbrowserObjectsIsAvailable = True
Exit Function
End If
Sheets(eBrowserSheet).Visible = False
MsgBox "Not succeeded to Add Ebrowser object"
End Function

Function AddEbrowserObject(arg As String) As Boolean


Dim ebrowser_object As OLEObject, h As Integer, extra_edge As Integer,
extra_edge_W As Integer
h = ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Height
extra_edge_H = 6
extra_edge_W = 40

On Error Resume Next


Set ebrowser_object =
ActiveSheet.OLEObjects.Add(classtype:="ebrowser.eBrowser.1", Link:=False, _
DisplayAsIcon:=False, _
Left:=0, Top:=0, _

Width:=ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Width -
extra_edge_H, _

Height:=ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Height -
extra_edge_W)
ebrowser_object.Name = eb_objname
If Err = 0 Then
AddEbrowserObject = True
Else
AddEbrowserObject = False
End If
On Error GoTo 0 ' set back to the default error handling in VB
End Function

Sub setup_eBrowserSheet_____this_function_is_not_used(arg As Integer)


If WorksheetExists(eBrowserSheet) Then Exit Sub
' actually this sheet is already defined as default (incl OLEobject and buton)

Dim remembered_activesheetname As String, remembered_activecell As String


Dim eb_file As String, RememberCurDir As String, ebrowser_object As OLEObject
Dim extra_edge As Integer, extra_edge_W As Integer
remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address

Sheets.Add 'Add new sheet


ActiveSheet.Name = eBrowserSheet 'Rename new sheet
ActiveSheet.Tab.ColorIndex = 41 ' some color
ActiveSheet.Move Before:=Sheets(1) 'move sheet to be first sheet
With ActiveWindow
.DisplayGridlines = False
.DisplayHeadings = False
End With

Dim btn As Button, h As Integer


h = ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Height
Set btn = ActiveSheet.Buttons.Add(Left:=0, Top:=0, Width:=16, Height:=h)
btn.Caption = "<<" 'buttontext
btn.Font.Bold = True
btn.Font.Underline = True
btn.OnAction = "button_switch_back_to_sheet"

extra_edge_H = 6
extra_edge_W = 25
Set ebrowser_object =
ActiveSheet.OLEObjects.Add(classtype:="ebrowser.eBrowser.1", Link:=False, _
DisplayAsIcon:=False, _
Left:=0, Top:=0, _
Width:=ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Width -
extra_edge_H, _

Height:=ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Height -
extra_edge_W)
ebrowser_object.Name = eb_objname

Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select
End Sub

'
' 'ask for location of eBrowserfile
'
Function get_ebfile() As String
Dim eb_file As String
If WorksheetExists(eBrowserSheet) Then
eb_file = arr_settings(HeaderLine8, 83)
Else
eb_file = ""
End If
If eb_file <> "" And File_Exists(eb_file) = True Then
If MsgBox("Connect to eBrowser-file:" & Chr(10) & Chr(10) & "< " & eb_file
& " >" & Chr(10) & _
Chr(10) & "OK ?" & Chr(10), _
vbQuestion + vbYesNo, "eBrowser link") = vbNo Then
'ask user to select the eBrowser file
eb_file = Application.GetOpenFilename("Select eBrowser file
(*.ebm), *.ebm")
End If
Else
Dim fname_tmp As String
fname_tmp = ThisWorkbook.Name
fname_tmp = ThisWorkbook.Path & "\" & Left(fname_tmp, Len(fname_tmp) - 4) &
".ebm"
If File_Exists(fname_tmp) Then
eb_file = fname_tmp
If MsgBox("Connect to eBrowser-file:" & Chr(10) & Chr(10) & "< " &
eb_file & " >" & Chr(10) & _
Chr(10) & "OK ?" & Chr(10), _
vbQuestion + vbYesNo, "eBrowser link") = vbNo Then
'ask user to select the eBrowser file
eb_file = Application.GetOpenFilename("Select eBrowser file
(*.ebm), *.ebm")
End If
Else
MsgBox "Could not find eBrowser-file <" & eb_file & " >"
'ask user to select the eBrowser file:
eb_file = Application.GetOpenFilename("Select eBrowser file (*.ebm),
*.ebm")
End If
End If

If eb_file <> "" And File_Exists(eb_file) = True Then


get_ebfile = eb_file
arr_settings(HeaderLine8, 83) = eb_file 'store eb_file
End If
End Function
Sub switch_to_eBrowsersheet(WithButton As Boolean)
If WithButton = True And ActiveSheet.Name <> eBrowserSheet Then
Sheets(eBrowserSheet).Cells(1, 1).Value = "button" 'signal field
Else
Sheets(eBrowserSheet).Cells(1, 1).Value = ""
End If
Sheets(eBrowserSheet).Cells(1, 2).Value = ActiveSheet.Name
Sheets(eBrowserSheet).Cells(1, 3).Value = ActiveCell.Address
Sheets(eBrowserSheet).Visible = True
Sheets(eBrowserSheet).Activate
Call set_size_eb_object(1)
End Sub

Private Sub button_switch_back_to_sheet()


Call init(1)
Dim remembered_activesheetname As String, remembered_activecell As String
remembered_activesheetname = Sheets(eBrowserSheet).Cells(1, 2).Text
remembered_activecell = Sheets(eBrowserSheet).Cells(1, 3).Text
Call sheet_sel(remembered_activesheetname)
If remembered_activecell <> "" Then Range(remembered_activecell).Select
End Sub

Function GetCurrentColumnName(ColNr As Integer) As String


GetCurrentColumnName = ""
For col = 1 To Col_ArraySize
col_position = arr_settings(HeaderLine2, col) + ListStartCol - 1
If col_position = ColNr Then
ColName = arr_settings(HeaderLine1, col)
End If
Next col

If ColName <> "" Then GetCurrentColumnName = ColName


End Function

Sub GotoObiRef(ObiRef As String)


Dim SheetNo As Integer, SheetRowGroup As Long, SheetRow As Long
pos = InStr(ObiRef, "_")
SheetNo = Left$(ObiRef, pos - 1)
SheetRowGroup = Mid$(ObiRef, pos + 1, Len(ObiRef))
Sheets(SheetNo).Visible = True
Sheets(SheetNo).Activate
SheetRow = GetSheetRow(SheetRowGroup, SheetNo)
Sheets(SheetNo).Rows(SheetRow & ":" & SheetRow).Select
End Sub

Function GetSheetRow(SheetRowGroup As Long, SheetNo As Integer) As Long


Dim arr_SheetRowGroups As Variant 'MUST be variant
Dim LastRowColA As Long, nr_of_rows As Long, col_nr As Integer
LastRowColA = last_row_nr(ListStartLine, ListStartCol)
nr_of_rows = LastRowColA - ListStartLine + 1
col_nr = arr_settings(HeaderLine2, COL_OBIREF) 'get column position
col_nr = col_nr + ListStartCol - 1

arr_SheetRowGroups = Range(Cells(ListStartLine, col_nr), Cells(LastRowColA,


col_nr)).Value
For rCounter = 1 To nr_of_rows
If arr_SheetRowGroups(rCounter, 1) = SheetRowGroup Then
GetSheetRow = rCounter + ListStartLine - 1
Exit Function
End If
Next rCounter
GetSheetRow = 1 'just the first line as default, because nothing was found
(which actually cannot occur)
End Function

Function FindObiFromImportList(obi As String, ObiRef As String) As Boolean


' IN: obi ( objectID )
' OUT: Obiref ( for instance 8_16 )
'
Application.ScreenUpdating = False
FindObiFromImportList = False
'Preparation for keeping track of objectID references
Dim Size_arr_obi As Long
Dim arr_obi As Variant 'MUST be variant
Dim arr_ObiRef As Variant 'MUST be variant
Sheets("import").Visible = True
Sheets("import").Activate
Size_arr_obi = last_row_nr(1, 1) 'call to function last_row_nr()
Call Fill_arr_obi(arr_obi, Size_arr_obi)
Call Fill_arr_obiRef(arr_ObiRef, Size_arr_obi)
For oCounter = 1 To Size_arr_obi
searchKey = "_" & obi & "_"
searchIn = "_" & arr_obi(oCounter, 1) & "_"
If InStr(searchIn, searchKey) > 0 Then ' search by trying to find
postion
ObiRef = arr_ObiRef(oCounter, 1)
If ObiRef <> "" Then
FindObiFromImportList = True
Exit For
End If
End If
Next oCounter
Sheets("import").Visible = False
Sheets(eBrowserSheet).Visible = True
Sheets(eBrowserSheet).Activate
Application.ScreenUpdating = True
End Function

Function FindObirefFromImportList(ObiRef As String, OneObiField As String) As


Boolean
' IN: Obiref ( for instance: 8_16 )
' OUT: arr_obi ( array of objectID's )
'
Application.ScreenUpdating = False
FindObirefFromImportList = False
'Preparation for keeping track of objectID references
Dim Size_arr_obi As Long, obi_sel_no As Long, pos As Integer
obi_sel_no = 0
Dim arr_obi As Variant 'MUST be variant
Dim arr_ObiRef As Variant 'MUST be variant
Dim arr_obi_sel As Variant 'MUST be variant

Sheets("import").Visible = True
Sheets("import").Activate
Size_arr_obi = last_row_nr(1, 1) 'call to function last_row_nr()
ReDim arr_obi_sel(1 To Size_arr_obi) As String
Call Fill_arr_obi(arr_obi, Size_arr_obi)
Call Fill_arr_obiRef(arr_ObiRef, Size_arr_obi)
Sheets("import").Visible = False

For oCounter = 1 To Size_arr_obi


If arr_ObiRef(oCounter, 1) = ObiRef Then
If arr_obi(oCounter, 1) <> "" Then
obi_sel_no = obi_sel_no + 1
arr_obi_sel(obi_sel_no) = arr_obi(oCounter, 1)
End If
End If
Next oCounter

If obi_sel_no = 0 Then ' no objects in set, so exit


FindObirefFromImportList = False
Exit Function
End If

If obi_sel_no = 1 Then 'if one object in set, we can exit because that one obi
will be searched
OneObiField = arr_obi_sel(1)
pos = InStr(OneObiField, "_") ' search by trying to find postion Then, if
not found this means there is only one obi in this field
If pos = 0 Then
FindObirefFromImportList = True
Exit Function
End If
End If

If WriteObisToATextFile(arr_obi_sel, obi_sel_no) = False Then


Exit Function
End If

FindObirefFromImportList = True
Application.ScreenUpdating = True
End Function

Function WriteObisToATextFile(arr_obi_sel As Variant, obi_sel_no As Long) As


Boolean
WriteObisToATextFile = False

Dim LocalPath As String, ebm_filename As String, ObiFile As String


LocalPath = RegKeyRead("HKLM\SOFTWARE\Cadmatic\eBrowser\LocalPath")
If LocalPath = "" Or FolderExists(LocalPath) = False Then
MsgBox "Cannot find the LocalPath of the eBrowser: " & LocalPath
Exit Function
End If
ebm_filename = arr_settings(HeaderLine8, 83)
ebm_filename = GetFilenameFromPath(ebm_filename)
ebm_filename = GetFilenameWithoutExtension(ebm_filename)
ObiFile = LocalPath & "\" & ebm_filename & "\ReportGeneratorSet.set"
If File_Exists(ObiFile) = True Then
Kill ObiFile
If File_Exists(ObiFile) = True Then
MsgBox "Failed to delete file: " & ObiFile
Exit Function
End If
End If

'Open and write file


Dim str As String, obi_before As String, pos As Integer
fnum = FreeFile() 'set and open file for output
Open ObiFile For Output As fnum
For counter = 1 To obi_sel_no
str = arr_obi_sel(counter)
Do ' if there are several obi's (seperated with "_") then get them one
by one in this loop
pos = InStr(str, "_")
If pos = 0 Then
Print #fnum, str
Exit Do
Else
obi_before = Left$(str, pos - 1) ' part before the "_"
str = Mid$(str, pos + 1, Len(str)) ' part after the "_"
Print #fnum, obi_before
End If
Loop
Next counter
Close #fnum

WriteObisToATextFile = True
End Function

'reads the value for the registry key i_RegKey


'if the key cannot be found, the return value is ""
Function RegKeyRead(i_RegKey As String) As String
Dim myWS As Object
On Error Resume Next
Set myWS = CreateObject("WScript.Shell") 'access Windows scripting
RegKeyRead = myWS.RegRead(i_RegKey) 'read key from registry
End Function

Function GetFilenameFromPath(ByVal strPath As String) As String


' Returns the rightmost characters of a string upto but not including the rightmost
'\'
' e.g. 'c:\winnt\win.ini' returns 'win.ini'

If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then


GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1))
+ Right$(strPath, 1)
End If
End Function
Function GetFilenameWithoutExtension(ByVal strPath As String) As String
'get filename without extension
Dim posn As Integer
posn = InStr(strPath, ".")
If posn <> 0 Then
GetFilenameWithoutExtension = Left(strPath, posn - 1)
Else
GetFilenameWithoutExtension = strPath
End If
End Function

Sub ShowObirefInEbrowser(OneObi As String)


Dim position As Integer
position = InStr(OneObi, "_") ' search by trying to find postion Then, if not
found this means there is only one obi in this field
If OneObi <> "" And position = 0 Then
Call FindObjID(OneObi)
Exit Sub
End If

Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthEnableModel (False)
Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthSetSetVisibility
"ReportGeneratorSet", 1
'Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthShowSidebar (False)

End Sub

===================================================================================
================

Rem Attribute VBA_ModuleType=VBADocumentModule


Option VBASupport 1
Private Sub Workbook_Open()
Call init(1)
If VB_References_OK(1) = False Then
MsgBox "Reprort Generator aborted because there seems to be a problem with
VB-references."
Else
Call Workbook_Open2
End If
End Sub

Private Sub Workbook_Open2()


If WorksheetExists("RunImportMacroOnlyOnce") Then
' delete signal-worksheet,
' but only when not in debug-mode (then filename is 'ReportToExcel')

If ThisWorkbookName <> Left(ThisWorkbook.Name, 11) = "ReportToExcel" Then


Application.DisplayAlerts = False 'to avoid questions when deleting
Worksheets("RunImportMacroOnlyOnce").Delete
Application.DisplayAlerts = True
End If

'run import macro


Call Macro_Main_Import
Else
'create or update custom menu
If WorksheetExists("settings") Then
Call ReadSettings(1)
Call CreateMenu(1)
End If
End If
End Sub

Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As


Range, Cancel As Boolean)

Dim item As String, remembered_activesheetname As String, remembered_activecell


As String
Dim ebfile As String, RememberCurDir As String, DriveLetter As String
remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address
If (filtersheets(remembered_activesheetname) = True) Then Exit Sub

'Readsettings
If Not WorksheetExists("settings") Then Exit Sub

Call init(1)
Call ReadSettings(1)
If CheckServicePack(2) Then
Call search_eb_object(1)
End If
End Sub

Private Sub Workbook_WindowResize(ByVal Wn As Window)


Call init(1)
If Not WorksheetExists("settings") Then Exit Sub
If EbrowserObjectExists(1) = True Then Call set_size_eb_object(1)
End Sub

Private Sub Workbook_SheetActivate(ByVal Sh As Object)


If Sh.Name = "eBrowser" Then
With ActiveWindow
.DisplayHorizontalScrollBar = False
.DisplayVerticalScrollBar = False
End With
End If
End Sub

Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)


If Sh.Name = "eBrowser" Then
With ActiveWindow
.DisplayHorizontalScrollBar = True
.DisplayVerticalScrollBar = True
End With
End If
End Sub
===================================================================================
========
Rem Attribute VBA_ModuleType=VBAFormModule
Option VBASupport 1
Private Sub btnOK_Click()
Me.Hide
End Sub

Private Sub btnCancel_Click()


Me.Hide
'Me.lbSelectedItems.Clear
End Sub

Private Sub SettingsButton_Click()


Load Form_Settings
Form_Settings.Show
End Sub

Private Sub UserForm_Initialize()


Call ReadSettings(1)

Dim LastColRow1 As Integer


LastColRow1 = Col_ArraySize
With Me

.Sum4.Visible = False
.Sum5.Visible = False
.Label14.Visible = False
.Label15.Visible = False

.ListToSheets.AddItem "(None)"
.Sum1.AddItem "(None)"
.Sum2.AddItem "(None)"
.Sum3.AddItem "(None)"
.Sum4.AddItem "(None)"
.Sum5.AddItem "(None)"
.Sort1.AddItem "(None)"
.Sort2.AddItem "(None)"
.Sort3.AddItem "(None)"

.SumAccording.AddItem "Use all rules, and if empty values then don't sum"
.SumAccording.AddItem "Use all rules, and if empty values then sum"
.SumAccording.AddItem "Use rules 1 & 2, and if empty then accord. rule 3"
.SumAccording.AddItem "Use rules 1, if empty: use rule 2, if empty: rule 3"

'For iCounter = 1 To LastColRow1


Dim tmp_txt As String
For iCounter = 1 To LastColRow1
tmp_txt = arr_settings(HeaderLine10, iCounter)
tmp_txt = Replace(tmp_txt, Chr(10), " ") 'delete <Enter> from string
.ListToSheets.AddItem tmp_txt
.Sum1.AddItem tmp_txt
.Sum2.AddItem tmp_txt
.Sum3.AddItem tmp_txt
.Sum4.AddItem tmp_txt
.Sum5.AddItem tmp_txt
.Sort1.AddItem tmp_txt
.Sort2.AddItem tmp_txt
.Sort3.AddItem tmp_txt
Next iCounter

'
'set listfocus to current value
'
Dim SheetDistr_Nr As Integer, SumR1 As Integer, SumR2 As Integer, SumR3 As
Integer, SumR4 As Integer, SumR5 As Integer
Dim SortR1 As Integer, SortR2 As Integer, SortR3 As Integer, sett As String

sett = arr_settings(HeaderLine8, 1)
SheetDistr_Nr = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 2)
SumR1 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 3)
SumR2 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 4)
SumR3 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 78)
SumR4 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 79)

sett = arr_settings(HeaderLine8, 5)
SortR1 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 6)
SortR2 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 7)
SortR3 = conv_to_number(sett)

.ListToSheets.ListIndex = SheetDistr_Nr
.Sum1.ListIndex = SumR1
.Sum2.ListIndex = SumR2
.Sum3.ListIndex = SumR3
.Sum4.ListIndex = SumR4
.Sum5.ListIndex = SumR5
.Sort1.ListIndex = SortR1
.Sort2.ListIndex = SortR2
.Sort3.ListIndex = SortR3

Select Case arr_settings(HeaderLine8, 91)


Case "0"
.SumAccording.ListIndex = 0
Case "1"
.SumAccording.ListIndex = 1
Case "2"
.SumAccording.ListIndex = 2
Case "3"
.SumAccording.ListIndex = 3
Case Else
.SumAccording.ListIndex = 1 ' Default
End Select
End With

End Sub

Private Sub CancelButton_Click()


Me.Hide
End Sub

Private Sub GenerateButton_Click()


Me.Hide

' The subroutine waitpanel_Activate() will call ControlList()


StartedFromListControl = True

waitpanel.LabelProgress.Width = 0
waitpanel.Show vbModeless 'this will trigger a call to waitpanel_Activate()
PctDone = 0
PctDonePrev = 0

Call WriteSettings(1)
End Sub
===================================================================================
============
Rem Attribute VBA_ModuleType=VBAFormModule
Option VBASupport 1
Private Sub UserForm_Initialize()
Call setup_ListView
Call setup_layout
Call setup_miscellaneous
End Sub

Private Sub DoneButton_Click()


Dim coln As String, desc As String, vis As String, tag As String, pip As
String, _
format As String, wid As String, sumtxt As String, col_nr As Integer
For ii = 1 To Col_ArraySize
coln = arr_settings(HeaderLine1, ii)
col_nr = arr_settings(HeaderLine2, ii) 'get column position
coln = sett_table(0, col_nr)
desc = sett_table(1, col_nr)
vis = sett_table(2, col_nr)
tag = Trim(sett_table(3, col_nr))
pip = sett_table(4, col_nr)
format = sett_table(5, col_nr)
wid = sett_table(6, col_nr)
sumtxt = sett_table(7, col_nr)

'arr_settings(HeaderLine1, ii) = coln 'Not needed while not changed


'arr_settings(HeaderLine2, ii) = col_nr 'Not needed while not changed
If vis = "Show" Then vis = "SHOW"
If vis = "Hide" Then vis = "HIDE"
arr_settings(HeaderLine3, ii) = vis
If format = "String" Then format = "string"
If format = "Number, 0 Dec." Then format = "float0"
If format = "Number, 1 Dec." Then format = "float1"
If format = "Number, 2 Dec." Then format = "float2"
If format = "Number, 3 Dec." Then format = "float3"
If format = "date" Then format = "date"
If format = "formula" Then format = "formula"
If InStr(tag, "qty") > 0 Then
If InStr(tag, "~") = 0 Then format = "float0PCS"
End If
arr_settings(HeaderLine4, ii) = format
If format = "formula" Then
If Left(tag, 1) = "=" Then tag = Right(tag, Len(tag) - 1) ' skip first
char when its a '='
End If
arr_settings(HeaderLine5, ii) = tag
If wid = "Autofit" Then wid = ""
If Right(wid, 4) = " Min" Then wid = Left(wid, Len(wid) - 4) & "MIN"
If Right(wid, 4) = " Max" Then wid = Left(wid, Len(wid) - 4) & "MAX"
arr_settings(HeaderLine6, ii) = wid
If sumtxt = "Yes" Then sumtxt = "sum"
If sumtxt = "No" Then sumtxt = ""
arr_settings(HeaderLine7, ii) = sumtxt
For kk = 1 To 6
If pip = tagfrom_options(kk, 1) Then pip = tagfrom_options(kk, 2)
Next kk
'arr_settings(HeaderLine8, ii) =
arr_settings(HeaderLine9, ii) = pip
arr_settings(HeaderLine10, ii) = desc
Next ii

Dim tmp_str As String


If ComboBox_layout.ListIndex >= 0 Then
tmp_str = ComboBox_layout.List(ComboBox_layout.ListIndex)
If tmp_str <> arr_settings(HeaderLine8, 8) Then LayoutSetting_just_changed
= True
arr_settings(HeaderLine8, 8) = tmp_str
If tmp_str <> "LAYOUT1" Then
If CheckBox_hidetitelrow.Value = True Then
arr_settings(HeaderLine8, 13) = "hidetitelrow"
Else
arr_settings(HeaderLine8, 13) = ""
End If

If CheckBox_colwidth_via_sheet.Value = True Then


arr_settings(HeaderLine8, 11) = "columnwidth_via_layoutsheet"
Else
arr_settings(HeaderLine8, 11) = ""
End If
End If
End If
arr_settings(HeaderLine8, 9) = TextBox_sheet_hlines.Text
arr_settings(HeaderLine8, 10) = TextBox_sheet_hcolumns.Text

' arr_settings(HeaderLine8, 12
arr_settings(HeaderLine8, 12) = "0" 'default
If CheckBox_total_fields.Value = False And CheckBox_sum_sheet.Value = False
Then
arr_settings(HeaderLine8, 12) = "0"
End If
If CheckBox_total_fields.Value = True And CheckBox_sum_sheet.Value = False Then
arr_settings(HeaderLine8, 12) = "1"
End If
If CheckBox_total_fields.Value = False And CheckBox_sum_sheet.Value = True Then
arr_settings(HeaderLine8, 12) = "2"
End If
If CheckBox_total_fields.Value = True And CheckBox_sum_sheet.Value = True Then
arr_settings(HeaderLine8, 12) = "3"
End If

If CheckBox_unit.Value = True Then


arr_settings(HeaderLine8, 15) = "1"
Else
arr_settings(HeaderLine8, 15) = "0"
End If

' arr_settings(HeaderLine8, 77)


If CheckBox_contweight1.Value = False And CheckBox_contweight2.Value = False
Then
arr_settings(HeaderLine8, 77) = "0"
End If
If CheckBox_contweight1.Value = True And CheckBox_contweight2.Value = False
Then
arr_settings(HeaderLine8, 77) = "1"
End If
If CheckBox_contweight1.Value = False And CheckBox_contweight2.Value = True
Then
arr_settings(HeaderLine8, 77) = "2"
End If
If CheckBox_contweight1.Value = True And CheckBox_contweight2.Value = True Then
arr_settings(HeaderLine8, 77) = "3"
End If

' arr_settings(HeaderLine8, 80)


If CheckBox_add_qty.Value = True Then
arr_settings(HeaderLine8, 80) = "1"
Else
arr_settings(HeaderLine8, 80) = "0"
End If
' arr_settings(HeaderLine8, 81)
If CheckBox_gaskets.Value = False And CheckBox_nuts.Value = False Then
arr_settings(HeaderLine8, 81) = "0"
End If
If CheckBox_gaskets.Value = True And CheckBox_nuts.Value = False Then
arr_settings(HeaderLine8, 81) = "1"
End If
If CheckBox_gaskets.Value = False And CheckBox_nuts.Value = True Then
arr_settings(HeaderLine8, 81) = "2"
End If
If CheckBox_gaskets.Value = True And CheckBox_nuts.Value = True Then
arr_settings(HeaderLine8, 81) = "3"
End If
If CheckBox_slave.Value = False Then
arr_settings(HeaderLine8, 81) = "4"
End If

' arr_settings(HeaderLine8, 88)


Dim all_bits As String, bit1 As String, bit2 As String, bit3 As String, bit4 As
String
bit1 = "0"
bit2 = "0"
bit3 = "0"
all_bits = arr_settings(HeaderLine8, 88)
bit4 = Mid(all_bits, 4, 1)
If bit4 <> "1" Then bit4 = "0"

If CheckBox_CloseExcel.Value = True Then bit1 = "1"


If CheckBox_exportCSV.Value = True Then bit2 = "1"
If CheckBox_DelSumFile.Value = True Then bit3 = "1"
' If CheckBox_CleanUp.Value = True Then bit4 = "1"
all_bits = bit1 & bit2 & bit3 & bit4
arr_settings(HeaderLine8, 88) = all_bits

' settings about CSV-file export


arr_settings(HeaderLine8, 84) = TextBox_Path.Text
arr_settings(HeaderLine8, 87) = TextBox_columns.Text
arr_settings(HeaderLine8, 86) = TextBox_seperator.Text
If arr_settings(HeaderLine8, 86) = ";" Then arr_settings(HeaderLine8, 86) =
"semicolumn"

col_nr = ComboBox_countcol.ListIndex
arr_settings(HeaderLine8, 14) = conv_colnr_to_colname(col_nr)

'report path
arr_settings(HeaderLine8, 90) = TextBox_reppath.Text

' Header / Footer -definitions


arr_settings(HeaderLine8, 16) = TextBox_lheader.Text
arr_settings(HeaderLine8, 17) = TextBox_cheader.Text
arr_settings(HeaderLine8, 18) = TextBox_rheader.Text
arr_settings(HeaderLine8, 19) = TextBox_lfooter.Text
arr_settings(HeaderLine8, 20) = TextBox_cfooter.Text
arr_settings(HeaderLine8, 21) = TextBox_rfooter.Text

If CheckBox_fitpage.Value = True Then


arr_settings(HeaderLine8, 42) = "1"
Else
arr_settings(HeaderLine8, 42) = "0"
End If

'Write headerlines from array to the cells of the settings-sheet


Call WriteSettings(1)
Call ReadSettings(1) 'to re-set public settings

Unload Form_Settings
End Sub

Private Sub CancelButton_Click()

Unload Form_Settings
'Form_Settings.Show
End Sub

Sub setup_ListView()
ListView1.ListItems.Clear
ListView1.ColumnHeaders.Clear

ListView1.ColumnHeaders.Add , , "", 20
ListView1.ColumnHeaders.Add , , "Title", 100
ListView1.ColumnHeaders.Add , , "Visibility", 38
ListView1.ColumnHeaders.Add , , "Tag", 80
ListView1.ColumnHeaders.Add , , "Tag from", 63
ListView1.ColumnHeaders.Add , , "Format", 65
ListView1.ColumnHeaders.Add , , "Width", 50
ListView1.ColumnHeaders.Add , , "Sum", 25
ListView1.ColumnHeaders.Add , , "Col_nr", 0

ReDim sett_table(0 To 9, 1 To Col_ArraySize) As Variant


Dim coln As String, desc As String, vis As String, tag As String, pip As
String, _
format As String, wid As String, sumtxt As String

For ii = 1 To Col_ArraySize
coln = arr_settings(HeaderLine1, ii)
col_nr = arr_settings(HeaderLine2, ii) 'get column position
desc = arr_settings(HeaderLine10, ii)
desc = Replace(desc, Chr(10), " ") 'delete <Enter> from string
vis = "Hide"
If arr_settings(HeaderLine3, ii) = "SHOW" Then vis = "Show"
tag = Trim(arr_settings(HeaderLine5, ii))
If LCase(arr_settings(HeaderLine7, ii)) = "sum" Then
sumtxt = "Yes"
Else
sumtxt = "No"
End If

' convert internal-text to menu-text:


Select Case Trim(LCase(arr_settings(HeaderLine9, ii)))
Case tagfrom_options(1, 2)
pip = tagfrom_options(1, 1)
Case tagfrom_options(2, 2)
pip = tagfrom_options(2, 1)
Case tagfrom_options(3, 2)
pip = tagfrom_options(3, 1)
Case tagfrom_options(4, 2)
pip = tagfrom_options(4, 1)
Case tagfrom_options(5, 2)
pip = tagfrom_options(5, 1)
Case tagfrom_options(6, 2)
pip = tagfrom_options(6, 1)
Case Else
pip = tagfrom_options(1, 1) ' Plant Modeller
End Select

Select Case Trim(Left(LCase(arr_settings(HeaderLine4, ii)), 6))


Case "string", ""
format = "String"
Case "float0" 'float
format = "Number, 0 Dec."
Case "float1" 'float
format = "Number, 1 Dec."
Case "float2" 'float
format = "Number, 2 Dec."
Case "float3" 'float
format = "Number, 3 Dec."
Case "date" 'date
format = "Date"
Case "formul" 'formula
format = "formula"
If Left(tag, 1) <> "=" Then tag = "=" & tag ' add a '=' as first
char in the formula
Case Else
format = "String"
End Select

wid = Trim(UCase(arr_settings(HeaderLine6, ii)))


If wid = "" Then wid = "Autofit"
If Right(wid, 3) = "MIN" Then
wid = Left(wid, Len(wid) - 3) & " Min"
End If
If Right(wid, 3) = "MAX" Then
wid = Left(wid, Len(wid) - 3) & " Max"
End If

sett_table(0, col_nr) = coln


sett_table(1, col_nr) = desc
sett_table(2, col_nr) = vis
sett_table(3, col_nr) = tag
sett_table(4, col_nr) = pip
sett_table(5, col_nr) = format
sett_table(6, col_nr) = wid
sett_table(7, col_nr) = sumtxt

Next ii

Dim iCounter As Long, AddListviewLine As Boolean, lv_nr As Long


lv_nr = 0
For iCounter = 1 To Col_ArraySize
AddListviewLine = False
If OptionButton1.Value Then
'Visible columns only
If sett_table(2, iCounter) = "Show" Then
AddListviewLine = True
End If
End If
If OptionButton2.Value Then
'Customised Columns only
If Left$(sett_table(0, iCounter), 8) = "COL_CUST" Then
AddListviewLine = True
End If
End If
If OptionButton3.Value Then
'All Columns
AddListviewLine = True
End If

If (AddListviewLine = True) Then


lv_nr = lv_nr + 1
With ListView1
.ListItems.Add , , iCounter
.ListItems(lv_nr).SubItems(1) = sett_table(1, iCounter)
.ListItems(lv_nr).SubItems(2) = sett_table(2, iCounter)
.ListItems(lv_nr).SubItems(3) = sett_table(3, iCounter)
.ListItems(lv_nr).SubItems(4) = sett_table(4, iCounter)
.ListItems(lv_nr).SubItems(5) = sett_table(5, iCounter)
.ListItems(lv_nr).SubItems(6) = sett_table(6, iCounter)
.ListItems(lv_nr).SubItems(7) = sett_table(7, iCounter)
.ListItems(lv_nr).SubItems(8) = iCounter
End With
End If

Next iCounter

End Sub

Private Sub OptionButton1_Click()


setup_ListView
End Sub

Private Sub OptionButton2_Click()


Call setup_ListView
End Sub

Private Sub OptionButton3_Click()


setup_ListView
End Sub

Private Sub Button_EditRow_Click()


Call edit_row
End Sub

Private Sub ListView1_DblClick()


Call edit_row
End Sub

Private Sub ListView1_Click()


If ListView1.SelectedItem > 0 Then
Button_EditRow.Locked = False
Button_EditRow.Enabled = True
Else
Button_EditRow.Locked = True
Button_EditRow.Enabled = False
End If
End Sub
Sub edit_row()
Button_EditRow.Locked = True
Button_EditRow.Enabled = False
'Set ListView1.SelectedItem = ListView1.ListItems(3)
Load Form_settings2
Form_settings2.Show

End Sub

'=======================================================================
' SETTINGS-SHEET LAYOUT
'
Sub setup_layout()

Dim LastColRow1 As Integer


LastColRow1 = Col_ArraySize

ComboBox_layout.AddItem "LAYOUT1"
For Each WorkSh In ActiveWorkbook.Worksheets
If (UCase(Left(WorkSh.Name, 6)) = "LAYOUT") Then
ComboBox_layout.AddItem WorkSh.Name
End If
Next

'
'set listfocus to current value
'
Dim sett As String, nr As Integer, item As String
nr = 0
sett = arr_settings(HeaderLine8, 8)
With Me.ComboBox_layout
.ListIndex = 0 'default
For i = 0 To .ListCount - 1
item = .List(i)
If item = sett Then
.ListIndex = nr
End If
nr = nr + 1
Next i
End With

TextBox_sheet_hlines.Text = arr_settings(HeaderLine8, 9)
TextBox_sheet_hcolumns.Text = arr_settings(HeaderLine8, 10)

If arr_settings(HeaderLine8, 13) = "hidetitelrow" Then


CheckBox_hidetitelrow.Value = True
Else
CheckBox_hidetitelrow.Value = False
End If

If arr_settings(HeaderLine8, 11) = "columnwidth_via_layoutsheet" Then


CheckBox_colwidth_via_sheet.Value = True
Else
CheckBox_colwidth_via_sheet.Value = False
End If

' Header / Footer -definitions


TextBox_lheader.Text = arr_settings(HeaderLine8, 16)
TextBox_cheader.Text = arr_settings(HeaderLine8, 17)
TextBox_rheader.Text = arr_settings(HeaderLine8, 18)
TextBox_lfooter.Text = arr_settings(HeaderLine8, 19)
TextBox_cfooter.Text = arr_settings(HeaderLine8, 20)
TextBox_rfooter.Text = arr_settings(HeaderLine8, 21)

If arr_settings(HeaderLine8, 42) = "1" Then


CheckBox_fitpage.Value = True
Else
CheckBox_fitpage.Value = False
End If

End Sub

Private Sub ComboBox_layout_Change()


If ComboBox_layout.ListIndex = 0 Then
'LAYOUT1 is selected
TextBox_sheet_hlines.Text = "0"
TextBox_sheet_hlines.Locked = True
TextBox_sheet_hlines.BackColor = &H80000011
TextBox_sheet_hcolumns.Text = "0"
TextBox_sheet_hcolumns.Locked = True
TextBox_sheet_hcolumns.BackColor = &H80000011

CheckBox_hidetitelrow.Locked = True
CheckBox_hidetitelrow.Enabled = False
CheckBox_colwidth_via_sheet.Locked = True
CheckBox_colwidth_via_sheet.Enabled = False
Label5.Enabled = False
Label6.Enabled = False
Else
TextBox_sheet_hlines.Text = arr_settings(HeaderLine8, 9)
TextBox_sheet_hlines.Locked = False
TextBox_sheet_hlines.BackColor = &H80000005
TextBox_sheet_hcolumns.Text = arr_settings(HeaderLine8, 10)
TextBox_sheet_hcolumns.Locked = False
TextBox_sheet_hcolumns.BackColor = &H80000005

CheckBox_hidetitelrow.Locked = False
CheckBox_hidetitelrow.Enabled = True
CheckBox_colwidth_via_sheet.Locked = False
CheckBox_colwidth_via_sheet.Enabled = True
Label5.Enabled = True
Label6.Enabled = True
End If
End Sub

Private Sub TextBox_sheet_hcolumns_KeyPress(ByVal KeyAscii As


MSForms.ReturnInteger)
ch = Chr$(KeyAscii)
If Not (ch >= "0" And ch <= "9") Then
' Cancel the character.
KeyAscii = 0
MsgBox ("Enter numbers only")
End If
End Sub

Private Sub TextBox_sheet_hlines_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)


ch = Chr$(KeyAscii)
If Not (ch >= "0" And ch <= "9") Then
' Cancel the character.
KeyAscii = 0
MsgBox ("Enter numbers only")
End If
End Sub

'=======================================================================
' SETTINGS-SHEET Miscellaneous
'
Sub setup_miscellaneous()
Dim sep As String
Select Case Trim(arr_settings(HeaderLine8, 12))
Case "0"
CheckBox_total_fields.Value = False
CheckBox_sum_sheet.Value = False
CheckBox_contweight1.Enabled = False
CheckBox_contweight2.Enabled = False
Case "1"
CheckBox_total_fields.Value = True
CheckBox_sum_sheet.Value = False
CheckBox_contweight1.Enabled = True
CheckBox_contweight2.Enabled = False
Case "2"
CheckBox_total_fields.Value = False
CheckBox_sum_sheet.Value = True
CheckBox_contweight1.Enabled = False
CheckBox_contweight2.Enabled = True
Case "3"
CheckBox_total_fields.Value = True
CheckBox_sum_sheet.Value = True
CheckBox_contweight1.Enabled = True
CheckBox_contweight2.Enabled = True
Case Else
CheckBox_total_fields.Value = False
CheckBox_sum_sheet.Value = False
CheckBox_contweight1.Enabled = False
CheckBox_contweight2.Enabled = False
End Select

Select Case Trim(arr_settings(HeaderLine8, 77))


Case "0"
CheckBox_contweight1.Value = False
CheckBox_contweight2.Value = False
Case "1"
CheckBox_contweight1.Value = True
CheckBox_contweight2.Value = False
Case "2"
CheckBox_contweight1.Value = False
CheckBox_contweight2.Value = True
Case "3"
CheckBox_contweight1.Value = True
CheckBox_contweight2.Value = True
Case Else
CheckBox_contweight1.Value = False
CheckBox_contweight2.Value = False
End Select

Select Case Trim(arr_settings(HeaderLine8, 80))


Case "1"
CheckBox_add_qty.Value = True
Case Else
CheckBox_add_qty.Value = False
End Select

Select Case Trim(arr_settings(HeaderLine8, 81))


Case "0"
CheckBox_gaskets.Value = False
CheckBox_nuts.Value = False
CheckBox_slave.Value = True
Case "1"
CheckBox_gaskets.Value = True
CheckBox_nuts.Value = False
CheckBox_slave.Value = True
Case "2"
CheckBox_gaskets.Value = False
CheckBox_nuts.Value = True
CheckBox_slave.Value = True
Case "3"
CheckBox_gaskets.Value = True
CheckBox_nuts.Value = True
CheckBox_slave.Value = True
Case "4"
CheckBox_gaskets.Value = False
CheckBox_nuts.Value = False
CheckBox_slave.Value = False
Case Else
CheckBox_gaskets.Value = False
CheckBox_nuts.Value = False
CheckBox_slave.Value = True
End Select

TextBox_Path.Text = arr_settings(HeaderLine8, 84)


sep = arr_settings(HeaderLine8, 86)
If sep = "semicolumn" Then sep = ";"
TextBox_seperator.Text = sep
TextBox_columns.Text = arr_settings(HeaderLine8, 87)

TextBox_reppath.Text = arr_settings(HeaderLine8, 90)

Dim all_bits As String, bit1 As String, bit2 As String, bit3 As String, bit4 As
String
all_bits = arr_settings(HeaderLine8, 88)
bit1 = Mid(all_bits, 1, 1)
bit2 = Mid(all_bits, 2, 1)
bit3 = Mid(all_bits, 3, 1)
bit4 = Mid(all_bits, 4, 1)
If bit1 = "1" Then
CheckBox_CloseExcel.Value = True
Else
CheckBox_CloseExcel.Value = False
End If
If bit2 = "1" Then
CheckBox_exportCSV.Value = True
Else
CheckBox_exportCSV.Value = False
End If
If bit3 = "1" Then
CheckBox_DelSumFile.Value = True
Else
CheckBox_DelSumFile.Value = False
End If

' Freeze / not freeze


If CheckBox_exportCSV.Value = False Then
Label36.Enabled = False
TextBox_seperator.Enabled = False
Label37.Enabled = False
TextBox_columns.Enabled = False
Label38.Enabled = False
DirButton.Enabled = False

TextBox_seperator.Locked = True
TextBox_columns.Locked = True
DirButton.Locked = True
Else
Label36.Enabled = True
TextBox_seperator.Enabled = True
Label37.Enabled = True
TextBox_columns.Enabled = True
Label38.Enabled = True
DirButton.Enabled = True

TextBox_seperator.Locked = False
TextBox_columns.Locked = False
DirButton.Locked = False
End If

Dim SP As Integer, SP_str As String


SP_str = Trim(arr_settings(HeaderLine8, 82))
If SP_str <> "" Then
SP = Val(SP_str)
Else
SP = 0
End If
If SP < 1 Then CheckBox_gaskets.Enabled = False

If Trim(arr_settings(HeaderLine8, 15)) = "1" Then


CheckBox_unit.Value = True
Else
CheckBox_unit.Value = False
End If

Dim tmp_txt As String


ComboBox_countcol.AddItem "(None)"
For iCounter = 1 To Col_ArraySize
tmp_txt = arr_settings(HeaderLine10, iCounter)
tmp_txt = Replace(tmp_txt, Chr(10), " ") 'delete <Enter> from string
ComboBox_countcol.AddItem tmp_txt
Next iCounter

Dim sett As String, col_nr As Integer


sett = Trim(arr_settings(HeaderLine8, 14))
col_nr = conv_to_number(sett)
ComboBox_countcol.ListIndex = col_nr
End Sub

Private Sub CheckBox_total_fields_Click()


If CheckBox_total_fields.Value = False Then
CheckBox_contweight1.Enabled = False
Else
CheckBox_contweight1.Enabled = True
End If
End Sub
Private Sub CheckBox_sum_sheet_Click()
If CheckBox_sum_sheet.Value = False Then
CheckBox_contweight2.Enabled = False
Else
CheckBox_contweight2.Enabled = True
End If
End Sub

Private Sub CheckBox_exportCSV_Click()


If CheckBox_exportCSV.Value = False Then
Label36.Enabled = False
TextBox_seperator.Enabled = False
Label37.Enabled = False
TextBox_columns.Enabled = False
Label38.Enabled = False
DirButton.Enabled = False

TextBox_seperator.Locked = True
TextBox_columns.Locked = True
DirButton.Locked = True
Else
Label36.Enabled = True
TextBox_seperator.Enabled = True
Label37.Enabled = True
TextBox_columns.Enabled = True
Label38.Enabled = True
DirButton.Enabled = True

TextBox_seperator.Locked = False
TextBox_columns.Locked = False
DirButton.Locked = False
End If
End Sub

Private Sub DirButton_click()


Dim DirName
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
DirName = .SelectedItems(1)
End If
End With
If DirName <> "" Then
TextBox_Path.Text = DirName & "\"
End If
End Sub

Private Sub RepDirButton_click()


Dim DirName
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
DirName = .SelectedItems(1)
End If
End With
If DirName <> "" Then
TextBox_reppath.Text = DirName & "\"
End If
End Sub

Private Sub CheckBox_slave_Change()


If CheckBox_slave.Value = False Then
CheckBox_gaskets.Value = False
CheckBox_nuts.Value = False
End If
End Sub
===================================================================================
==========
Rem Attribute VBA_ModuleType=VBAFormModule
Option VBASupport 1
Private Sub CancelButton_Click()
Unload Form_settings2

End Sub

Private Sub DoneButton_Click()


Dim row As Integer, str As String, index As Integer, col_nr As Integer
row = TextBox_nr.Text
col_nr = Form_Settings.ListView1.ListItems(row).SubItems(8)

If check_duplicate_desc(TextBox_Title.Text, col_nr) = False Then Exit Sub


sett_table(1, col_nr) = TextBox_Title.Text
'sett_table(2, col_nr) = 'not saving Visabillity, while it doesn't change
Call read_tag_fields(str)
sett_table(3, col_nr) = str
index = ComboBox_TagFrom.ListIndex
str = ComboBox_TagFrom.Column(0, index)
sett_table(4, col_nr) = str
index = ComboBox_Format.ListIndex
str = ComboBox_Format.Column(0, index)
sett_table(5, col_nr) = str
str = TextBox_width.Text
If str = "" Then str = "8" 'default in case it was forgotten to fill in the
field
If ComboBox_width.ListIndex = 0 Then str = "Autofit"
If ComboBox_width.ListIndex = 1 Then str = str
If ComboBox_width.ListIndex = 2 Then str = str & " Min"
If ComboBox_width.ListIndex = 3 Then str = str & " Max"
sett_table(6, col_nr) = str
index = ComboBox_sum.ListIndex
str = ComboBox_sum.Column(0, index)
sett_table(7, col_nr) = str

'Fill ListItems in panel


For i = 1 To 7
With Form_Settings.ListView1
.ListItems(row).SubItems(i) = sett_table(i, col_nr)
End With
Next i

Unload Form_settings2
End Sub

Private Sub ComboBox_width_Change()


If ComboBox_width.ListIndex = 0 Then
TextBox_width.Locked = True
TextBox_width.BackColor = &H80000011
CommandButton_width.Enabled = False
Else
TextBox_width.Locked = False
TextBox_width.BackColor = &H80000005
CommandButton_width.Enabled = True
End If
End Sub

Private Sub CommandButton_width_Click()


Dim retrieve_width As Integer, col As Integer
col = TextBox_nr.Text + ListStartCol - 1
retrieve_width = Columns(col).ColumnWidth
TextBox_width.Value = retrieve_width
End Sub

Private Sub ComboBox_Format_Change()


Call ini_formula
End Sub

Private Sub TextBox_width_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)


ch = Chr$(KeyAscii)
If Not (ch >= "0" And ch <= "9") Then
' Cancel the character.
KeyAscii = 0
MsgBox ("Enter numbers only")
End If
End Sub

Private Sub UserForm_Initialize()


Dim selected_index As Long
Dim row As Long, tagstring As String, TagFrom As Integer, formatnr As Integer,
_
sumnr As Integer, widnr As Integer, width_value As Integer, width_str As String
Dim col_nr As Integer
With Form_Settings.ListView1
'loop to find which item is selected, because using "row = .SelectedItem"
'gave problem.
For i = .ListItems.Count To 1 Step -1
If (.ListItems(i).Selected = True) Then row = i
Next i
TextBox_nr.Text = row
TextBox_Title.Text = .ListItems(row).SubItems(1)
TextBox_vis.Text = .ListItems(row).SubItems(2)
tagstring = .ListItems(row).SubItems(3)

Select Case .ListItems(row).SubItems(4)


Case tagfrom_options(1, 1)
TagFrom = 0
Case tagfrom_options(2, 1)
TagFrom = 1
Case tagfrom_options(3, 1)
TagFrom = 2
Case tagfrom_options(4, 1)
TagFrom = 3
Case tagfrom_options(5, 1)
TagFrom = 4
Case tagfrom_options(6, 1)
TagFrom = 5
Case Else
TagFrom = 0
End Select

Select Case .ListItems(row).SubItems(5)


Case "String"
formatnr = 0
Case "Number, 0 Dec."
formatnr = 1
Case "Number, 1 Dec."
formatnr = 2
Case "Number, 2 Dec."
formatnr = 3
Case "Number, 3 Dec."
formatnr = 4
Case "Date"
formatnr = 5
Case "formula"
formatnr = 6
Case Else
formatnr = 0
End Select

width_str = .ListItems(row).SubItems(6)
Select Case Right(width_str, 3)
Case "fit" 'Autofit
widnr = 0
width_value = -1
Case "Min"
widnr = 2
width_value = Left(width_str, Len(width_str) - 4)
Case "Max"
widnr = 3
width_value = Left(width_str, Len(width_str) - 4)
Case Else
widnr = 1
width_value = width_str
End Select

If .ListItems(row).SubItems(7) = "Yes" Then


sumnr = 1
Else
sumnr = 0
End If

col_nr = .ListItems(row).SubItems(8)
End With

If formatnr = 6 Then ' Choosen format is "formula"


TextBox_Formula.Text = tagstring
Else
Dim t1 As String, t2 As String, t3 As String, t4 As String, t5 As String, _
t6 As String, t7 As String, t8 As String, t9 As String, t10 As String, ifm
As Boolean
Call gettag(tagstring, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, ifm)
TextBox_tag1.Text = t1
TextBox_tag2.Text = t2
TextBox_tag3.Text = t3
TextBox_tag4.Text = t4
TextBox_tag5.Text = t5
TextBox_tag6.Text = t6
TextBox_tag7.Text = t7
TextBox_tag8.Text = t8
TextBox_tag9.Text = t9
TextBox_tag10.Text = t10
If (ifm) Then
CheckBox_ifm.Value = True
Else
CheckBox_ifm.Value = False
End If
End If

ComboBox_TagFrom.AddItem tagfrom_options(1, 1)
ComboBox_TagFrom.AddItem tagfrom_options(2, 1)
ComboBox_TagFrom.AddItem tagfrom_options(3, 1)
ComboBox_TagFrom.AddItem tagfrom_options(4, 1)
ComboBox_TagFrom.AddItem tagfrom_options(5, 1)
ComboBox_TagFrom.AddItem tagfrom_options(6, 1)
ComboBox_TagFrom.ListIndex = TagFrom

ComboBox_sum.AddItem "No"
ComboBox_sum.AddItem "Yes"
ComboBox_sum.ListIndex = sumnr

ComboBox_width.AddItem "Autofit"
ComboBox_width.AddItem "Fixed"
ComboBox_width.AddItem "Min."
ComboBox_width.AddItem "Max."
ComboBox_width.ListIndex = widnr
If widnr = 0 Then
TextBox_width.Locked = True
TextBox_width.BackColor = &H80000011
CommandButton_width.Enabled = False
Else
TextBox_width.Locked = False
TextBox_width.BackColor = &H80000005
CommandButton_width.Enabled = True
If width_value > 0 Then TextBox_width.Text = width_value
End If

' unfreeze some fields in case of CUSTOMISED COLUMNS


If Left$(sett_table(0, col_nr), 8) = "COL_CUST" Then
TextBox_tag1.Locked = False
TextBox_tag2.Locked = False
TextBox_tag3.Locked = False
TextBox_tag4.Locked = False
TextBox_tag5.Locked = False
TextBox_tag6.Locked = False
TextBox_tag7.Locked = False
TextBox_tag8.Locked = False
TextBox_tag9.Locked = False
TextBox_tag10.Locked = False
CheckBox_ifm.Locked = False
CheckBox_ifm.Enabled = True ' enable
ComboBox_TagFrom.Locked = False 'ComboBox
ComboBox_Format.Locked = False 'ComboBox
ComboBox_sum.Locked = False 'ComboBox
TextBox_tag1.BackColor = &H80000005
TextBox_tag2.BackColor = &H80000005
TextBox_tag3.BackColor = &H80000005
TextBox_tag4.BackColor = &H80000005
TextBox_tag5.BackColor = &H80000005
TextBox_tag6.BackColor = &H80000005
TextBox_tag7.BackColor = &H80000005
TextBox_tag8.BackColor = &H80000005
TextBox_tag9.BackColor = &H80000005
TextBox_tag10.BackColor = &H80000005
ComboBox_TagFrom.BackColor = &H80000005 'ComboBox
ComboBox_Format.BackColor = &H80000005 'ComboBox
ComboBox_sum.BackColor = &H80000005 'ComboBox
End If

ComboBox_Format.AddItem "String"
ComboBox_Format.AddItem "Number, 0 Dec."
ComboBox_Format.AddItem "Number, 1 Dec."
ComboBox_Format.AddItem "Number, 2 Dec."
ComboBox_Format.AddItem "Number, 3 Dec."
ComboBox_Format.AddItem "Date"
ComboBox_Format.AddItem "formula"
ComboBox_Format.ListIndex = formatnr

Call ini_formula

End Sub

Private Sub ini_formula()


If ComboBox_Format.ListIndex = 6 Then ' Choosen format is "formula"
Frame1.Visible = False
TextBox_Formula.Visible = True
Label33.Visible = True
ValidateFormulaButton.Visible = True
TextBoxHelpFormula.Visible = True
ComboBox_TagFrom.ListIndex = 0 ' Tagfrom-combo is set to PlantMod
Else
Frame1.Visible = True
TextBox_Formula.Visible = False
Label33.Visible = False
ValidateFormulaButton.Visible = False
TextBoxHelpFormula.Visible = False
End If
End Sub

Sub gettag(tagstr As String, t1 As String, t2 As String, t3 As String, _


t4 As String, t5 As String, t6 As String, t7 As String, t8 As String, _
t9 As String, t10 As String, ifm As Boolean)

If Right(tagstr, 5) = "(ifm)" Then


ifm = True
tagstr = Left(tagstr, Len(tagstr) - 5)
Else
ifm = False
End If

'get t9 and t10 ( the part after the ~)


Dim t9_t10 As String
Dim SplitStringA() As String, SplitStringB() As String, SplitString() As String
If InStr(tagstr, "~") > 0 Then
SplitStringA = Split(tagstr, "~")
tagstr = SplitStringA(0)
t9_t10 = SplitStringA(1)
If InStr(t9_t10, "+") > 0 Then
SplitStringB = Split(t9_t10, "+")
t9 = Trim(SplitStringB(0))
t10 = Trim(SplitStringB(1))
Else
t9 = Trim(t9_t10)
End If
End If

If InStr(tagstr, "+") > 0 Then


SplitString = Split(tagstr, "+")
CountOccurances = UBound(SplitString) - LBound(SplitString) + 1
t1 = Trim(SplitString(0))
If CountOccurances > 1 Then t2 = Trim(SplitString(1))
If CountOccurances > 2 Then t3 = Trim(SplitString(2))
If CountOccurances > 3 Then t4 = Trim(SplitString(3))
If CountOccurances > 4 Then t5 = Trim(SplitString(4))
If CountOccurances > 5 Then t6 = Trim(SplitString(5))
If CountOccurances > 6 Then t7 = Trim(SplitString(6))
If CountOccurances > 7 Then t8 = Trim(SplitString(7))
Else
t1 = Trim(tagstr)
End If

End Sub

Sub read_tag_fields(tag As String)


If ComboBox_Format.ListIndex = 6 Then ' Choosen format is "formula"
tag = TextBox_Formula.Text
Exit Sub
End If

Dim t1 As String, t2 As String, t3 As String, t4 As String, t5 As String, _


t6 As String, t7 As String, t8 As String, t9 As String, t10 As String
t1 = Trim(TextBox_tag1.Text)
t2 = Trim(TextBox_tag2.Text)
t3 = Trim(TextBox_tag3.Text)
t4 = Trim(TextBox_tag4.Text)
t5 = Trim(TextBox_tag5.Text)
t6 = Trim(TextBox_tag6.Text)
t7 = Trim(TextBox_tag7.Text)
t8 = Trim(TextBox_tag8.Text)
t9 = Trim(TextBox_tag9.Text)
t10 = Trim(TextBox_tag10.Text)

' when tag begins with a "=" then put a space in front of it to avoid
interpretation as formula
If Left(t1, 1) = "=" Then t1 = " " & t1
If Left(t2, 1) = "=" Then t2 = " " & t2
If Left(t3, 1) = "=" Then t3 = " " & t3
If Left(t4, 1) = "=" Then t4 = " " & t4
If Left(t5, 1) = "=" Then t5 = " " & t5
If Left(t6, 1) = "=" Then t6 = " " & t6
If Left(t7, 1) = "=" Then t7 = " " & t7
If Left(t8, 1) = "=" Then t8 = " " & t8
If Left(t9, 1) = "=" Then t9 = " " & t9
If Left(t10, 1) = "=" Then t10 = " " & t10

tag = t1
If t1 = "" Then
Exit Sub
Else
If t2 <> "" Then
tag = tag & "+" & t2
If t3 <> "" Then
tag = tag & "+" & t3
If t4 <> "" Then
tag = tag & "+" & t4
If t5 <> "" Then
tag = tag & "+" & t5
If t6 <> "" Then
tag = tag & "+" & t6
If t7 <> "" Then
tag = tag & "+" & t7
If t8 <> "" Then
tag = tag & "+" & t8
End If
End If
End If
End If
End If
End If
End If
End If
If t9 <> "" Then
tag = tag & "~" & t9
If t10 <> "" Then tag = tag & "+" & t10
End If

If CheckBox_ifm.Value = True Then tag = tag & "(ifm)"

'Fix: if first char is ' then put space before it otherwise excel will
' skip this when putting value to a cell.
If Left(tag, 1) = "'" Then tag = " " & tag
End Sub

Private Sub ValidateFormulaButton_Click()


Dim tagstring As String, ListStartRow As String, str As String
ListStartRow = Trim(arr_settings(HeaderLine8, 9))
If ListStartRow = "" Or ListStartRow = "0" Then ListStartRow = "3"
tagstring = TextBox_Formula.Text
tagstring = Replace(tagstring, "[R]", ListStartRow)

On Error GoTo ErrorHandlingLabel


Range("HH1").NumberFormat = "General"
Range("HH1").Formula = tagstring
On Error GoTo 0 ' set back to the default error handling in VB
Range("HH1").Value = ""
MsgBox "Formula is OK"
Exit Sub

ErrorHandlingLabel:
MsgBox "Warning, formula is NOT valid: " & tagstring
Range("HH1").Value = ""
On Error GoTo 0 ' set back to the default error handling in VB
End Sub

Function check_duplicate_desc(desc, col_nr) As Boolean


check_duplicate_desc = True
For counter = 1 To Col_ArraySize
If counter <> col_nr And desc = sett_table(1, counter) Then
MsgBox "Description < " & desc & " > is already used in another column.
Please use another description."
check_duplicate_desc = False
Exit For
End If
Next counter
End Function
===================================================================================
===
Rem Attribute VBA_ModuleType=VBAFormModule
Option VBASupport 1
Dim ListContent(1 To 91) As Variant

Private Sub Label2_Click()

End Sub

Private Sub UserForm_Initialize()

Dim item As String


Call ReadSettings(1)

Me.LabelVisibleCol.Clear ' remove existing content


Me.LabelHiddenCol.Clear

' fill ColTitel() array retrieved from arr_settings


For iCounter = 1 To Col_ArraySize
col_nr = arr_settings(HeaderLine2, iCounter) 'get column position
item = arr_settings(HeaderLine10, iCounter)
item = Replace(item, Chr(10), " ") 'delete <Enter> from string
ColTitel(col_nr) = item
'remember all column positions
ColPos(iCounter) = col_nr
Next iCounter

' fill ColHideShow() array retrieved from current sheet and setup panel
For iCounter = 1 To Col_ArraySize
item = ColTitel(iCounter)
If Columns(iCounter + ListStartCol - 1).EntireColumn.Hidden = True Then
Me.LabelHiddenCol.AddItem item
Else
Me.LabelVisibleCol.AddItem item
End If
Next iCounter

End Sub

Private Sub btnOK_Click()


'get last column
Dim LastRowColA As Long, LastColRow1 As Long

Application.ScreenUpdating = False
Me.Hide
Dim WorkSh As Worksheet
Dim remembered_activesheetname As String, remembered_activecell As String
remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address

'
'scan which items are selected to be shown, and fill array
'

Dim c_nr As Integer, titel_desc As String


c_nr = 0
With Me.LabelVisibleCol
For i = 0 To .ListCount - 1
c_nr = c_nr + 1
item = .List(i)
For iCounter = 1 To Col_ArraySize
titel_desc = arr_settings(HeaderLine10, iCounter)
titel_desc = Replace(titel_desc, Chr(10), " ") 'delete <Enter> from
string
If item = titel_desc Then
arr_settings(HeaderLine2, iCounter) = c_nr 'set new column
number
arr_settings(HeaderLine3, iCounter) = "SHOW" 'set Show/Hide
End If
Next iCounter
Next i
End With

With Me.LabelHiddenCol
For i = 0 To .ListCount - 1
c_nr = c_nr + 1
item = .List(i)
For iCounter = 1 To Col_ArraySize
titel_desc = arr_settings(HeaderLine10, iCounter)
titel_desc = Replace(titel_desc, Chr(10), " ") 'delete <Enter> from
string
If item = titel_desc Then
arr_settings(HeaderLine2, iCounter) = c_nr 'set new column
number
arr_settings(HeaderLine3, iCounter) = "HIDE" 'set Show/Hide
End If
Next iCounter
Next i
End With

' Declaration
Dim nr_of_sheets As Long
nr_of_sheets = Sheets.Count
ReDim TotalFields(1 To nr_of_sheets, 1 To 12) As Variant

Dim SheetNr As Long


SheetNr = 0
For Each WorkSh In ActiveWorkbook.Worksheets
If (filtersheets(WorkSh.Name) = False) Then
SheetNr = SheetNr + 1
WorkSh.Select
LastRowColA = last_row_nr_methodB(ListStartLine, ListStartCol) 'call to
function last_row_nr()
LastColRow1 = last_col_nr(ListStartCol) 'call to function
last_col_nr()

'
' re-arrange complete sheet according new position and show/hide
'
Call ReArrange(LastRowColA, LastColRow1, SheetNr)

'activate cell A1, to avoid that previous selection is still active


Range("A1").Select
'set active window to left upper corner
ActiveWindow.ScrollRow = 1
ActiveWindow.ScrollColumn = 1

End If
Next

Call WriteSettings(0)

'HIDE sheets
Call HideSheets(1)

Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select

Application.ScreenUpdating = True
Me.Hide
Unload Form_ShowColumns
End Sub

Private Sub btnCancel_Click()


Me.Hide
Unload Form_ShowColumns

End Sub

Private Sub btnSelect1_Click()


' moves selected items from the HiddenColumns listbox to the Visible Columns
listbox
Dim i As Integer
Application.ScreenUpdating = False

'deselect first all items in visible column ( to see clearly which one is
added)
With Me.LabelVisibleCol
For i = .ListCount - 1 To 0 Step -1
If .Selected(i) Then
.Selected(i) = False
End If
Next i
End With

With Me.LabelHiddenCol
For i = .ListCount - 1 To 0 Step -1
If .Selected(i) Then
.Selected(i) = False
item = .List(i)
Me.LabelVisibleCol.AddItem item
Me.LabelVisibleCol.Selected(Me.LabelVisibleCol.ListCount - 1) =
True
.RemoveItem i

End If
Next i

End With
Application.ScreenUpdating = True
End Sub

Private Sub btnDeSelect1_Click()


' moves selected items from the VisibleColumns listbox to the HiddenColumns listbox

Dim i As Integer
Application.ScreenUpdating = False

'deselect first all items in visible column ( to see clearly which one is
added)
With Me.LabelHiddenCol
For i = .ListCount - 1 To 0 Step -1
If .Selected(i) Then
.Selected(i) = False
End If
Next i
End With

With Me.LabelVisibleCol
'li = .ListIndex
For i = .ListCount - 1 To 0 Step -1
If .Selected(i) Then
item = .List(i)
Me.LabelHiddenCol.AddItem item
Me.LabelHiddenCol.Selected(Me.LabelHiddenCol.ListCount - 1) = True
.RemoveItem i

End If
Next i

'If li >= .ListCount Then li = .ListCount - 1


'.ListIndex = li
End With
Application.ScreenUpdating = True
End Sub

Private Sub btnSelectAll_Click()


' moves all selected items from the HiddenColumns listbox to the VisibleColumns
listbox
Dim i As Integer
With Me.LabelHiddenCol
If .ListCount > 0 Then
Application.ScreenUpdating = False
For i = 0 To .ListCount - 1
Me.LabelVisibleCol.AddItem .List(i)
Next i
.Clear
Application.ScreenUpdating = True
End If
End With
End Sub

Private Sub btnDeSelectAll_Click()


' moves all selected items from the VisibleColumns listbox to the HiddenColumns
listbox

Dim i As Integer
With Me.LabelVisibleCol
If .ListCount > 0 Then
Application.ScreenUpdating = False
For i = 0 To .ListCount - 1
Me.LabelHiddenCol.AddItem .List(i)
Next i
.Clear
Application.ScreenUpdating = True
End If
End With
End Sub

Private Sub LabelHiddenCol_DblClick(ByVal Cancel As MSForms.ReturnBoolean)


btnSelect1_Click
End Sub

Private Sub LabelVisibleCol_DblClick(ByVal Cancel As MSForms.ReturnBoolean)


btnDeSelect1_Click
End Sub

Private Sub btnDown_Click()


Dim i As Integer
Dim leaveAlone As Boolean
Dim pos As Long
Dim Temp As String

pos = LabelVisibleCol.ListCount - 1

For i = LabelVisibleCol.ListCount - 1 To 0 Step -1

leaveAlone = False
If LabelVisibleCol.Selected(i) Then

If i = pos Then
leaveAlone = True
End If

pos = pos - 1
If Not leaveAlone Then
Temp = LabelVisibleCol.List(i + 1)
LabelVisibleCol.List(i + 1) = LabelVisibleCol.List(i)
LabelVisibleCol.List(i) = Temp
LabelVisibleCol.ListIndex = i + 1
LabelVisibleCol.Selected(i) = False
LabelVisibleCol.Selected(i + 1) = True
End If
End If
Next

End Sub

Private Sub btnUp_Click()


Dim i As Long
Dim leaveAlone As Boolean
Dim pos As Long
Dim Temp As String

pos = 0

For i = 0 To LabelVisibleCol.ListCount - 1
leaveAlone = False

If LabelVisibleCol.Selected(i) Then

If i = pos Then
leaveAlone = True
End If
pos = pos + 1

If leaveAlone = False Then


Temp = LabelVisibleCol.List(i - 1)
LabelVisibleCol.List(i - 1) = LabelVisibleCol.List(i)
LabelVisibleCol.List(i) = Temp
LabelVisibleCol.ListIndex = i - 1
LabelVisibleCol.Selected(i) = False
LabelVisibleCol.Selected(i - 1) = True
End If
End If
Next
End Sub

Sub ReArrange(LastRowColA As Long, LastColRow1 As Long, SheetNr As Long)


'
're-arrange current sheet to new col-postions and hide/show settings
' this according the settings retrieved from settings-array
'

'get last row and column


Dim nr_of_rows As Long, nr_of_cols As Integer, Titel_row_nr As Integer
Titel_row_nr = ListStartLine - 2
If Titel_row_nr < 2 Then Titel_row_nr = 1
nr_of_rows = LastRowColA - ListStartLine + 1
nr_of_cols = LastColRow1 - ListStartCol + 1

'read in whole sheet into an array


Dim arr_in As Variant 'MUST be variant
ReDim arr_outB(1 To nr_of_rows, 1 To nr_of_cols) As Variant
arr_in = Range(Cells(ListStartLine, ListStartCol), Cells(LastRowColA,
LastColRow1)).Value

'
' Just before writing the array to the sheet we now (re-)arrange the order of
the columns
'
Dim ColNr_old As Integer, ColNr_new As Integer
For iCol = 1 To nr_of_cols
ColNr_old = ColPos(iCol)
ColNr_new = arr_settings(HeaderLine2, iCol)

For iRow = 1 To nr_of_rows


arr_outB(iRow, ColNr_new) = arr_in(iRow, ColNr_old)
Next iRow
Next iCol

'
'write back to the sheet the array arr_outB
'
Call SetColFormat(1) 'set format correct otherwise value might get mutilated
(0011 becomes 11)
Range(Cells(ListStartLine, ListStartCol), Cells(LastRowColA,
LastColRow1)).Value = arr_outB
'Call Rounding(LastRowColA)

Dim nr_of_sheets As Long


nr_of_sheets = Sheets.Count
ReDim TotalFields(1 To nr_of_sheets, 1 To 12) As Variant

Call Layout_general(ActiveSheet, True, SheetNr)

Cells(1, 1).Select 'just select "A1" in order to get active cel to so far down

End Sub

===================================================================================
============
Rem Attribute VBA_ModuleType=VBAFormModule
Option VBASupport 1
Private Sub UserForm_activate()

If StartedFromListControl = True Then


'wait 1 sec. to give system enough time for last call which hides the panel
Application.Wait (Now + TimeValue("00:00:01")) 'wait 1 sec.

Dim remembered_activesheetname As String, remembered_activecell As String


remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address

'Turn off calculation and screenupdating to speed up the macro.


Application.ScreenUpdating = False

Dim SheetDistr_Nr As Integer


SheetDistr_Nr = Form_ListControl.ListToSheets.ListIndex
Dim SumR1 As Integer, SumR2 As Integer, SumR3 As Integer, SumR4 As Integer,
SumR5 As Integer
SumR1 = Form_ListControl.Sum1.ListIndex
SumR2 = Form_ListControl.Sum2.ListIndex
SumR3 = Form_ListControl.Sum3.ListIndex
SumR4 = Form_ListControl.Sum4.ListIndex
SumR5 = Form_ListControl.Sum5.ListIndex

Dim SortR1 As Integer, SortR2 As Integer, SortR3 As Integer


SortR1 = Form_ListControl.Sort1.ListIndex
SortR2 = Form_ListControl.Sort2.ListIndex
SortR3 = Form_ListControl.Sort3.ListIndex

arr_settings(HeaderLine8, 1) = conv_colnr_to_colname(SheetDistr_Nr)
arr_settings(HeaderLine8, 2) = conv_colnr_to_colname(SumR1)
arr_settings(HeaderLine8, 3) = conv_colnr_to_colname(SumR2)
arr_settings(HeaderLine8, 4) = conv_colnr_to_colname(SumR3)
arr_settings(HeaderLine8, 5) = conv_colnr_to_colname(SortR1)
arr_settings(HeaderLine8, 6) = conv_colnr_to_colname(SortR2)
arr_settings(HeaderLine8, 7) = conv_colnr_to_colname(SortR3)
arr_settings(HeaderLine8, 78) = conv_colnr_to_colname(SumR4)
arr_settings(HeaderLine8, 79) = conv_colnr_to_colname(SumR5)

Select Case Form_ListControl.SumAccording.ListIndex


Case "0"
arr_settings(HeaderLine8, 91) = "0"
Case "1"
arr_settings(HeaderLine8, 91) = "1"
Case "2"
arr_settings(HeaderLine8, 91) = "2"
Case "3"
arr_settings(HeaderLine8, 91) = "3"
Case Else
arr_settings(HeaderLine8, 91) = "1" ' Default
End Select

Call WriteSettings(0)

PctDone = 0 'set how much procent is done in pogress-bar


Call Progress(PctDone)
Call ListControl(SheetDistr_Nr, SumR1, SumR2, SumR3, SumR4, SumR5, SortR1,
SortR2, SortR3, LayoutSetting_just_changed)

Call Progress(1)
'wait 1 sec. to give user enough time to see that 100% is reached.
'Application.Wait (Now + TimeValue("00:00:01")) 'wait 1 sec.
Unload waitpanel

On Error Resume Next


AppActivate ("Microsoft excel")

Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select

Application.ScreenUpdating = True

End If

End Sub
Private Sub CancelButton_Click()

MsgBox "flag test1"


End Sub

=========================================================================
Rem Attribute VBA_ModuleType=VBAModule
Option VBASupport 1
Sub Macro_Main_Import()

'
'initialize
'
If NotAllowedToStartMacroFromHere(True) Then Exit Sub
StartedFromListControl = False
Call init(1)

' Define Importfile-name: same as current workbook, only without the addition
extension
Dim ThisWorkbookPath As String, ThisWorkbookName As String, Importfile As
String
ThisWorkbookPath = ThisWorkbook.Path
ThisWorkbookName = ThisWorkbook.Name
ThisWorkbookName = Left(ThisWorkbookName, Len(ThisWorkbookName) - 4) 'cut off
the extension ".xls"
Importfile = ThisWorkbookPath & "\" & ThisWorkbookName & f_extension
'check if importfile exists:
If File_Exists(Importfile) = False Then
MsgBox "Warning, Could not find file " & Importfile
Exit Sub
End If

Application.ScreenUpdating = False
'Application.Visible = False 'hide excel application, so only wait-panel is
visible

waitpanel.LabelProgress.Width = 0
Load waitpanel
waitpanel.Show vbModeless
Call Progress(0.01)

If ImportSettings(ThisWorkbookName, Importfile) = False Then


Application.ScreenUpdating = True
Unload waitpanel
Exit Sub
End If
Call Progress(0.02)

' Open Importfile as semicolon seprated file


' name is same as current excel workbook, only without the addition extension
Workbooks.OpenText Filename:=Importfile, Origin:=xlWindows,
startrow:=QueryLines + HeaderLines _
, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=True, Comma:=False _
, Space:=False, Other:=False, FieldInfo:=Array(Array(1, frm(1)), _
Array(2, frm(2)), Array(3, frm(3)), Array(4, frm(4)), Array(5, frm(5)),
Array(6, frm(6)), _
Array(7, frm(7)), Array(8, frm(8)), Array(9, frm(9)), Array(10, frm(10)),
Array(11, frm(11)), _
Array(12, frm(12)), Array(13, frm(13)), Array(14, frm(14)), Array(15,
frm(15)), Array(16, frm(16)), _
Array(17, frm(17)), Array(18, frm(18)), Array(19, frm(19)), Array(20,
frm(20)), Array(21, frm(21)), _
Array(22, frm(22)), Array(23, frm(23)), Array(24, frm(24)), Array(25,
frm(25)), Array(26, frm(26)), _
Array(27, frm(27)), Array(28, frm(28)), Array(29, frm(29)), Array(30,
frm(30)), Array(31, frm(31)), _
Array(32, frm(32)), Array(33, frm(33)), Array(34, frm(34)), Array(35,
frm(35)), Array(36, frm(36)), _
Array(37, frm(37)), Array(38, frm(38)), Array(39, frm(39)), Array(40,
frm(40)), Array(41, frm(41)), _
Array(42, frm(42)), Array(43, frm(43)), Array(44, frm(44)), Array(45,
frm(45)), Array(46, frm(46)), _
Array(47, frm(47)), Array(48, frm(48)), Array(49, frm(49)), Array(50,
frm(50)), Array(51, frm(51)), _
Array(52, frm(52)), Array(53, frm(53)), Array(54, frm(54)), Array(55,
frm(55)), Array(56, frm(56)), _
Array(57, frm(57)), Array(58, frm(58)), Array(59, frm(59)), Array(60,
frm(60)), Array(61, frm(61)), _
Array(62, frm(62)), Array(63, frm(63)), Array(64, frm(64)), Array(65,
frm(65)), Array(66, frm(66)), _
Array(67, frm(67)), Array(68, frm(68)), Array(69, frm(69)), Array(70,
frm(70)), Array(71, frm(71)), _
Array(72, frm(72)), Array(73, frm(73)), Array(74, frm(74)), Array(75,
frm(75)), Array(76, frm(76)), _
Array(77, frm(77)), Array(78, frm(78)), Array(79, frm(79)), Array(80,
frm(80)), Array(81, frm(81)), _
Array(82, frm(82)), Array(83, frm(83)), Array(84, frm(84)), Array(85,
frm(85)), Array(86, frm(86)), _
Array(87, frm(87)), Array(88, frm(88)), Array(89, frm(89)), Array(90,
frm(90))), _
DecimalSeparator:=".", ThousandsSeparator:=" "

Call Progress(0.03)

'
'Copy content of this imported excel workbook into current sheet and delete
that workbook
'
Dim Importfile_excel As String
'check if import succeed ( if succeeded then the csv-file is opened and tabname
is always the same as the filename )
If Validate_FileImport(ThisWorkbookName, Importfile_excel) = False Then
Application.ScreenUpdating = True
Unload waitpanel
Exit Sub
End If
Application.DisplayAlerts = False 'to avoid message about clipboard when
coping
Windows(Importfile_excel).Activate 'activate imported excel workbook
Cells.Select 'select whole sheet
Selection.Copy 'copy whole sheet to clipboard
Windows(ThisWorkbook.Name).Activate 'activate current workbook
If Not WorksheetExists("import") Then
Sheets.Add 'Add new sheet
ActiveSheet.Name = "import" 'Rename new sheet
End If
Sheets("import").Select 'select the sheet with the name "import"
Cells.Select 'select whole sheet
ActiveSheet.Paste 'paste content of clipboard to the sheet
Windows(Importfile_excel).Activate 'activate imported excel workbook
'
Call Progress(0.04)
Application.CutCopyMode = False 'Clear Clipboard. VERY GOOD LINE: it will
fasten up
' following SAVE/CLOSE very much (no time
instead of 2 sec)
ActiveWindow.Close SaveChanges:=0 'close imported excel workbook
Call Progress(0.05)
Application.DisplayAlerts = True 'set original value back ("True")

'
'setup sheets; distribute import sheets to the differen sheets and setup layout
'
Dim SheetDistr_Nr As Integer, SumR1 As Integer, SumR2 As Integer, SumR3 As
Integer, SumR4 As Integer
Dim SumR5 As Integer, SortR1 As Integer, SortR2 As Integer, SortR3 As Integer,
sett As String
sett = arr_settings(HeaderLine8, 1)
SheetDistr_Nr = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 2)
SumR1 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 3)
SumR2 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 4)
SumR3 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 78)
SumR4 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 79)
SumR5 = conv_to_number(sett)

sett = arr_settings(HeaderLine8, 5)
SortR1 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 6)
SortR2 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 7)
SortR3 = conv_to_number(sett)

Call ListControl(SheetDistr_Nr, SumR1, SumR2, SumR3, SumR4, SumR5, SortR1,


SortR2, SortR3, True)

Dim all_bits As String, bit1 As String, bit2 As String, bit3 As String, bit4 As
String, bit5 As String
all_bits = arr_settings(HeaderLine8, 88)
bit1 = Mid(all_bits, 1, 1)
bit2 = Mid(all_bits, 2, 1)
bit3 = Mid(all_bits, 3, 1)
bit4 = Mid(all_bits, 4, 1)
bit5 = Mid(all_bits, 5, 1)
If bit2 = "1" Then Call ExportToCSV(False) ' export to CSV (and repress
messages popping up)
If bit3 = "1" Then
If File_Exists(Importfile) = True Then
Kill Importfile 'delete sumfile, (which may also be used as indicator
that it's ready to external program)
End If
End If
If bit4 = "1" Then Call CleanUp_B(False) ' Removes N-C menu, and internal
database
Call Progress(1)
Unload waitpanel

If bit5 = "1" Then


' NEEDED (!) preperation for the following sendkey commands ( because in
batchmode it otherwise went wrong)
Application.ScreenUpdating = True
'Call CleanUp_C(1) ' Removes all macros, etc.
End If

'SAVE
Application.CutCopyMode = False 'Clear Clipboard. VERY GOOD LINE: it
will fasten up
' following SAVE/CLOSE vermy much (no
time instead of 2 sec)
ActiveWorkbook.Save
Application.CutCopyMode = True ' set value back to orginal value

If bit1 = "1" Then


If Workbooks.Count = 1 Then
Application.DisplayAlerts = False
Application.Quit
Application.DisplayAlerts = True
Else
Application.WindowState = xlMinimized ' just minimize window while
there are still other workbooks active
Application.ScreenUpdating = True
Application.Visible = True
Application.DisplayAlerts = False
ThisWorkbook.Close SaveChanges:=False
Application.DisplayAlerts = True
End If
Else
Application.WindowState = xlMaximized 'Maximize excel window
Application.ScreenUpdating = True
Application.Visible = True
End If

End Sub

Function conv_to_number(sett As String) As Integer


conv_to_number = 0
If sett = "" Or sett = "0" Then Exit Function
For iCounter = 1 To Col_ArraySize
If UCase(sett) = arr_settings(HeaderLine1, iCounter) Then
conv_to_number = iCounter
End If
Next iCounter
End Function

Function conv_colnr_to_colname(ColNr As Integer) As String


conv_colnr_to_colname = "0"
If ColNr > 0 And ColNr <= Col_ArraySize Then
conv_colnr_to_colname = arr_settings(HeaderLine1, ColNr)
End If
End Function

Sub closing(arg As String)


'clean up
Unload waitpanel
'Application.WindowState = xlMinimized 'Minimize excel window
Application.WindowState = xlMaximized 'Maxmize excel window
Application.ScreenUpdating = True
Application.Visible = True
Application.CutCopyMode = True

End Sub

'Distribute the list from sheet "import" to the different sheets,


'this distributed groups will be defined according DistrColNr
Sub SetupSheets(DistrColNr As Integer, setup_importsheet As Boolean)

'setup lautout of import sheet (much layout is copied to other sheets form
there)
If (setup_importsheet) Then Call Layout_of_import_sheet

'Distribute the list from sheet "import" to the different sheets


Call DistributeTosHeets(DistrColNr) 'according DistrColNr

'create or update custom menu


Call CreateMenu(1)

PctDone = 0.25
Call Progress(PctDone) 'set how much procent is done in pogress-bar

End Sub

Sub DistributeTosHeets(DistrColNr As Integer)


'Distribute the list from sheet "import" to the different sheets,
'this distributed groups will be defined according defined DistrColNr

'first DELETE existing SHEETS, except sheet "import" & "settings"

'un-hide sheet "import", because we only can delete the old sheets when
'there is at least one sheet left visible
Sheets("import").Visible = True

Dim WorkSh As Worksheet


For Each WorkSh In ActiveWorkbook.Worksheets
If UCase(WorkSh.Name) = "TOTAL" Then Call totalsheet_clear(1)
If (filtersheets(WorkSh.Name) = False) Then
Application.DisplayAlerts = False
WorkSh.Delete
Application.DisplayAlerts = True
End If
Next

'get last row and last column of sheet "import"


Dim LastRowColA As Long, LastColRow1 As Integer
Sheets("import").Activate
LastRowColA = last_row_nr(1, 1) 'call to function last_row_nr()
LastColRow1 = last_col_nr(1)

If (LastRowColA > 65536 - 10) Then


MsgBox "Warning: Imported material-file contains more rows then excel can
handle (65536)."
End If

If DistrColNr = 0 Then
'selected DistrColNr is 0 (= None)
Rows(2 & ":" & LastRowColA).Select
Range("A" & 2 & ":" & Column2Char(LastColRow1) & LastRowColA).Select
Selection.Copy
Sheets.Add 'Add new sheet
ActiveSheet.Name = "All" 'Rename new sheet
Range(Column2Char(ListStartCol) & ListStartLine).Select
ActiveSheet.Paste
Call Progress(0.25)
Exit Sub
End If

PctDone = 0.09
Call Progress(PctDone)

'First Sort that column in sheet "import" in order to find the unique values
Dim SortCelValue As String, SortCelValuePrev As String
Rows("2:" & LastRowColA).Select
Selection.Sort Key1:=Cells(2, DistrColNr), Order1:=xlAscending,
Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom

'scan every cell in (sorted) column 'DistrColNr' and if value changes,


'then copy that range into new sheet
Dim BeginRow As Long, endrow As Long, PctDoneTemp As Single, iCounter As Long
Dim celvalue As String, ValuePrev As String
BeginRow = 2
For iCounter = 2 To LastRowColA + 1
Sheets("import").Select
ValuePrev = celvalue 'store previous celvalue
celvalue = Cells(iCounter, DistrColNr).Value
If celvalue = "" And iCounter <> LastRowColA + 1 Then
celvalue = "empty"
End If
If ((LCase(celvalue) <> LCase(ValuePrev)) And (iCounter > 2)) Then
endrow = iCounter - 1
Range("A" & BeginRow & ":" & Column2Char(LastColRow1) & endrow).Select
Selection.Copy
If WorksheetExists(ValuePrev) Then
MsgBox ("Warning, Could not add sheet <" & ValuePrev & ">.")
Exit Sub
End If
Sheets.Add 'Add new sheet
Call RenameCurrSheet(ValuePrev) 'Rename new sheet
Range(Column2Char(ListStartCol) & ListStartLine).Select
ActiveSheet.Paste
BeginRow = iCounter
End If

'set how much procent is done in pogress-bar (Fill till 0.25 )


PctDoneTemp = PctDone + ((0.25 - PctDone) * iCounter / LastRowColA)
Call Progress(PctDoneTemp)
Next iCounter
End Sub

Private Sub RenameCurrSheet(sheet_name As String)

'get rid of strange character in sheetname which excel cannot handle when
renaming sheet

Dim i As Long
For i = 1 To Len(sheet_name)
Select Case Mid$(sheet_name, i, 1)
Case "?"
Mid$(sheet_name, i, 1) = "."
Case "/"
Mid$(sheet_name, i, 1) = "."
Case "\"
Mid$(sheet_name, i, 1) = "."
Case "*"
Mid$(sheet_name, i, 1) = "."
Case "["
Mid$(sheet_name, i, 1) = "."
Case "]"
Mid$(sheet_name, i, 1) = "."
Case Else

End Select
Next

If Len(sheet_name) > 31 Then sheet_name = Left$(sheet_name, 30) + "~"

If WorksheetExists(sheet_name) Then
MsgBox ("Warning, Could not add sheet <" & sheet_name & "> because this
sheet already exists.")
sheet_name = sheet_name & "_WARNING_"
End If
ActiveSheet.Name = sheet_name 'Rename new sheet
End Sub

Private Sub Layout_of_import_sheet()


'arrange layout of the sheet, like borders. Here only the sheet named "import" will
be set up
' Because later when copying from this sheet to another sheet then the layout is
copied along

'get last row and last column


Dim LastRowColA As Long, LastColRow1 As Long
LastRowColA = last_row_nr(1, 1) 'call to function last_row_nr()
LastColRow1 = last_col_nr(1)

If (LastColRow1 < 3) Then


MsgBox ("Warning, expected a bit more columns then only " & LastColRow1 _
& " , in sheet:" & sheetname & "aborting ,layout setup in this sheet.")
'When there is only 2 column then excel give error at 'xlInsideVertical'
Exit Sub
End If

Call Progress(0.06)
If UCase(arr_settings(HeaderLine8, 8)) <> "LAYOUT2" Then
'
' make boxlines around all cells
'
' Layout whole range: Borders (thin thickness)
Range(Cells(1, 1), Cells(LastRowColA, LastColRow1)).Select
Call NormalBorder(1)

'
' Layout rows: make left & right -borders of every row thick
'
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With

Call Progress(0.07)

'thick outer border:


'OuterBorderThick

'add sort-buttons in title-row


For Each cel In Range(Cells(1, 1), Cells(1, LastColRow1))
ActiveSheet.Buttons.Add(0, 0, 0, 0).Select
With Selection
.Top = cel.Top
.Left = cel.Left
.Height = cel.Height
.Width = cel.Width
.Text = cel.Value
.Font.Bold = True
.OnAction = "'MacroSort """ & cel.Address & """'"

End With
Next cel

End If

'
' Layout title row: make bold text, filling, and thick outer Border
'
Range(Cells(1, 1), Cells(1, LastColRow1)).Select
Selection.RowHeight = 35
'bold text:
For Each cel In Selection
cel.Font.Bold = True
Next cel
' filling:
With Selection.Interior
.ColorIndex = 15 'light-gray
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With

'Freeze titel-row when scrolling:


ActiveWindow.splitrow = 1
ActiveWindow.FreezePanes = True

Call Progress(0.08)

End Sub

Sub Layout_general(sheetname As Worksheet, quick As Boolean, SheetNr As Long)


'arrange layout of the sheet, like borders,

'get last row and column


Dim LastRowColA As Long, LastColRow1 As Long, nr_of_rows As Long, nr_of_cols As
Integer
Dim layoutsheet As String, hidetitelrow As Boolean
Dim columnwidth_via_layoutsheet As Boolean

LastRowColA = last_row_nr(ListStartLine, ListStartCol) 'call to function


last_row_nr()
LastColRow1 = last_col_nr(ListStartCol) 'call to function last_col_nr()
nr_of_rows = LastRowColA - ListStartLine + 1
nr_of_cols = LastColRow1 - ListStartCol + 1

'
'Read settings
'
layoutsheet = UCase(arr_settings(HeaderLine8, 8))
If LCase(arr_settings(HeaderLine8, 11)) = "columnwidth_via_layoutsheet" Then
columnwidth_via_layoutsheet = True
Else
columnwidth_via_layoutsheet = False
End If

If LCase(arr_settings(HeaderLine8, 13)) = "hidetitelrow" Then


hidetitelrow = True
Else
hidetitelrow = False
End If

Dim col_nr As Integer, titel As String, Titel_row_nr As Integer


ReDim Titel_row(1 To 1, 1 To nr_of_cols) As Variant
For nCounter = 1 To Col_ArraySize
titel = arr_settings(HeaderLine10, nCounter)
col_nr = arr_settings(HeaderLine2, nCounter) 'get column position
Titel_row(1, col_nr) = titel
Next nCounter
Titel_row_nr = SheetHeaderLines + 1

'
'copy headerlines of the layoutsheet to current sheet (content and width)
'
If WorksheetExists(layoutsheet) Then
Sheets(layoutsheet).Visible = True
Call sheet_sel(layoutsheet) 'select the sheet with that name
If columnwidth_via_layoutsheet = True Then
Dim iCounter As Long
ReDim c_width(1 To LastColRow1) As Integer
For iCounter = 1 To LastColRow1
c_width(iCounter) = Columns(iCounter).ColumnWidth
Next iCounter
End If

'selecting the rows and copy it


Application.DisplayAlerts = False 'to avoid message about clipboard
when coping
If SheetHeaderLines > 0 Then Rows(1 & ":" & SheetHeaderLines).Copy
Sheets(sheetname.Name).Activate
Range("A1").Select
If SheetHeaderLines > 0 Then ActiveSheet.Paste 'paste content of
clipboard to the sheet
Sheets(sheetname.Name).Activate
Application.DisplayAlerts = False 'to avoid message about clipboard when
coping
If SheetHeaderLines > 0 Then Call
fill_environment_values_in_layout(LastColRow1)

If columnwidth_via_layoutsheet = True Then


For iCounter = 1 To LastColRow1
Columns(iCounter).ColumnWidth = c_width(iCounter)
Next iCounter
End If
End If

'
'Titel-labels: description
'
Range(Cells(Titel_row_nr, ListStartCol), Cells(Titel_row_nr,
LastColRow1)).Value = Titel_row

'
' Titel-labels: make bold text, filling, and thick outer Border
'
Range(Cells(Titel_row_nr, ListStartCol), Cells(Titel_row_nr,
LastColRow1)).Select
Selection.RowHeight = 35
'bold text:
For Each cel In Selection
cel.Font.Bold = True
Next cel

If hidetitelrow = False Then


'so skip this when Titelrow is hidden anyway, because the outerline messes
up
'then bottom-line of the row directly above it
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With

OuterBorderThick

End If

'Titel row: pattern filling:


With Selection.Interior
.ColorIndex = 36 'light-yellow
.ColorIndex = 15 'light-gray
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With

'Titel-row: HIDE
If hidetitelrow = True Then
Rows(Titel_row_nr).Select
Selection.EntireRow.Hidden = True
End If

'
' Select layoutsheet additional sheet definitions
'
Select Case layoutsheet
Case "LAYOUT1"
Call Layout1(sheetname, LastRowColA, LastColRow1, quick) 'default
layout

Case "LAYOUT2"
Call Layout2(sheetname, LastRowColA, LastColRow1, quick)

Case Else
Call Layout1(sheetname, LastRowColA, LastColRow1, quick) 'default
layout
End Select

Call set_named_cell(sheetname)

'
' Add total fields (like total mass total length, total COG)
' (also activates that sheet
'
Call addtotalfields(LastRowColA, LastColRow1, SheetNr)

'
' Column width
'
If columnwidth_via_layoutsheet = False Then
Call Columns_Width(Titel_row_nr, LastRowColA, LastColRow1)
End If

'
'DECIMALS presenting ( and also assign formula )
'
Call Rounding(LastRowColA)

'
'HIDE / SHOW the columns
'
Call Columns_HideShow(LastRowColA, LastColRow1)

If quick = False Then


'Freeze titelrow. In oder to leave the titels presented when scrolling down
Dim splitrow As Integer
splitrow = ListStartLine - 2
If splitrow < 1 Then splitrow = 1
ActiveWindow.splitrow = splitrow
ActiveWindow.FreezePanes = True
End If

'Fill_counter_column
Dim counter As Long, sett As String, cc As Integer
sett = arr_settings(HeaderLine8, 14)
counter_col_nr = conv_to_number(sett)
If counter_col_nr > 0 Then
cc = arr_settings(HeaderLine2, counter_col_nr) 'get column position
cc = cc + ListStartCol - 1
counter = 0
For rr = ListStartLine To LastRowColA
counter = counter + 1
Cells(rr, cc).Value = counter
Next rr
End If

Range("A1").Select

End Sub

Sub Layout1(sheetname As Worksheet, LastRowColA As Long, LastColRow1 As Long, quick


As Boolean)

Dim nr_of_rows As Long, nr_of_cols As Integer, Titel_row_nr As Integer


nr_of_rows = LastRowColA - ListStartLine + 1
nr_of_cols = LastColRow1 - ListStartCol + 1
Titel_row_nr = ListStartLine - 2
If Titel_row_nr < 2 Then Titel_row_nr = 1

'retrieve Projname from excel-filename (so, after "_" and without extension)
Dim projectname As String, UnderScorePosition As Integer, pos As Integer
projectname = ThisWorkbook.Name
UnderScorePosition = InStr(1, projectname, "_") 'get postion of "_"
If UnderScorePosition > 0 Then
pos = UnderScorePosition + 1 'begin after "_"
projectname = Mid(projectname, pos, Len(projectname) - (pos - 1) - 4)
End If

sheet_leftheader = arr_settings(HeaderLine8, 46)


sheet_centerheader = arr_settings(HeaderLine8, 47)
sheet_rightheader = arr_settings(HeaderLine8, 48)
sheet_leftfooter = arr_settings(HeaderLine8, 49)
sheet_centerfooter = arr_settings(HeaderLine8, 50)
sheet_rightfooter = arr_settings(HeaderLine8, 51)

If quick = False Then


With ActiveSheet.PageSetup
.PrintTitleRows = ActiveSheet.Rows(Titel_row_nr).Address
.Orientation = xlLandscape
.PrintHeadings = False
.LeftHeader = sheet_leftheader
.CenterHeader = sheet_centerheader
.RightHeader = sheet_rightheader
.LeftFooter = sheet_leftfooter
.CenterFooter = sheet_centerfooter
.RightFooter = sheet_rightfooter
If arr_settings(HeaderLine8, 42) = "1" Then
.FitToPagesWide = 1
.Zoom = False
.FitToPagesTall = False
End If
End With
End If

'thick outer border:


Range(Cells(ListStartLine, ListStartCol), Cells(LastRowColA,
LastColRow1)).Select
OuterBorderThick

End Sub
Sub Layout2(sheetname As Worksheet, LastRowColA As Long, LastColRow1 As Long, quick
As Boolean)

Dim layoutsheet As String, Titel_row_nr As Integer


Dim nr_of_rows As Long, nr_of_cols As Integer
nr_of_rows = LastRowColA - ListStartLine + 1
nr_of_cols = LastColRow1 - ListStartCol + 1

If quick = True Then Exit Sub

' Empty row: filling:


Titel_row_nr = SheetHeaderLines + 1
Range(Cells(Titel_row_nr + 1, 1), Cells(Titel_row_nr + 1, LastColRow1 +
1)).Select
With Selection.Interior
.ColorIndex = 15 'light-gray
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With

'
' BORDERS: Outer border is double line and inner cells normal line
'
Range(Cells(ListStartLine, ListStartCol), Cells(LastRowColA,
LastColRow1)).Select
Call InnerNormal_OuterDouble_Border(1)

'
'BORDERS: column 16 should be total empty only left and right line is double
line
'
Dim sel_col_nr As Integer
sel_col_nr = ListStartCol + 16 - 1
Range(Cells(ListStartLine, sel_col_nr), Cells(LastRowColA, sel_col_nr)).Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlDouble
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
Selection.Borders(xlEdgeTop).LineStyle = xlNone
Selection.Borders(xlEdgeBottom).LineStyle = xlNone
With Selection.Borders(xlEdgeRight)
.LineStyle = xlDouble
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
'
'BORDERS: column 17 should be total empty only left and right line is double
line
'
sel_col_nr = ListStartCol + 17 - 1
Range(Cells(ListStartLine, sel_col_nr), Cells(LastRowColA, sel_col_nr)).Select
With Selection.Borders(xlEdgeRight)
.LineStyle = xlDouble
.Weight = xlThick
.ColorIndex = xlAutomatic
End With

'printpreview
With ActiveSheet.PageSetup
.Orientation = xlLandscape
.Zoom = 43
.LeftMargin = Application.InchesToPoints(0.3)
.RightMargin = Application.InchesToPoints(0.3)
End With

'zoom
ActiveWindow.Zoom = 75

End Sub

Private Sub OuterBorderThick()


Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
End Sub

Sub NormalBorder(arg As Integer)


Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With

End Sub

Sub InnerNormal_OuterDouble_Border(arg As String)


Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlDouble
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlDouble
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlDouble
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlDouble
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
End Sub

Function ImportSettings(ThisWorkbookName As String, Importfile As String) As


Boolean

' Open Importfile and read the semicolon seprated file,


'only the header (which are the first few lines containing the settings)
'
'There are 2 parts:
'- the query-lines, they should be all in the first column only (nr of lines is
unknown)
' these will be read just by opening the file
'- the headerlines, a fix number of lines will a lot of columns (seperated by
";")
'
ImportSettings = False
ReDim query_lines_firstCol(1 To QueryLinesMax, 1 To 1) As Variant
Dim FileNum As Integer, tLine As String, line_nr As Integer, stop_reading As
Boolean
FileNum = FreeFile() ' next file number
Open Importfile For Input Access Read Shared As #FileNum ' open the file for
reading
stop_reading = False
line_nr = 0
Do While Not EOF(FileNum) And stop_reading = False
Line Input #FileNum, tLine ' read a line from the text file
If Left(tLine, 4) = "COL_" Then
stop_reading = True
Else
line_nr = line_nr + 1
query_lines_firstCol(line_nr, 1) = tLine
End If
Loop ' until the last line is read
QueryLines = line_nr
Close #FileNum ' close the file

Workbooks.OpenText Filename:=Importfile, Origin:=xlMSDOS, startrow:=QueryLines


+ 1 _
, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=True, Comma:=False _
, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 2), Array(2, 2), _
Array(3, 2), Array(4, 2), Array(5, 2), Array(6, 2), Array(7, 2), Array(8,
2), Array(9, 2), _
Array(10, 2), Array(11, 2), Array(12, 2), Array(13, 2), Array(14, 2),
Array(15, 2), _
Array(16, 2), Array(17, 2), Array(18, 2), Array(19, 2), Array(20, 2),
Array(21, 2), _
Array(22, 2), Array(23, 2), Array(24, 2), Array(25, 2), Array(26, 2),
Array(27, 2), _
Array(28, 2), Array(29, 2), Array(30, 2), Array(31, 2), Array(32, 2),
Array(33, 2), _
Array(34, 2), Array(35, 2), Array(36, 2), Array(37, 2), Array(38, 2),
Array(39, 2), _
Array(40, 2), Array(41, 2), Array(42, 2), Array(43, 2), Array(44, 2),
Array(45, 2), _
Array(46, 2), Array(47, 2), Array(48, 2), Array(49, 2), Array(50, 2),
Array(51, 2), _
Array(52, 2), Array(53, 2), Array(54, 2), Array(55, 2), Array(56, 2),
Array(57, 2), _
Array(58, 2), Array(59, 2), Array(60, 2), Array(61, 2), Array(62, 2),
Array(63, 2), _
Array(64, 2), Array(65, 2), Array(66, 2), Array(67, 2), Array(68, 2),
Array(69, 2), _
Array(70, 2), Array(71, 2), Array(72, 2), Array(73, 2), Array(74, 2),
Array(75, 2), _
Array(76, 2), Array(77, 2), Array(78, 2), Array(79, 2), Array(80, 2),
Array(81, 2), _
Array(82, 2), Array(83, 2), Array(84, 2), Array(85, 2), Array(86, 2),
Array(87, 2), _
Array(88, 2), Array(89, 2), Array(90, 2)), _
DecimalSeparator:=".", ThousandsSeparator:=" "

'
'Copy first lines of this imported excelWorkbook into curr sheet,& delete that
workbook
'
Dim Importfile_excel As String
'check if import succeed ( if succeeded then the csv-file is opened and tabname
is always the same as the filename )
If Validate_FileImport(ThisWorkbookName, Importfile_excel) = False Then Exit
Function

Application.DisplayAlerts = False 'to avoid message about clipboard when


coping
Windows(Importfile_excel).Activate 'activate imported excel workbook
Rows("1:" & HeaderLines).Select 'select the header (which is the first
few lines)
Selection.Copy 'copy whole sheet to clipboard
Windows(ThisWorkbook.Name).Activate 'activate current workbook
If Not WorksheetExists("settings") Then
Sheets.Add 'Add new sheet
ActiveSheet.Name = "settings" 'Rename new sheet
End If
Sheets("settings").Select 'select the sheet with the name
"settings"
Rows(QueryLines + 1 & ":" & QueryLines + HeaderLines).Select
ActiveSheet.Paste 'paste content of clipboard to the sheet

'also write Querylines to the settings-sheet


Range(Cells(1, 1), Cells(QueryLines, 1)).Value = query_lines_firstCol

Windows(Importfile_excel).Activate 'activate imported excel workbook


Application.CutCopyMode = False 'Clear Clipboard. VERY GOOD LINE: it will
fasten up
' following SAVE/CLOSE vermy much (no
time instead of 2 sec)

ActiveWindow.Close SaveChanges:=0 'close imported excel workbook


Application.DisplayAlerts = True 'set original value back ("True")

Call ReadSettings(0)
ImportSettings = True
End Function

Sub ReadSettings(SwitchBackToSheet As String)

If Not WorksheetExists("settings") Then


Exit Sub
End If

If SwitchBackToSheet = "1" Then


Dim remembered_activesheetname As String, remembered_activecell As String
remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address
Application.ScreenUpdating = False
End If

Sheets("settings").Visible = True
Sheets("settings").Select

Call get_number_of_query_lines(1)

'read in whole settings-sheet into an array


'Dim arr_settings As Variant 'MUST be variant (is already declared as public)
ReDim arr_settings(1 To HeaderLines, 1 To Col_ArraySize) As Variant
arr_settings = Range(Cells(QueryLines + 1, 1), Cells(QueryLines + HeaderLines,
Col_ArraySize)).Value

Dim default_desc As String, cust_desc As String, counter_empty As Integer


counter_empty = 0
For iCounter = 1 To Col_ArraySize
cust_desc = arr_settings(HeaderLine10, iCounter)
default_desc = arr_settings(HeaderLine11, iCounter)
If Trim(cust_desc) = "" Then
cust_desc = default_desc
End If
'stil empty? then fill it with "empty__<number>"
If Trim(cust_desc) = "" Then
counter_empty = counter_empty + 1
cust_desc = " < empty__" & counter_empty & " >"
End If
' put back to array:
arr_settings(HeaderLine10, iCounter) = cust_desc
Next iCounter

'only for compat reason add new columns: (because they migh miss when
rrp-file is form old version)
If Trim(arr_settings(HeaderLine1, COL_CUST41)) = "" Then
arr_settings(HeaderLine1, COL_CUST41) = "COL_CUST41"
arr_settings(HeaderLine2, COL_CUST41) = first_free_pos()
arr_settings(HeaderLine3, COL_CUST41) = "HIDE"
arr_settings(HeaderLine4, COL_CUST41) = "string"
End If
If Trim(arr_settings(HeaderLine1, COL_CUST42)) = "" Then
arr_settings(HeaderLine1, COL_CUST42) = "COL_CUST42"
arr_settings(HeaderLine2, COL_CUST42) = first_free_pos()
arr_settings(HeaderLine3, COL_CUST42) = "HIDE"
arr_settings(HeaderLine4, COL_CUST42) = "string"
End If
If Trim(arr_settings(HeaderLine1, COL_OBIREF)) = "" Then
arr_settings(HeaderLine1, COL_OBIREF) = "COL_OBIREF"
arr_settings(HeaderLine2, COL_OBIREF) = first_free_pos()
arr_settings(HeaderLine3, COL_OBIREF) = "HIDE"
arr_settings(HeaderLine4, COL_OBIREF) = "string"
End If

'read layout settings


Dim read_nr1 As Integer, read_nr2 As Integer
read_nr1 = arr_settings(HeaderLine8, 9)
read_nr2 = arr_settings(HeaderLine8, 10)
Call get_SheetHeaderLines(read_nr1, read_nr2)
Sheets("settings").Select
ListStartLine = SheetHeaderLines + 3 ' begin-row of the list-area
ListStartCol = SheetHeaderColumns + 1 ' begin-column of the list-area

'write desc (and alos headerlines) back to settings sheet


Range(Cells(QueryLines + 1, 1), Cells(QueryLines + HeaderLines,
Col_ArraySize)).Value = arr_settings

For iCounter = 1 To Col_ArraySize


Select Case Trim(arr_settings(HeaderLine1, iCounter))
Case "COL_CAT"
COL_CAT = iCounter
Case "COL_PLI"
COL_PLI = iCounter
Case "COL_SPN"
COL_SPN = iCounter
Case "COL_SYS"
COL_SYS = iCounter
Case "COL_DE"
COL_DE = iCounter
Case "COL_DD"
COL_DD = iCounter
Case "COL_FII"
COL_FII = iCounter
Case "COL_ART"
COL_ART = iCounter
Case "COL_VPO"
COL_VPO = iCounter
Case "COL_BPL"
COL_BPL = iCounter
Case "COL_LEN"
COL_LEN = iCounter
Case "COL_QTY"
COL_QTY = iCounter
Case "COL_GT"
COL_GT = iCounter
Case "COL_MAS"
COL_MAS = iCounter
Case "COL_CGX"
COL_CGX = iCounter
Case "COL_CGY"
COL_CGY = iCounter
Case "COL_CGZ"
COL_CGZ = iCounter
Case "COL_CONM"
COL_CONM = iCounter
Case "COL_CONX"
COL_CONX = iCounter
Case "COL_CONY"
COL_CONY = iCounter
Case "COL_CONZ"
COL_CONZ = iCounter
Case "COL_FLUID"
COL_FLUID = iCounter
Case "COL_CONV"
COL_CONV = iCounter
Case "COL_TOTM"
COL_TOTM = iCounter
Case "COL_TOTX"
COL_TOTX = iCounter
Case "COL_TOTY"
COL_TOTY = iCounter
Case "COL_TOTX"
COL_TOTX = iCounter
Case "COL_TOTY"
COL_TOTY = iCounter
Case "COL_TOTZ"
COL_TOTZ = iCounter
Case "COL_OBI"
COL_OBI = iCounter
Case "COL_PID"
COL_PID = iCounter
Case "COL_CORP"
COL_CORP = iCounter
Case "COL_DIMT"
COL_DIMT = iCounter
Case "COL_SLAVE"
COL_SLAVE = iCounter
Case "COL_MAT"
COL_MAT = iCounter
Case "COL_SPC"
COL_SPC = iCounter
Case "COL_CMD"
COL_CMD = iCounter
Case "COL_NAM"
COL_NAM = iCounter
Case "COL_LOX"
COL_LOX = iCounter
Case "COL_LOY"
COL_LOY = iCounter
Case "COL_LOZ"
COL_LOZ = iCounter
Case "COL_HUL"
COL_HUL = iCounter
Case "COL_MTH"
COL_MTH = iCounter
Case "COL_SCO"
COL_SCO = iCounter
Case "COL_UNIT"
COL_UNIT = iCounter
Case "COL_IDN"
COL_IDN = iCounter
Case "COL_MOT"
COL_MOT = iCounter
Case "COL_SPO"
COL_SPO = iCounter
Case "COL_BLK"
COL_BLK = iCounter
Case "COL_IPO"
COL_IPO = iCounter
Case "COL_CUST1"
COL_CUST1 = iCounter
Case "COL_CUST2"
COL_CUST2 = iCounter
Case "COL_CUST3"
COL_CUST3 = iCounter
Case "COL_CUST4"
COL_CUST4 = iCounter
Case "COL_CUST5"
COL_CUST5 = iCounter
Case "COL_CUST6"
COL_CUST6 = iCounter
Case "COL_CUST7"
COL_CUST7 = iCounter
Case "COL_CUST8"
COL_CUST8 = iCounter
Case "COL_CUST9"
COL_CUST9 = iCounter
Case "COL_CUST10"
COL_CUST10 = iCounter
Case "COL_CUST11"
COL_CUST11 = iCounter
Case "COL_CUST12"
COL_CUST12 = iCounter
Case "COL_CUST13"
COL_CUST13 = iCounter
Case "COL_CUST14"
COL_CUST14 = iCounter
Case "COL_CUST15"
COL_CUST15 = iCounter
Case "COL_CUST16"
COL_CUST16 = iCounter
Case "COL_CUST17"
COL_CUST17 = iCounter
Case "COL_CUST18"
COL_CUST18 = iCounter
Case "COL_CUST19"
COL_CUST19 = iCounter
Case "COL_CUST20"
COL_CUST20 = iCounter
Case "COL_CUST21"
COL_CUST21 = iCounter
Case "COL_CUST22"
COL_CUST22 = iCounter
Case "COL_CUST23"
COL_CUST23 = iCounter
Case "COL_CUST24"
COL_CUST24 = iCounter
Case "COL_CUST25"
COL_CUST25 = iCounter
Case "COL_CUST26"
COL_CUST26 = iCounter
Case "COL_CUST27"
COL_CUST27 = iCounter
Case "COL_CUST28"
COL_CUST28 = iCounter
Case "COL_CUST29"
COL_CUST29 = iCounter
Case "COL_CUST30"
COL_CUST30 = iCounter
Case "COL_CUST31"
COL_CUST31 = iCounter
Case "COL_CUST32"
COL_CUST32 = iCounter
Case "COL_CUST33"
COL_CUST33 = iCounter
Case "COL_CUST34"
COL_CUST34 = iCounter
Case "COL_CUST35"
COL_CUST35 = iCounter
Case "COL_CUST36"
COL_CUST36 = iCounter
Case "COL_CUST37"
COL_CUST37 = iCounter
Case "COL_CUST38"
COL_CUST38 = iCounter
Case "COL_CUST39"
COL_CUST39 = iCounter
Case "COL_CUST40"
COL_CUST40 = iCounter
Case "COL_CUST41"
COL_CUST41 = iCounter
Case "COL_CUST42"
COL_CUST42 = iCounter
Case "COL_OBIREF"
COL_OBIREF = iCounter
Case ""
Case "COL_EMP3" ' for compatibilly reason with older versions, June
2009
COL_IPO = iCounter
Case "COL_EMP2" ' for compatibilly reason with older versions, Jan
2010
COL_BLK = iCounter
Case "COL_EMP1" ' for compatibilly reason with older versions, Jan
2010
COL_SPO = iCounter
Case Else
MsgBox "unknown COLUMN found in header: <" &
arr_settings(HeaderLine1, iCounter) & "> col=" & iCounter
End Select
Next iCounter

' Read the FORMAT-setting of the columns and store it in a public array
Call GetColFormat(1)
Sheets("settings").Visible = False

If SwitchBackToSheet = "1" Then


Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select
Application.ScreenUpdating = True
End If

End Sub
Sub WriteSettings(SwitchBackToSheet As String)
If Not WorksheetExists("settings") Then
Exit Sub
End If

If SwitchBackToSheet = "1" Then


Dim remembered_activesheetname As String, remembered_activecell As String
remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address
Application.ScreenUpdating = False
End If

Dim layout As String


Dim cellvalue As String, EnvStartPosition As Integer, EnvEndPosition As
Integer, env As String, changed As Boolean
Dim arr_header As Variant 'MUST be variant
layout = arr_settings(HeaderLine8, 8)
If WorksheetExists(layout) And SheetHeaderLines > 0 And layout = "ff
uitgeschakeld door jtk, under proces" Then
Sheets(layout).Visible = True
Sheets(layout).Select
arr_header = Range(Cells(1, 1), Cells(SheetHeaderLines, LastColRow1)).Value
'LastColRow1 is NOT known ! ERROR

For iCol = 1 To 50
For iRow = 1 To SheetHeaderLines
EnvStartPosition = InStr(cellvalue, "$") 'get postion of "$"
If EnvStartPosition > 0 Then
EnvEndPosition = InStr(EnvStartPosition, cellvalue, " ") 'get
postion of space
If EnvEndPosition = 0 Then EnvEndPosition = Len(cellvalue)
env = Mid(cellvalue, EnvStartPosition, EnvEndPosition -
EnvStartPosition)
End If
Next iRow
Next iCol
Sheets(layout).Visible = False
End If

Sheets("settings").Visible = True
Sheets("settings").Select

'read in whole settings-sheet into an array


'Dim arr_settings As Variant 'MUST be variant (is already declared as public)

' Do not write the description: < empty_xx >


ReDim arr_headerlin10_tmp(1 To Col_ArraySize) As Variant
For nn = 1 To Col_ArraySize
arr_headerlin10_tmp(nn) = arr_settings(HeaderLine10, nn)
If Left(arr_settings(HeaderLine10, nn), 9) = " < empty_" Then
arr_settings(HeaderLine10, nn) = ""
End If
Next nn

'Write headerlines from array to the cells of the settings-sheet


Range(Cells(QueryLines + 1, 1), Cells(QueryLines + HeaderLines,
Col_ArraySize)).Value = arr_settings

Sheets("settings").Visible = False
If SwitchBackToSheet = "1" Then
Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select
Application.ScreenUpdating = True
End If

End Sub

Function WorksheetExists(wksName As String) As Boolean


On Error Resume Next
WorksheetExists = CBool(Len(Worksheets(wksName).Name) > 0)
On Error GoTo 0 ' set back to the default error handling in VB
End Function

Sub MacroSort(Celladdress As String)


Application.ScreenUpdating = False

'get last row and last column


Dim LastRowColA As Long, LastColRow1 As Long
LastRowColA = last_row_nr(ListStartLine, ListStartCol) 'call to function
last_row_nr()

'Sort according CurrentColumn


Rows(ListStartLine & ":" & LastRowColA).Select
Selection.Sort Key1:=Range(Celladdress), Order1:=xlAscending, Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom

'activate current cell


Range(Celladdress).Activate

Application.ScreenUpdating = True
End Sub
Sub PresentDecimals(SelColumn As Integer, LastRowColA As Long, NrOfDecimals As
Integer)
Range(Cells(ListStartLine, SelColumn), Cells(LastRowColA, SelColumn)).Select
If NrOfDecimals = 0 Then Selection.NumberFormat = "0"
If NrOfDecimals = 1 Then Selection.NumberFormat = "0.0"
If NrOfDecimals = 2 Then Selection.NumberFormat = "0.00"
If NrOfDecimals = 3 Then Selection.NumberFormat = "0.000"
End Sub

Function Column2Char(ColumnNumber As Integer) As String


If ColumnNumber > 26 Then

' 1st character: Subtract 1 to map the characters to 0-25,


' but you don't have to remap back to 1-26
' after the 'Int' operation since columns
' 1-26 have no prefix letter

' 2nd character: Subtract 1 to map the characters to 0-25,


' but then must remap back to 1-26 after
' the 'Mod' operation by adding 1 back in
' (included in the '65')

Column2Char = Chr(Int((ColumnNumber - 1) / 26) + 64) & _


Chr(((ColumnNumber - 1) Mod 26) + 65)
Else
' Columns A-Z
Column2Char = Chr(ColumnNumber + 64)
End If
End Function

Sub GetColFormat(arg As String)


'
' Read the FORMAT-setting of the columns and store it in a public array
'
For iCounter = 1 To Col_ArraySize
read_frm = arr_settings(HeaderLine4, iCounter)
If arr_settings(HeaderLine1, iCounter) = "COL_QTY" Then read_frm =
"float0PCS" 'automatic fix for old bug
read_frm = LCase(Left(read_frm, 4))
Select Case Trim(LCase(read_frm))
Case "stri", ""
frm(iCounter) = 2 'means text (string)
Case "floa" 'float
frm(iCounter) = 1 'means general
Case "date" 'date
frm(iCounter) = 5 'means YMD date
Case "form" 'formula
frm(iCounter) = 1 'means general
Case Else
MsgBox "unknown Format found in header: <" &
arr_settings(HeaderLine4, iCounter) & " > col = " & iCounter
frm(iCounter) = 2 'means text
End Select
Next iCounter

End Sub

Sub SetColFormat(arg As String)


'
' Set the FORMAT of the columns, these Format-settings are read from a public
array
'
Dim col_nr As Integer
For iCounter = 1 To Col_ArraySize
col_nr = arr_settings(HeaderLine2, iCounter) 'get column position
col_nr = col_nr + ListStartCol - 1
Select Case frm(iCounter)
Case 1 'means Format 'general'
Columns(col_nr).NumberFormat = "General"
Case 2 'means text (string)
Columns(col_nr).NumberFormat = "@"
Case 5 'means YMD date
Columns(col_nr).NumberFormat = "yyyy/mm/dd"
Case Else
Columns(col_nr).NumberFormat = "General"
End Select
Next iCounter

End Sub

Sub Rounding(LastRowColA As Long)

'
'DECIMALS presenting ( and also call to assign formula)
'
Dim col_nr As Integer, declaration As String, decimals As String, col_nr_unit
As Integer
Dim celformat As String, row As Long, unit As String, pcs As String, TheFormula
As String

For iCounter = 1 To Col_ArraySize


declaration = arr_settings(HeaderLine4, iCounter)
If Left(declaration, 5) = "float" Then
decimals = Mid$(declaration, 6, 1)
col_nr = arr_settings(HeaderLine2, iCounter) 'get column position
col_nr = col_nr + ListStartCol - 1
If decimals = "0" Then Call PresentDecimals(col_nr, LastRowColA, 0)
If decimals = "1" Then Call PresentDecimals(col_nr, LastRowColA, 1)
If decimals = "2" Then Call PresentDecimals(col_nr, LastRowColA, 2)
If decimals = "3" Then Call PresentDecimals(col_nr, LastRowColA, 3)

pcs = UCase(Mid$(declaration, 7, 3))


If pcs = "PCS" Then
col_nr_unit = arr_settings(HeaderLine2, COL_UNIT) 'get column
position of COL_UNIT
col_nr_unit = col_nr_unit + ListStartCol - 1
For row = ListStartLine To LastRowColA
unit = UCase(Cells(row, col_nr_unit).Value)
If unit = "PCS" Then
Cells(row, col_nr).NumberFormat = "0"
End If
Next row
End If

End If
If declaration = "formula" Then
col_nr = arr_settings(HeaderLine2, iCounter) 'get column position
col_nr = col_nr + ListStartCol - 1
TheFormula = "=" & arr_settings(HeaderLine5, iCounter)
TheFormula = Replace(TheFormula, "[R]", ListStartLine)
If TheFormula <> "" Then Call AssignFormula(col_nr, LastRowColA,
TheFormula)
End If
Next iCounter

End Sub

Sub AssignFormula(SelColumn As Integer, LastRowColA As Long, TheFormula As String)


On Error GoTo ErrorHandlingLabel
Range(Cells(ListStartLine, SelColumn), Cells(LastRowColA, SelColumn)).Select
Range(Cells(ListStartLine, SelColumn), Cells(LastRowColA, SelColumn)).Formula =
TheFormula
On Error GoTo 0 ' set back to the default error handling in VB
Exit Sub

ErrorHandlingLabel:
MsgBox "Warning the following formula has a problem (so check via report
control the formula) : " & TheFormula
On Error GoTo 0 ' set back to the default error handling in VB
End Sub

Sub Columns_HideShow(LastRowColA As Long, LastColRow1 As Long)


'
' Hide or Show all columns
'
For iCounter = 1 To Col_ArraySize
col_nr = arr_settings(HeaderLine2, iCounter) 'get column position
col_nr = col_nr + ListStartCol - 1
If arr_settings(HeaderLine3, iCounter) = "SHOW" Then
'un-hide (Show) the columns
Columns(col_nr).EntireColumn.Hidden = False
Else
'hide the columns
Columns(col_nr).EntireColumn.Hidden = True
End If
Next iCounter
End Sub

Sub Columns_Width(Titel_row_nr As Integer, LastRowColA As Long, LastColRow1 As


Long)
'
' Column width
'
'autofit column width
Rows(Titel_row_nr & ":" & LastRowColA + 7).Select '+7 to include the total-
fields
Selection.Columns.AutoFit

Dim Format_sett As String, width_str As String, MinMax As String


For iCounter = 1 To Col_ArraySize
col_nr = arr_settings(HeaderLine2, iCounter) 'get column position
col_nr = col_nr + ListStartCol - 1
Format_sett = Trim(UCase(arr_settings(HeaderLine6, iCounter)))

If Format_sett <> "AUTOFIT" And Format_sett <> "" Then


'
' Value could a number only or added with MIN or MAX, examples:
' 12MIN
' 15
' 30MAX
'
Pos_of_M = InStr(Format_sett, "M")
If Pos_of_M > 0 Then
width_str = Left(Format_sett, Pos_of_M - 1)
MinMax = Mid$(Format_sett, Pos_of_M, 3)
Else
width_str = Format_sett
MinMax = ""
End If

'col width
If MinMax = "" Then
Columns(col_nr).ColumnWidth = width_str
End If

'MIN col width


If MinMax = "MIN" Then
If Columns(col_nr).ColumnWidth < width_str Then
Columns(col_nr).ColumnWidth = width_str
End If
End If

'MAX col width


If MinMax = "MAX" Then
If Columns(col_nr).ColumnWidth > width_str Then
Columns(col_nr).ColumnWidth = width_str
End If
End If

End If
Next iCounter
End Sub

Function get_obi_from_pipefile(guid As String) As String

get_obi_from_pipefile = ""
If InStr(guid, "-") <= 0 Then
Exit Function
End If

Dim SplitString() As String


SplitString = Split(guid, "-")
get_obi_from_pipefile = SplitString(0)

End Function

Function get_obi(obi As String) As String

Dim str_len As Integer


str_len = Len(obi)
Do While str_len < 8
obi = "0" + obi
str_len = Len(obi)
Loop

get_obi = obi
End Function

Function isspool(IsoMfileName As String) As Boolean


isspool = True
If InStr(IsoMfileName, ".") > 0 Then

Dim SplitString() As String, nr As Integer


SplitString = Split(IsoMfileName, ".")
nr = SplitString(1)
If nr = 0 Then isspool = False

End If
End Function

'Select sheet
Sub sheet_sel(sh_name As String)
If sh_name <> ActiveSheet.Name Then
If WorksheetExists(sh_name) Then
If Sheets(sh_name).Visible = True Then Sheets(sh_name).Select
End If
End If
End Sub

Sub get_number_of_query_lines(arg As Integer)


ReDim FirstColumn(1 To QueryLinesMax) As Variant
Dim iCounter As Integer, found As Boolean
QueryLines = 0
iCounter = 0
found = False
FirstColumn = Range(Cells(1, 1), Cells(QueryLinesMax, 1)).Value
Do While found = False And iCounter <= QueryLinesMax
iCounter = iCounter + 1
If Left(Trim(FirstColumn(iCounter, 1)), 4) = "COL_" Then
found = True
QueryLines = iCounter - 1
End If
Loop ' until

End Sub

Sub set_named_cell(sheetname As Worksheet)


Dim named_cell As String, rest As String, namedcell_Address As String,
namedcell_Name As String
Dim namedcell_value As String, CommaPosition As Integer,
reference_to_namedcell_Address As String, condition As String
named_cell = arr_settings(HeaderLine8, 89)
If named_cell = "" Then Exit Sub
CommaPosition = InStr(1, named_cell, ",") 'get postion of ","
If CommaPosition > 0 Then
namedcell_Address = Left(named_cell, CommaPosition - 1)
rest = Mid(named_cell, CommaPosition + 1)
CommaPosition = InStr(1, rest, ",") 'get postion of ","
If CommaPosition > 0 Then
namedcell_Name = Left(rest, CommaPosition - 1)
namedcell_value = Mid(rest, CommaPosition + 1)
Else
namedcell_Name = rest
End If
End If

Dim first_sheetNO As Integer


first_sheetNO = SheetNo_of_firstdatasheet()
If first_sheetNO = sheetname.index Then
Range(namedcell_Address).Value = namedcell_value
Range(namedcell_Address).Name = namedcell_Name
If CustomPropertyDoesExist(namedcell_Name) = False Then
ActiveWorkbook.CustomDocumentProperties.Add Name:=namedcell_Name,
LinkToContent:=False, Value:="", Type:=msoPropertyTypeString
End If
Else
reference_to_namedcell_Address = "'" & Sheets(first_sheetNO).Name & "'!" &
Range(namedcell_Address).Address
condition = reference_to_namedcell_Address & "<>" & Chr(34) & Chr(34)
Range(namedcell_Address).Value = "=IF(" & condition & "," &
reference_to_namedcell_Address & "," & Chr(34) & Chr(34) & ")"
End If
End Sub

Sub fill_environment_values_in_layout(LastColRow1 As Long)


Exit Sub 'DISABLED, because not yet read.....................

' SheetHeaderLines
Dim cellvalue As String, changed As Boolean
Dim arr_header As Variant 'MUST be variant
arr_header = Range(Cells(1, 1), Cells(SheetHeaderLines, LastColRow1)).Value

For iCol = 1 To LastColRow1


For iRow = 1 To SheetHeaderLines
cellvalue = arr_header(iRow, iCol)
changed = False
Call replace_env_with_its_values(cellvalue, changed)
Call replace_env_with_its_values(cellvalue, changed) ' maybe another
env in the cell
Call replace_env_with_its_values(cellvalue, changed) ' maybe another
env in the cell
If (changed) Then arr_header(iRow, iCol) = cellvalue
Next iRow
Next iCol

Range(Cells(1, 1), Cells(SheetHeaderLines, LastColRow1)).Value = arr_header


End Sub

Sub replace_env_with_its_values(cellvalue, changed As Boolean)


Dim EnvStartPosition As Integer, EnvEndPosition As Integer, env As String,
changed As Boolean
EnvStartPosition = InStr(cellvalue, "$") 'get postion of "$"
If EnvStartPosition = 0 Then Exit Sub

EnvEndPosition = InStr(EnvStartPosition, cellvalue, " ") 'get postion of space


If EnvEndPosition = 0 Then EnvEndPosition = Len(cellvalue)
env = Mid(cellvalue, EnvStartPosition, EnvEndPosition - EnvStartPosition)
For field = 1 To 20
field_env = 21 + field
field_env_value = 52 + field
If env = arr_settings(HeaderLine8, field_env) Then
env_value = arr_settings(HeaderLine8, field_env_value)
changed = True
End If
Next field
If (changed) Then cellvalue = Left(cellvalue, EnvStartPosition - 1) & env &
Right(cellvalue, Len(cellvalue) - EnvEndPosition + 1)
End Sub

Function CustomPropertyDoesExist(CustomPropertyName As String) As Boolean


' Checks if custom property of this workbook already exists
Dim propCustom As DocumentProperty
For Each propCustom In ActiveWorkbook.CustomDocumentProperties
If propCustom.Name = CustomPropertyName Then
CustomPropertyDoesExist = True
Exit Function
End If
Next
CustomPropertyDoesExist = False
End Function

Function CheckServicePack(RequiredServicePack As String) As Boolean


Dim GetServicePack_str As String, ServicePack_num As Integer
CheckServicePack = False ' default value
GetServicePack_str = arr_settings(HeaderLine8, 82) 'Service Pack
If GetServicePack_str = "" Then GetServicePack_str = "0"
ServicePack_num = CInt(GetServicePack_str) ' convert string to integer
If ServicePack_num >= RequiredServicePack Then
CheckServicePack = True
Else
CheckServicePack = False
End If
End Function

Function first_free_pos() As String


ReDim ColPos_used(1 To Col_ArraySize) As Integer
Dim col_nr As Integer
For aCounter = 1 To Col_ArraySize
If Trim(arr_settings(HeaderLine2, aCounter)) <> "" Then
col_nr = arr_settings(HeaderLine2, aCounter) 'get column position
ColPos_used(col_nr) = aCounter
End If
Next aCounter
For aCounter = 1 To Col_ArraySize
If ColPos_used(aCounter) = 0 Then
first_free_pos = aCounter
Exit For
End If
Next aCounter
End Function

Function SheetNo_of_firstdatasheet() As Integer


For Each WorkSh In ActiveWorkbook.Worksheets
If (filtersheets(WorkSh.Name) = False) Then
SheetNo_of_firstdatasheet = WorkSh.index
Exit Function
End If
Next
SheetNo_of_firstdatasheet = -1
End Function
Sub get_SheetHeaderLines(start_r As Integer, start_c As Integer)
SheetHeaderLines = 0
SheetHeaderColumns = 0
If start_c > 0 Then SheetHeaderColumns = start_c
If start_r > 0 Then
SheetHeaderLines = start_r
Exit Sub
End If

Dim layoutsheet As String


layoutsheet = UCase(arr_settings(HeaderLine8, 8))
If layoutsheet = "LAYOUT1" Or layoutsheet = "" Then Exit Sub
If Not WorksheetExists(layoutsheet) Then Exit Sub
Sheets(layoutsheet).Visible = True
Call sheet_sel(layoutsheet) 'select the sheet with that name

Dim arr_in As Variant 'MUST be variant


Dim LastRow As Long, FirstFewCol As Integer
FirstFewCol = 4 ' Check only first few columns for the word 'DATA' ( no
need to check all columns)
SheetHeaderLines = 0
Call sheet_sel(layoutsheet)
LastRow = ActiveSheet.UsedRange.Rows.Count
arr_in = Range(Cells(1, 1), Cells(LastRow, FirstFewCol)).Value 'Checks the
firstfew rows if the word 'DATA' could be found
For col = 1 To FirstFewCol
For counterr = LastRow To 1 Step -1
If SheetHeaderLines = 0 Then
If UCase(arr_in(counterr, col)) = "DATA" Then
start_r = counterr - 1
start_c = col - 1
Exit For
End If
End If
Next counterr
If SheetHeaderLines <> 0 Then Exit For
Next col
SheetHeaderLines = start_r
SheetHeaderColumns = start_c
End Sub

Function window_exists(windowname) As Boolean


window_exists = False
Dim dummy As Long
On Error Resume Next
dummy = Windows(windowname).index
If Err.Number = 0 Then window_exists = True
On Error GoTo 0 ' set back to default
End Function

Function Validate_FileImport(ThisWorkbookName As String, Importfile_excel As


String) As Boolean
'check if import succeded ( if succeeded then an window is active with that
name. exact name stored in Importfile_excel)
Validate_FileImport = False

Importfile_excel = ThisWorkbookName & f_extension


If window_exists(Importfile_excel) Then
Validate_FileImport = True
Exit Function
End If

Importfile_excel = ThisWorkbookName & f_extension & ".xls"


If window_exists(Importfile_excel) Then
Validate_FileImport = True
Exit Function
End If

MsgBox "Warning: Failed fo find an open excel window with the name: " &
Chr(13) & _
"< " & Importfile_excel & " > or < " & ThisWorkbookName &
f_extension & " >" & Chr(13) & _
"Info: This is the expected result after having imported the file: " &
Chr(13) & _
" < " & ThisWorkbook.Path & "\" & ThisWorkbookName & f_extension & "
> ." & Chr(13) & _
" p.s. Current active window is: < " & ActiveWindow.Caption & " > )"
End Function

Function File_Exists(strFile As String) As Boolean


On Error Resume Next
File_Exists = (Len(Dir(strFile)) > 0)
End Function

Function FolderExists(strPath As String) As Boolean


On Error Resume Next
FolderExists = ((GetAttr(strPath) And vbDirectory) = vbDirectory)
End Function
===================================================================================
=========
Rem Attribute VBA_ModuleType=VBAModule
Option VBASupport 1
Option Explicit

Sub CreateMenu(arg As String)


'(added an optional Fake Argument to this subroutine,
' because then it will not be presented in the available macro-list when user
tries to start a macro

'
' creates a new menu.
'
Dim cbMenu As CommandBarControl, cbSubMenu As CommandBarControl

RemoveMenu ' delete the menu if it's already exists


' create a new menu on an existing commandbar (the next 6 lines)
Set cbMenu = Application.CommandBars(1).Controls.Add(msoControlPopup, , , ,
True)
With cbMenu
.Caption = "&N-C Menu"
.tag = "MyTag_N-C_Menu"
.BeginGroup = False
End With

' add menuitem to menu


With cbMenu.Controls.Add(msoControlButton, 1, , , True)
.Caption = "&Report Control"
.OnAction = ThisWorkbook.Name & "!Macro_ListControl"
.FaceId = 548
End With

' add menuitem to menu


With cbMenu.Controls.Add(msoControlButton, 1, , , True)
.Caption = "&Columns Hide / Show"
.OnAction = ThisWorkbook.Name & "!Macro_Form_ShowColumns"
.FaceId = 3836
End With

' add a submenu


Set cbSubMenu = cbMenu.Controls.Add(msoControlPopup, 1, , , True)
With cbSubMenu
.Caption = "&Sheet selection"
.tag = "SubMenu1"
.BeginGroup = True

End With

' add all existing sheets as menuitem to submenu


Dim sheetIndexVar As Long
For sheetIndexVar = 1 To Sheets.Count
'If Sheets(sheetIndexVar).Visible = True Then
If (filtersheets(Sheets(sheetIndexVar).Name) = False) Then
' add menuitem to submenu
With cbSubMenu.Controls.Add(msoControlButton, 1, , , True)
.Caption = Sheets(sheetIndexVar).Name
.OnAction = "'MacroSelectSheet """ & .Caption & """'"
.Style = msoButtonIconAndCaption
If .Caption = ActiveSheet.Name Then
.FaceId = 1 '1= selected
Else
.FaceId = 0 '0=empty
End If
.State = msoButtonDown ' or msoButtonUp
.Enabled = True ' or False
End With
End If
Next sheetIndexVar

' add menuitem to menu


With cbMenu.Controls.Add(msoControlButton, 1, , , True)
.Caption = "&Write settings to a file ( a Report Profile)"
.OnAction = ThisWorkbook.Name & "!Macro_WriteSettingsFile"
.Style = msoButtonIconAndCaption
.FaceId = 3
.BeginGroup = True
End With

If (CheckServicePack(2)) Then
' add menuitem to menu
With cbMenu.Controls.Add(msoControlButton, 1, , , True)
.Caption = "&eBrowser link"
.OnAction = ThisWorkbook.Name & "!setup_eBrowser_link"
.Style = msoButtonIconAndCaption
.FaceId = 1577
.BeginGroup = True
End With
End If

'tip:
'instead of .FaceId = 463 you can also use your own facID's by replacing it with:
'Sheet1.Shapes("Pic1").Copy
'.PasteFace

' add menuitem to menu


With cbMenu.Controls.Add(msoControlButton, 1, , , True)
.Caption = "&Clean up"
.OnAction = ThisWorkbook.Name & "!CleanUp_A"
.Style = msoButtonIconAndCaption
.FaceId = 463
.BeginGroup = True
End With

' add menuitem to menu


With cbMenu.Controls.Add(msoControlButton, 1, , , True)
.Caption = "&Export to a textfile (*.csv)"
.OnAction = ThisWorkbook.Name & "!Macro_ExportToCSV"
.Style = msoButtonIconAndCaption
.FaceId = 0
.BeginGroup = True
End With

Set cbSubMenu = Nothing


Set cbMenu = Nothing
End Sub

Private Sub setup_eBrowser_link()


Call init(1)
If NotAllowedToStartMacroFromHere(True) Then Exit Sub
If Not WorksheetExists("settings") Or Not WorksheetExists(eBrowserSheet) Then
MsgBox "ReportGenerator. It is not possible to Setup an eBrowser-link after
a CleanUp has been done."
Exit Sub
End If
Dim eb_file As String, incl_setup_ref As Boolean
Call ReadSettings(1) 'Readsettings
eb_file = get_ebfile 'ask for location of eBrowserfile
If eb_file = "" Or File_Exists(eb_file) = False Then Exit Sub
Call WriteSettings(1)
incl_setup_ref = True
Call EbrowserInitialize(True, incl_setup_ref) 'initialize the connection
to the eBrowserfile, and load it
If EbrowserInitialized = False Then
Sheets(eBrowserSheet).Visible = False
MsgBox "Failed to setup an eBrowser link."
Exit Sub
End If
Call switch_to_eBrowsersheet(False) 'swich to the eBrowser sheet ( and show no
go-back-button on sheet)
End Sub

Private Sub CleanUp_A()


If MsgBox("The Clean-Up will remove this N-C Menu, " & Chr(10) & _
"and deletes the internal " & "database of this excel file." & Chr(10) & _
"" & Chr(10) & _
"Do you want to Clean-Up ?", vbQuestion + vbYesNo, "Clean up.") = vbNo Then
Exit Sub
End If
Application.ScreenUpdating = False
Call CleanUp_B(True) ' Removes N-C menu, and internal database
Call CleanUp_C(1) ' Removes all macros, etc.
Application.ScreenUpdating = True
End Sub

Sub CleanUp_B(with_message As Boolean)


Call init(1)
If NotAllowedToStartMacroFromHere(with_message) Then Exit Sub

Dim remembered_activesheetname As String, remembered_activecell As String


remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address
Call ReadSettings(0)

Dim WorkSh As Worksheet, LastColRow1 As Long, iCounter As Long


For Each WorkSh In ActiveWorkbook.Worksheets
If (filtersheets(WorkSh.Name) = True) Then
'
' Delete the hidden sheets
'
Application.DisplayAlerts = False
'skip sheet "TOTAL". Also skip sheet "eBrowser" because that sheet will
be deleted at the end.
If WorkSh.Name <> "eBrowser" And UCase(WorkSh.Name) <> "TOTAL" Then
WorkSh.Delete
Application.DisplayAlerts = True
Else
'
' Delete the hidden columns
'
WorkSh.Select
LastColRow1 = last_col_nr(ListStartCol) 'call to function
last_col_nr()

For iCounter = LastColRow1 To 1 Step -1


If Columns(iCounter).EntireColumn.Hidden = True Then
Columns(iCounter).EntireColumn.Delete
End If
Next iCounter

'activate cell A1, to avoid that previous selection is still active


Range("A1").Select
'set active window to left upper corner
ActiveWindow.ScrollRow = 1
ActiveWindow.ScrollColumn = 1

End If
Next

Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select
Call RemoveMenu
Call EbrowserInitialize(False, False) 'check if eBrowser is initialized

' Special treatment for ebrowsersheet while earlier it was crashing during
deletion in previous block ( probably somehow related to the activeX object)
' And also below lines should be done at the end because after this some
function somehow do not work anymore like: Application.ActiveWorkbook.Name
If WorksheetExists("eBrowser") Then
If EbrowserInitialized = False Then ' skip deleting when its active
because otherwise excel crashes
Application.DisplayAlerts = False
' Sheets("eBrowser").Delete ' does not yet work, it crashes because
eBrowser object is still somehow active. Lic even remains active till complete
excel is closed
Application.DisplayAlerts = True
End If
End If
End Sub

Sub Macro_ExportToCSV()
Application.ScreenUpdating = False
Call ExportToCSV(True)
Application.ScreenUpdating = True
End Sub

Sub ExportToCSV(with_message As Boolean)


Call init(1)
If NotAllowedToStartMacroFromHere(with_message) Then Exit Sub

Dim remembered_activesheetname As String, remembered_activecell As String


remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address
Call ReadSettings(0)
Call ExportToCSV_core(with_message)

Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select
End Sub

Sub ExportToCSV_core(with_message As Boolean)


Dim vFileNum As Integer, csv_file As Variant, csv_file_path As String
Dim LastRowColA As Long, LastColRow1 As Long, nr_of_rows As Long, RowIn As
Long, colin As Long
Dim nr_of_cols As Integer, col_pos As Integer, iCounter As Integer,
csv_column_index As Integer
Dim one_line As String, ColName As String, separator As String
Dim csv_file_n As String, next_char As String
Dim WorkSh As Worksheet

csv_file_path = arr_settings(HeaderLine8, 84)


If csv_file_path = "" Then csv_file_path = ThisWorkbook.Path & "\"
If Right(csv_file_path, 1) <> "\" Then csv_file_path = csv_file_path & "\"

If File_Exists(csv_file_path) = False Then


MsgBox "RepGen. Info: Could not export to CSV-file because path is not
found: " & csv_file_path
If with_message = True Then
'ask user the directory:
Exit Sub
Else
Exit Sub
End If
End If
csv_file_n = arr_settings(HeaderLine8, 85)
If csv_file_n = "" Then csv_file_n = Left(ThisWorkbook.Name,
Len(ThisWorkbook.Name) - 4) & ".csv" 'cut off the extension ".xls" and add ".csv"
csv_file = csv_file_path & csv_file_n

Dim ThisWorkbookPath As String, ThisWorkbookName As String, Importfile As


String
ThisWorkbookPath = ThisWorkbook.Path
ThisWorkbookName = ThisWorkbook.Name
ThisWorkbookName = Left(ThisWorkbookName, Len(ThisWorkbookName) - 4) 'cut off
the extension ".xls"

separator = arr_settings(HeaderLine8, 86)


If separator = "" Or separator = "semicolumn" Then separator = ";"

' Get all defined CSV columns and it's column positions and store it in an
array
ReDim arr_csv_col(1 To 99, 1 To 3) As Variant ' 1=Colname, 2=position-nr,
3=value
csv_column_index = 0
Call get_CSV_columns(arr_csv_col, csv_column_index)
If csv_column_index = 0 Then Exit Sub

'Open file for writing


vFileNum = FreeFile()
On Error Resume Next
Open csv_file For Output As #vFileNum
On Error GoTo 0

For Each WorkSh In ActiveWorkbook.Worksheets


If (filtersheets(WorkSh.Name) = False) Then
Sheets(WorkSh.Name).Select 'make the sheet the active sheet
'get last row and column:
LastRowColA = last_row_nr(ListStartLine, ListStartCol) 'call to
function last_row_nr()
LastColRow1 = last_col_nr(ListStartCol) 'call to function
last_col_nr()
nr_of_rows = LastRowColA - ListStartLine + 1
nr_of_cols = LastColRow1 - ListStartCol + 1

Dim cc As Integer
For cc = 1 To csv_column_index
For iCounter = 1 To nr_of_cols
ColName = arr_settings(HeaderLine1, iCounter)
If ColName = arr_csv_col(cc, 1) Then
col_pos = arr_settings(HeaderLine2, iCounter) 'get column
position
arr_csv_col(cc, 2) = col_pos
End If
Next iCounter
Next cc

'read in whole sheet into an array, and loop to all cells and store
value if the columns is needed for CSV
ReDim arr_in(1 To nr_of_rows, 1 To nr_of_cols) As Variant
arr_in = Range(Cells(ListStartLine, ListStartCol), Cells(LastRowColA,
LastColRow1)).Value
For RowIn = 1 To nr_of_rows
one_line = ""
For colin = 0 To nr_of_cols
For cc = 1 To csv_column_index
If colin = arr_csv_col(cc, 2) Then arr_csv_col(cc, 3) =
arr_in(RowIn, colin) ' store value in array
Next cc
Next colin

For cc = 1 To csv_column_index
one_line = one_line & Chr(34) & arr_csv_col(cc, 3) & Chr(34) &
separator
Next cc
one_line = Left(one_line, Len(one_line) - 1) 'skip last seperator-
char at the end of the line (requested by DamenSchelde)

Print #vFileNum, one_line


Next RowIn
End If
Next
Close #vFileNum
If with_message = True Then
MsgBox "created csv-file ready at: " & csv_file
End If
End Sub

Sub get_CSV_columns(arr_csv_col, csv_column_index)


Dim CSV_columnsToDo As String, next_CSV_column As String
CSV_columnsToDo = arr_settings(HeaderLine8, 87)
If CSV_columnsToDo = "" Then Exit Sub

next_CSV_column = "dummy"
Do While (next_CSV_column <> "")
next_CSV_column = get_next_CSV_column(CSV_columnsToDo, csv_column_index)
If next_CSV_column <> "" Then
arr_csv_col(csv_column_index, 1) = next_CSV_column
End If
Loop
End Sub

Function get_next_CSV_column(CSV_columnsToDo, csv_column_index)


Dim pos As Integer
get_next_CSV_column = ""
If CSV_columnsToDo = "" Then Exit Function
pos = InStr(CSV_columnsToDo, ",")
If pos = 0 Then
get_next_CSV_column = CSV_columnsToDo
csv_column_index = csv_column_index + 1
CSV_columnsToDo = ""
Else
get_next_CSV_column = Left(CSV_columnsToDo, pos - 1)
csv_column_index = csv_column_index + 1
CSV_columnsToDo = Right(CSV_columnsToDo, Len(CSV_columnsToDo) - pos)
End If
End Function

Private Sub RemoveMenu()


DeleteCustomCommandBarControl "MyTag_N-C_Menu" ' deletes the new menu
End Sub

Private Sub DeleteCustomCommandBarControl(CustomControlTag As String)


' deletes ALL occurences of commandbar controls with a tag = CustomControlTag
On Error Resume Next
Do
Application.CommandBars.FindControl(, , CustomControlTag, False).Delete
Loop Until Application.CommandBars.FindControl(, , CustomControlTag, False) Is
Nothing
On Error GoTo 0
End Sub

Sub MacroSelectSheet(SelectedSheet As String)


'macro used by the menuitems in order to select a sheet
Call init(1)
If NotAllowedToStartMacroFromHere(True) Then Exit Sub
With Worksheets(SelectedSheet)
.Activate
.Range("A1").Select
End With

'Readsettings ( just voor one headerline8 setting used in subroutine:


CreateMenu
If Not WorksheetExists("settings") Then Exit Sub
Call ReadSettings(1)
Call CreateMenu(1)
End Sub

Sub Macro_ListControl()
Call init(1)
If NotAllowedToStartMacroFromHere(True) Then Exit Sub
Form_ListControl.Show
End Sub

Sub Macro_Form_ShowColumns()
Call init(1)
If NotAllowedToStartMacroFromHere(True) Then Exit Sub
If (filtersheets(ActiveSheet.Name) = True) Then
MsgBox "Not possible to start this function from sheet '" &
ActiveSheet.Name & "'" & _
Chr(10) & " ( please first select another sheet to start this
function )"
Exit Sub
End If
Form_ShowColumns.Show
End Sub

Function NotAllowedToStartMacroFromHere(with_message As Boolean) As Boolean


'Abort when this subroutine is started from some other workbook
' (by checking existence of sheet "import"
'this is just for safety because one of these functions will delete sheets
If Not WorksheetExists("import") Then
If with_message = True Then
MsgBox "ReportGenerator. Not possible to run this macro from this
workbook" & _
Chr(10) & " ( checked by looking for internal import-sheet )"
NotAllowedToStartMacroFromHere = True
End If
Else
NotAllowedToStartMacroFromHere = False
End If

End Function

Sub Macro_WriteSettingsFile()
Call init(1)
If NotAllowedToStartMacroFromHere(True) Then Exit Sub
If Not WorksheetExists("settings") Then Exit Sub

Dim item As String, remembered_activesheetname As String, remembered_activecell


As String
Dim vFileNum As Integer, tempStr As String, i As Long, j As Integer, _
default_rpp_file As String, rpp_file As Variant, rpp_file_str As String,
default_rpp_path As String, _
RememberCurDir As String, DriveLetter As String, default_rpp As String

remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address

Call ReadSettings(1)

' Change dir to directory of rpp-file


default_rpp = arr_settings(HeaderLine8, 76)
default_rpp = Replace(default_rpp, "/", "\")
default_rpp_file = StripFileOrPath(default_rpp, "GetFile")
default_rpp_path = StripFileOrPath(default_rpp, "GetPath")
RememberCurDir = CurDir$()

If File_Exists(default_rpp_path & default_rpp_file) = True Then


DriveLetter = Left$(default_rpp_path, 1)
If DriveLetter <> "/" And DriveLetter <> "\" Then ChDrive DriveLetter
ChDir default_rpp_path
Else
MsgBox "Info: file-Location of rpp-file may be: " & default_rpp_path
End If

'ask user the filename and location:


rpp_file = Application.GetSaveAsFilename(InitialFileName:= _
default_rpp_file, filefilter:= _
"Report Profile (*.rpp), *.rpp", Title:="Please enter filename to export the
settings")

' Change dir to original current directory


DriveLetter = Left$(RememberCurDir, 1)
If DriveLetter <> "/" And DriveLetter <> "\" Then ChDrive DriveLetter
ChDir RememberCurDir

If (rpp_file = False Or rpp_file = "") Then Exit Sub


rpp_file_str = rpp_file
If File_Exists(rpp_file_str) = True Then
If MsgBox("File Already exists!" & Chr(10) & Chr(10) & _
"Are you really sure to overwrite existing file:" & Chr(10) & _
" < " & default_rpp_file & " > ?", _
vbQuestion + vbYesNo, "Writing current settings to a report profile file")
= vbNo Then
MsgBox "Writing file aborted."
Exit Sub
End If
End If

'Open file for writing


vFileNum = FreeFile()
On Error Resume Next
Open rpp_file For Output As #vFileNum
If Err <> 0 Then MsgBox "Cannot save to filename " & rpp_file: End
On Error GoTo 0

Application.ScreenUpdating = False
Sheets("settings").Visible = True
Sheets("settings").Select

If QueryLines > 0 Then


ReDim arr_dummy_q(1 To 1, 1 To QueryLines) As Variant
arr_dummy_q = Range(Cells(1, 1), Cells(QueryLines, 1)).Value
For i = 1 To QueryLines
Print #vFileNum, arr_dummy_q(i, 1)
Next i
End If

ReDim arr_dummy_h(1 To HeaderLines, 1 To Col_ArraySize) As Variant


arr_dummy_h = Range(Cells(QueryLines + 1, 1), Cells(QueryLines + HeaderLines,
Col_ArraySize)).Value
For i = 1 To HeaderLines - 1
tempStr = ""
For j = 1 To Col_ArraySize
tempStr = tempStr & arr_dummy_h(i, j) & ";"
Next j
Print #vFileNum, tempStr
Next i

Close #vFileNum

Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select
Sheets("settings").Visible = False
Application.ScreenUpdating = True
End Sub

Public Function StripFileOrPath(FullPath As String, ReturnType As String) As String


' =====================================================================
' Returns either the FileName or the Path from a given Full FileName
' 1st Arg = Pass a files full name (C:\Example\MyFile.xls)
' 2nd Arg = What to return (either the filename [0] or the path [1]

' Example: MsgBox StripFileOrPath(ThisWorkbook.FullName, GetPath)


' =====================================================================
Dim szPathSep As String, szCut As String, i As Long, szPath As String, szFile
As String
szPathSep = Application.PathSeparator
szCut = CStr(Empty)
i = Len(FullPath)
If i > 0 Then
Do While ((szCut <> szPathSep) And (i > 0))
szCut = Mid$(FullPath, i, 1)
If szCut = szPathSep Then
szPath = Left$(FullPath, i)
szFile = Right$(FullPath, Len(FullPath) - i)
End If
i = i - 1
Loop

Select Case ReturnType


Case "GetPath"
StripFileOrPath = szPath
Case "GetFile"
StripFileOrPath = szFile
Case Else
MsgBox "script warning: unknown case " & ReturnType & " (should be
GetPath or GetFile)"
End Select
Else
StripFileOrPath = CStr(Empty)
End If

End Function

===================================================================================
===
Rem Attribute VBA_ModuleType=VBAModule
Option VBASupport 1
Sub ListControl(SheetDistr_Nr As Integer, SumR1 As Integer, SumR2 As Integer, _
SumR3 As Integer, SumR4 As Integer, SumR5 As Integer, SortR1 As Integer, _
SortR2 As Integer, SortR3 As Integer, setup_importsheet As Boolean)

'Remember current active Worksheet


Dim CurrSheet As String
CurrSheet = ActiveSheet.Name

'==========================================='
' Distribute list to sheets '
'==========================================='
Call SetupSheets(SheetDistr_Nr, setup_importsheet)

Dim nr_of_sheets As Long


nr_of_sheets = Sheets.Count
ReDim TotalFields(1 To nr_of_sheets, 1 To 12) As Variant
TotalShNr = 0

'Preparation for keeping track of objectID references


Dim Size_arr_obi As Long
Sheets("import").Visible = True
Sheets("import").Activate
Size_arr_obi = last_row_nr(1, 1) 'call to function last_row_nr()
ReDim arr_ObiRef(1 To Size_arr_obi, 1 To 1) As Variant 'MUST be variant
Dim arr_obi As Variant 'MUST be variant
Call Fill_arr_obi(arr_obi, Size_arr_obi)
'==========================================='
' Summing & Sorting Rules '
'==========================================='

'loop through all sheets


Dim WorkSh As Worksheet, TotalSheetNr As Long, SheetNr As Long
'TotalSheetNr = ActiveWorkbook.Worksheets.Count - 3 'because excl. "import" &
"settings" sheet
SheetNr = 0
For Each WorkSh In ActiveWorkbook.Worksheets
If (filtersheets(WorkSh.Name) = False) Then
SheetNr = SheetNr + 1
End If
Next
TotalSheetNr = SheetNr

PctDonePiece = 0.74 * (1 / TotalSheetNr)


SheetNr = 0
For Each WorkSh In ActiveWorkbook.Worksheets
If (filtersheets(WorkSh.Name) = False) Then
SheetNr = SheetNr + 1

'make sheet the active sheet


Sheets(WorkSh.Name).Select

'SORT, (first according to the SumRules, to get it proper summed)


Dim c_SumR1 As Integer, c_SumR2 As Integer, c_SumR3 As Integer
Dim c_SumR4 As Integer, c_SumR5 As Integer
Call SortingRules(WorkSh.Name, SumR1, SumR2, SumR3, SumR4, SumR5,
ListStartLine, ListStartCol)

PctDone = 0.25 + (0.74 * ((SheetNr - 0.9) / TotalSheetNr))

'SUM ,(also re-arrange col order)


Call SummingRules(WorkSh.Name, SumR1, SumR2, SumR3, SumR4, SumR5,
arr_obi, arr_ObiRef, Size_arr_obi)

PctDone = 0.25 + (0.74 * ((SheetNr - 0.6) / TotalSheetNr))

'SORT, now according to the SortRules


'before that we retrieve the actual column of the sortkeys
Dim c_SortR1 As Integer, c_SortR2 As Integer, c_SortR3 As Integer
If SortR1 > 0 Then c_SortR1 = arr_settings(HeaderLine2, SortR1)
If SortR2 > 0 Then c_SortR2 = arr_settings(HeaderLine2, SortR2)
If SortR3 > 0 Then c_SortR3 = arr_settings(HeaderLine2, SortR3)
Call SortingRules(WorkSh.Name, c_SortR1, c_SortR2, c_SortR3, 0, 0,
ListStartLine, ListStartCol)

PctDone = 0.25 + (0.74 * ((SheetNr - 0.5) / TotalSheetNr))

'LAYOUT like hide/show, borders, width, etc.


Call Layout_general(WorkSh, False, SheetNr)

PctDone = 0.25 + (0.74 * ((SheetNr - 0) / TotalSheetNr))


Call Progress(PctDone) 'set how much procent is done in pogress-bar

End If
Next
Call sheet_total(SheetNr)

Call write_arr_obi_2_importsheet(arr_ObiRef, Size_arr_obi)

'HIDE sheets
Call HideSheets(1)
If WorksheetExists(CurrSheet) Then
If Sheets(CurrSheet).Name <> "import" Then Sheets(CurrSheet).Activate
End If
End Sub

Private Sub SummingRules(sheetname As String, SumR1 As Integer, SumR2 As Integer, _


SumR3 As Integer, SumR4 As Integer, SumR5 As Integer, _
arr_obi As Variant, arr_ObiRef As Variant, Size_arr_obi As
Long)

'get last row and column


Dim LastRowColA As Long, LastColRow1 As Long, nr_of_rows As Long, nr_of_cols As
Integer
LastRowColA = last_row_nr(ListStartLine, ListStartCol) 'call to function
last_row_nr()
LastColRow1 = last_col_nr(ListStartCol) 'call to function last_col_nr()
nr_of_rows = LastRowColA - ListStartLine + 1
nr_of_cols = LastColRow1 - ListStartCol + 1

'read in whole sheet into an array


Dim arr_in As Variant 'MUST be variant
ReDim arr_outA(1 To nr_of_rows, 1 To nr_of_cols) As Variant
ReDim arr_outB(1 To nr_of_rows, 1 To nr_of_cols) As Variant
arr_in = Range(Cells(ListStartLine, ListStartCol), Cells(LastRowColA,
LastColRow1)).Value

'
'Scan every cell in the three (sorted) suming-columns and,
' if values are same then merge the rows
'
Dim RowIn As Long, RowOut As Long, PctDoneTmp As Single, ObiRef_value As String
Dim s1 As String, s2 As String, s3 As String, obi As String
Dim base1 As String, base2 As String, base3 As String, ColNr As Integer

RowOut = 0
For RowIn = 1 To nr_of_rows
obi = ""
If check_summingrules(arr_in, arr_outA, RowIn, RowOut, SumR1, SumR2, SumR3,
SumR4, SumR5) Then
'values of the three summing-rows are equal, so merge & delete row
Call merge_lines(arr_in, arr_outA, RowIn, RowOut, nr_of_cols, obi)
Else
' just copy the line of arr_in, to a new line in arr_outA
RowOut = RowOut + 1

For i = 1 To nr_of_cols
arr_outA(RowOut, i) = arr_in(RowIn, i)
Next i
obi = arr_in(RowIn, COL_OBI)
End If

'one line in the list could be a merge of several object. Each particular
object
'on the import sheet will refer to the sheet and the OBIREF line which is
stored here:
'(is stored because after sorting the actual line numbers will be husstled
arr_outA(RowOut, COL_OBIREF) = RowOut
ObiRef_value = Sheets(sheetname).index & "_" & RowOut
Call Fill_field_Obi(arr_obi, arr_ObiRef, Size_arr_obi, ObiRef_value, obi)

PctDoneTmp = PctDone + PctDonePiece * iCounter / LastRowColA


Call Progress(PctDoneTmp)

Next RowIn

If 1 = 0 Then
'
'SKIP this because this method is not save. if COG=(0,0,0) we can fill it with
LOXYZ,
'this is good when COG is not defined, BUT NOT GOOD for instance when main
engine is
'placed has COG(0,0,0), then we should NOT replace this with LOXYZ
'
'
' Values are all in array so make use of this opportunity and do some
additional processing:
' when COG is not defined then take values from LocalCoordinate; LOX YZ
'
Dim cgx As String, cgy As String, cgz As String
Dim lox As String, loy As String, loz As String
For iRow = 1 To nr_of_rows
For iCol = 1 To nr_of_cols
cgx = arr_outA(COL_CGX, iCol)
cgy = arr_outA(COL_CGY, iCol)
cgz = arr_outA(COL_CGZ, iCol)
lox = arr_outA(COL_LOX, iCol)
loy = arr_outA(COL_LOY, iCol)
loz = arr_outA(COL_LOZ, iCol)
'
' if .... then ....
'
Next iCol
Next iRow
End If

'
' Just before writing the array to the sheet we now (re-)arrange the order of
the columns
'
'BE AWARE THAT HeaderLine2 contains all rowvalues (if one is missing then it is
not declared)
'
For iCol = 1 To nr_of_cols
ColNr = arr_settings(HeaderLine2, iCol)
For iRow = 1 To nr_of_rows
arr_outB(iRow, ColNr) = arr_outA(iRow, iCol)
Next iRow
Next iCol

'
'write back to the sheet the array arr_outB
'
Call SetColFormat(1) 'set format correct otherwise value might get mutilated
(0011 becomes 11)
Range(Cells(ListStartLine, ListStartCol), Cells(LastRowColA,
LastColRow1)).Value = arr_outB

Dim old_lastline, new_lastline


old_lastline = LastRowColA
new_lastline = RowOut + ListStartLine - 1
If new_lastline < old_lastline Then
'delete the empty rows between last line in arr_outA and last line of
arr_in
Rows(new_lastline + 1 & ":" & old_lastline).Delete
End If

Cells(1, 1).Select 'just select "A1" in order to get active cel to so far down

End Sub

Function check_summingrules(arr_in As Variant, arr_outA As Variant, RowIn As Long,


RowOut As Long, SumR1 As Integer, _
SumR2 As Integer, SumR3 As Integer, SumR4 As Integer, SumR5 As Integer) As
Boolean

check_summingrules = False

'no lines yes copied to arr_outA so nothing to compare yes, therefor exit
If RowOut = 0 Then Exit Function

'Exit in case all Summing rules are "<none>" (=0)


If SumR1 = 0 And SumR2 = 0 And SumR3 = 0 And SumR4 = 0 And SumR5 = 0 Then Exit
Function

'refering to the two rows; check if the three cell-values are the same
Dim s1 As String, s2 As String, s3 As String, s4 As String, s5 As String,
SumAccording As String
Dim base1 As String, base2 As String, base3 As String, base4 As String, base5
As String
base1 = ""
base2 = ""
base3 = ""
base4 = ""
base5 = ""
s1 = ""
s2 = ""
s3 = ""
s4 = ""
s5 = ""
If SumR1 > 0 Then base1 = arr_in(RowIn, SumR1)
If SumR2 > 0 Then base2 = arr_in(RowIn, SumR2)
If SumR3 > 0 Then base3 = arr_in(RowIn, SumR3)
If SumR4 > 0 Then base4 = arr_in(RowIn, SumR4)
If SumR5 > 0 Then base5 = arr_in(RowIn, SumR5)
If SumR1 > 0 Then s1 = arr_outA(RowOut, SumR1)
If SumR2 > 0 Then s2 = arr_outA(RowOut, SumR2)
If SumR3 > 0 Then s3 = arr_outA(RowOut, SumR3)
If SumR4 > 0 Then s4 = arr_outA(RowOut, SumR4)
If SumR5 > 0 Then s5 = arr_outA(RowOut, SumR5)
SumAccording = arr_settings(HeaderLine8, 91)
If SumAccording = "0" Or SumAccording = "1" Then
If (base1 = s1) And (base2 = s2) And (base3 = s3) And (base4 = s4) And
(base5 = s5) Then
check_summingrules = True
If SumAccording = "0" Then
'Don't Sum the EmptyFields
If (base1 = "") And (base2 = "") And (base3 = "") And (base4 = "")
And (base5 = "") Then check_summingrules = False
End If
End If
End If

If SumAccording = "2" Then


' Sum first only according Sum1 and Sum2, and only if both are epmty then
Sum according Sum3
If (base1 = s1) And (base2 = s2) Then
If (base1 <> "") And (base2 <> "") Then
check_summingrules = True
Else
' S1 and S2 are empty
If (base3 = s3) Then
If (base3 <> "") Then
check_summingrules = True
End If
End If
End If
End If
End If

If SumAccording = "3" Then


' Sum first only according Sum1 and only if empty then Sum according Sum2
and if that's also empty, then sum according Sum3
If (base1 = s1) Then
If (base1 <> "") Then
check_summingrules = True
Else
' S1 is empty
If (base2 = s2) Then
If (base2 <> "") Then
check_summingrules = True
Else
' S1 and S2 are empty
If (base3 = s3) Then
If (base3 <> "") Then
check_summingrules = True
End If
End If
End If
End If
End If
End If
End If

End Function

Private Sub merge_lines(arr_in As Variant, arr_outA As Variant, RowIn As Long,


RowOut As Long, _
nr_of_cols As Integer, obi As String)

Dim TempValue As Double


Dim i As Integer, temp_str1 As String, temp_str2 As String, temp_biggest_value
As String

' First all the columns that should be summed with a weightfactor according to
another column
' (this needs to be done first otherwise that other columns is already summed)
For i = 1 To nr_of_cols
Select Case i

Case COL_CGX, COL_CGY, COL_CGZ


arr_outA(RowOut, i) = weighted_summ(i, COL_MAS, arr_in, arr_outA,
RowIn, RowOut)

Case COL_CONX, COL_CONY, COL_CONZ


arr_outA(RowOut, i) = weighted_summ(i, COL_CONM, arr_in, arr_outA,
RowIn, RowOut)

Case COL_TOTX, COL_TOTY, COL_TOTZ


arr_outA(RowOut, i) = weighted_summ(i, COL_TOTM, arr_in, arr_outA,
RowIn, RowOut)

End Select
Next i

' the other Columns


For i = 1 To nr_of_cols
Select Case i

Case COL_BPL, COL_LEN, COL_QTY, COL_MAS, COL_CONM, COL_TOTM, COL_CONV


'numeric fields that should be just summed
TempValue = arr_outA(RowOut, i)
If IsNumeric(arr_in(RowIn, i)) Then TempValue = TempValue +
arr_in(RowIn, i) ' check if value is numeric just to be sure and avoid error
If TempValue > 0.0001 Then arr_outA(RowOut, i) = TempValue

Case COL_CUST1 To nr_of_cols


If LCase(arr_settings(HeaderLine7, i)) = "sum" Then
TempValue = arr_outA(RowOut, i) + arr_in(RowIn, i)
If TempValue > 0.0001 Then arr_outA(RowOut, i) = TempValue
Else
If arr_outA(RowOut, i) <> arr_in(RowIn, i) Then arr_outA(RowOut, i)
= ""
End If

Case COL_CGX, COL_CGY, COL_CGZ, COL_CONX, COL_CONY, COL_CONZ, COL_TOTX,


COL_TOTY, COL_TOTZ
' do nothing here (beacuse is already done)
Case COL_MOT
If arr_outA(RowOut, i) <> "" And arr_in(RowIn, i) <> "" Then
temp_str1 = arr_outA(RowOut, i)
temp_str2 = arr_in(RowIn, i)
If temp_str1 > temp_str2 Then
temp_biggest_value = temp_str1
Else
temp_biggest_value = temp_str2
End If
arr_outA(RowOut, i) = temp_biggest_value
End If
If arr_outA(RowOut, i) = "" And arr_in(RowIn, i) <> "" Then
arr_outA(RowOut, i) = arr_in(RowIn, i)
End If

Case COL_OBI
' put one objectID in the column in case of different values.
' ( not all objectId because that will be too much for big lists)
temp_str1 = arr_in(RowIn, i)
temp_str2 = arr_outA(RowOut, i)
If temp_str1 <> "" And temp_str2 = "" Then
arr_outA(RowOut, i) = temp_str1
End If
Case COL_OBIREF
'do nothing (is done elsewhere)
Case COL_BLK
' in case of different values don't clear it.
' and in case one of the value is empty then take the not-empty one.
temp_str1 = arr_in(RowIn, i)
temp_str2 = arr_outA(RowOut, i)
If temp_str1 <> "" And temp_str2 = "" Then
arr_outA(RowOut, i) = temp_str1
End If
Case Else
'clear field if contents are different
If arr_outA(RowOut, i) <> arr_in(RowIn, i) Then
arr_outA(RowOut, i) = ""
If i = COL_CAT Then arr_outA(RowOut, i) = "Several"
End If

End Select
Next i
obi = arr_in(RowIn, COL_OBI)

End Sub

Private Sub SortingRules(sheetname As String, SortR1 As Integer, SortR2 As Integer,


SortR3 As Integer, _
SortR4 As Integer, SortR5 As Integer, begin_row As
Integer, begin_col As Integer)

If SortR4 <> 0 Or SortR5 <> 0 Then


MsgBox "you are using more then 3 summing rules, this is not (yet?)
supported"
End If

'Exit in case all Sorting rules are "<none>" (=0)


If SortR1 = 0 And SortR2 = 0 And SortR3 = 0 And SortR4 = 0 And SortR5 = 0 Then
Exit Sub

'First Sort according the selected sortingrules


Dim sortkey1 As Range, sortkey2 As Range, sortkey3 As Range
If SortR1 > 0 Then
If SortR2 = 0 And SortR3 = 0 Then Call sorting(sheetname, SortR1, 0, 0,
begin_row, begin_col)
If SortR2 = 0 And SortR3 > 0 Then Call sorting(sheetname, SortR1, SortR3,
0, begin_row, begin_col)
If SortR2 > 0 And SortR3 = 0 Then Call sorting(sheetname, SortR1, SortR2,
0, begin_row, begin_col)
If SortR2 > 0 And SortR3 > 0 Then Call sorting(sheetname, SortR1, SortR2,
SortR3, begin_row, begin_col)
Else
If SortR2 = 0 And SortR3 = 0 Then MsgBox "actually, this should never
occur"
If SortR2 = 0 And SortR3 > 0 Then Call sorting(sheetname, SortR3, 0, 0,
begin_row, begin_col)
If SortR2 > 0 And SortR3 = 0 Then Call sorting(sheetname, SortR2, 0, 0,
begin_row, begin_col)
If SortR2 > 0 And SortR3 > 0 Then Call sorting(sheetname, SortR2, SortR3,
0, begin_row, begin_col)
End If

End Sub

Private Sub sorting(sheetname As String, sortkey1 As Integer, sortkey2 As Integer,


_
sortkey3 As Integer, begin_row As Integer, begin_col As
Integer)

'get last row


Dim LastRowColA As Long, br As Integer
Dim sortkey1_ As Integer, sortkey2_ As Integer, sortkey3_ As Integer
br = begin_row
sortkey1_ = sortkey1 + begin_col - 1
sortkey2_ = sortkey2 + begin_col - 1
sortkey3_ = sortkey3 + begin_col - 1
LastRowColA = last_row_nr(br, begin_col) 'call to function last_row_nr()

'select
Rows(br & ":" & LastRowColA).Select

If sortkey1 > 0 And sortkey2 = 0 And sortkey3 = 0 Then


Selection.Sort Key1:=Range(Cells(br, sortkey1_), Cells(br, sortkey1_)),
Order1:=xlAscending, _
Header:=xlGuess, OrderCustom:=1, MatchCase:=False,
Orientation:=xlTopToBottom
End If
If sortkey1 > 0 And sortkey2 > 0 And sortkey3 = 0 Then
Selection.Sort Key1:=Range(Cells(br, sortkey1_), Cells(br, sortkey1_)),
Order1:=xlAscending, _
Key2:=Range(Cells(br, sortkey2_), Cells(br, sortkey2_)),
Order2:=xlAscending, _
Header:=xlGuess, OrderCustom:=1, MatchCase:=False,
Orientation:=xlTopToBottom
End If
If sortkey1 > 0 And sortkey2 > 0 And sortkey3 > 0 Then
Selection.Sort Key1:=Range(Cells(br, sortkey1_), Cells(br, sortkey1_)),
Order1:=xlAscending, _
Key2:=Range(Cells(br, sortkey2_), Cells(br, sortkey2_)),
Order2:=xlAscending, _
Key3:=Range(Cells(br, sortkey3_), Cells(br, sortkey3_)),
Order3:=xlAscending, _
Header:=xlGuess, OrderCustom:=1, MatchCase:=False,
Orientation:=xlTopToBottom
End If

Cells(1, 1).Select 'just select "A1" in order to de-select last range-selection


End Sub

Sub Progress(ProcentDone As Single)


' Only update when it's needed (otherwise the repaint-command will let the
panelflickering
ProcentDone = Round(ProcentDone, 2)
If ProcentDone >= PctDonePrev + 0.01 Then
'WAITPANEL
With waitpanel
.FrameProgress.Caption = format(ProcentDone, "0%")
.LabelProgress.Width = ProcentDone * (.FrameProgress.Width - 10)
.Repaint
End With

If (False) Then
'STATUS-BAR
Const NumBars As Integer = 30 ' # of characters in the bar
Dim FBar As Integer, BBar As Integer
FBar = CInt(ProcentDone * NumBars)
BBar = NumBars - FBar
BarText = format(ProcentDone, "0%")
Application.StatusBar = BarText & Application.Rept(">", FBar) & _
Application.Rept(".", BBar)
If ProcentDone = 1 Then Application.StatusBar = False
End If

PctDonePrev = ProcentDone
End If

End Sub

Function weighted_summ(col As Integer, col_weight_factor As Integer, arr_in As


Variant, _
arr_outA As Variant, RowIn As Long, RowOut As Long) As
Double

'calculates a summ, but not just add values of the col,


' but it will weight it to the column col_weight_factor.
'For instance the CGX is not just added, but weighted to the MASS column

Dim SummWeight As Double, sum_part1 As Double, sum_part2 As Double


Dim TempValue As Double

SummWeight = arr_outA(RowOut, col_weight_factor) + arr_in(RowIn,


col_weight_factor)
If (SummWeight > 0.001) Then
sum_part1 = arr_outA(RowOut, col) * arr_outA(RowOut, col_weight_factor)
sum_part2 = arr_in(RowIn, col) * arr_in(RowIn, col_weight_factor)
weighted_summ = (sum_part1 + sum_part2) / SummWeight
Else
'Cannot do a weighted sum because Summweight is zero. Therefore do just a
unweighted sum
' this can happen for instance when object has no Mass or ContentMass, but
do has a COG
Unweighted_summ = (arr_in(RowIn, col) + arr_outA(RowOut, col)) / 2

'15-1-2009 skip unweighted_sum, for instance the content weight can be 0


then I don't want
' content COG to be inserted in total COG!
' skip this line: weighted_summ = Unweighted_summ
weighted_summ = arr_outA(RowOut, col)
' so actually nothing done here: just writes same value back

End If

End Function

Function last_row_nr(begin_row As Integer, begin_col As Integer) As Long


'
' get the last Rownr.
'
' check from COL_CAT and from the actual column that belongs to COL_CAT
' (this is because it is run from "import"-sheet or from another sheet,
' the other sheets the columns where already re-ordered)
'

Dim c1 As Long, c2 As Long, c_ As Integer


c1 = 0
c2 = 0
c_ = arr_settings(HeaderLine2, COL_CAT)
'c1 = Range(Column2Char(c_ + begin_col - 1) & begin_row).End(xlDown).Row
'c2 = Range(Column2Char(COL_CAT + begin_col - 1) & begin_row).End(xlDown).Row
c1 = Range(Column2Char(c_ + begin_col - 1) & "65536").End(xlUp).row
c2 = Range(Column2Char(COL_CAT + begin_col - 1) & "65536").End(xlUp).row

'get biggest value (=lowest row)


If c1 > c2 Then
last_row_nr = c1
Else
last_row_nr = c2
End If

If last_row_nr <= begin_row Then last_row_nr = begin_row + 1

End Function

Function last_row_nr_methodB(begin_row As Integer, begin_col As Integer) As Long


'
' get the last Rownr.
'
' check from COL_CAT and from the actual column that belongs to COL_CAT
' (this is because it is run from "import"-sheet or from another sheet,
' the other sheets the columns where already re-ordered)
'
' This is now not done via reading settings_array because in this
'context is has not the actual values (but in the process of new values)

Dim c1 As Long, c_ As Integer


c_ = ColPos(COL_CAT)
c1 = Range(Column2Char(c_ + begin_col - 1) & "65536").End(xlUp).row
last_row_nr_methodB = c1

If last_row_nr_methodB <= begin_row Then last_row_nr_methodB = begin_row + 1

End Function
Function last_col_nr(begin_col As Integer) As Integer
'
' get the last Col-nr.
'
last_col_nr = begin_col + Col_ArraySize - 1
If last_col_nr < begin_col Then last_col_nr = begin_col

End Function

Function filtersheets(WorkSh_Name As String) As Boolean


'the worksheets defined here, are not part of the sheets of the material list
filtersheets = False
If (LCase(WorkSh_Name) = "import") Then filtersheets = True
If (LCase(WorkSh_Name) = "settings") Then filtersheets = True
If (UCase(WorkSh_Name) = "TOTAL") Then filtersheets = True
If (UCase(Left(WorkSh_Name, 6)) = "LAYOUT") Then filtersheets = True
If (WorkSh_Name = "eBrowser") Then filtersheets = True
End Function

Sub HideSheets(arg As Integer)

'HIDE sheets
For Each WorkSh In ActiveWorkbook.Worksheets
If (WorkSh_Name = "eBrowser") Then
If (EbrowserInitialized = False) Then Sheets(WorkSh.Name).Visible =
False
Else
If (filtersheets(WorkSh.Name) = True) Then
Sheets(WorkSh.Name).Visible = False
End If
End If

If UCase(WorkSh.Name) = "TOTAL" Then


Dim add_tot_fields As Integer
add_tot_fields = arr_settings(HeaderLine8, 12)
If add_tot_fields > 3 Then add_tot_fields = 0
If add_tot_fields = 2 Or add_tot_fields = 3 Then
Sheets(WorkSh.Name).Visible = True
Else
Sheets(WorkSh.Name).Visible = False
End If
End If
Next
End Sub

Sub Fill_arr_obi(arr_obi As Variant, Size_arr_obi As Long)


Size_arr_obi = last_row_nr(1, 1) 'call to function last_row_nr()
arr_obi = Range(Cells(1, COL_OBI), Cells(Size_arr_obi, COL_OBI)).Value
End Sub

Sub Fill_arr_obiRef(arr_ObiRef As Variant, Size_arr_obi As Long)


Size_arr_obi = last_row_nr(1, 1) 'call to function last_row_nr()
arr_ObiRef = Range(Cells(1, COL_OBIREF), Cells(Size_arr_obi, COL_OBIREF)).Value
End Sub

Sub Fill_field_Obi(arr_obi As Variant, arr_ObiRef As Variant, Size_arr_obi As Long,


_
ObiRef_value As String, obi As String)
For rCounter = 1 To Size_arr_obi
If arr_obi(rCounter, 1) = obi Then
arr_ObiRef(rCounter, 1) = ObiRef_value
Exit For
End If
Next rCounter
End Sub

Sub write_arr_obi_2_importsheet(arr_ObiRef As Variant, Size_arr_obi As Long)


Sheets("import").Visible = True
Sheets("import").Activate
Range(Cells(1, COL_OBIREF), Cells(Size_arr_obi, COL_OBIREF)).Value = arr_ObiRef
End Sub
===================================================================================
===
Rem Attribute VBA_ModuleType=VBAModule
Option VBASupport 1
Public RepaintProgressBar As Boolean
Public StartedFromListControl As Boolean
Public EbrowserInitialized As Boolean
Public eBrowserSheet As String
Public eb_objname As String
Public f_extension As String
Public ColPos(1 To 91) As Variant 'this max. should be same value as
Col_ArraySize
Public ColTitel(1 To 91) As Variant 'this max. should be same value as
Col_ArraySize
Public ColTitel_sor(1 To 91) As Variant 'this max. should be same value as
Col_ArraySize
Public ColHideShow(1 To 91) As Variant 'this max. should be same value as
Col_ArraySize
Public frm(1 To 91) As Variant 'this max. should be same value as
Col_ArraySize
Public Col_ArraySize As Integer
Public arr_settings As Variant
Public TotalFields As Variant
Public sett_table As Variant
Public tagfrom_options(1 To 6, 1 To 2) As Variant

Public PctDone As Single


Public PctDonePrev As Single
Public PctDonePiece As Single
Public SheetHeaderLines As Integer
Public SheetHeaderColumns As Integer
Public ListStartCol As Integer
Public ListStartLine As Integer
Public QueryLines As Integer
Public QueryLinesMax As Integer
Public HeaderLines As Integer
Public HeaderLine1 As Integer
Public HeaderLine2 As Integer
Public HeaderLine3 As Integer
Public HeaderLine4 As Integer
Public HeaderLine5 As Integer
Public HeaderLine6 As Integer
Public HeaderLine7 As Integer
Public HeaderLine8 As Integer
Public HeaderLine9 As Integer
Public HeaderLine10 As Integer
Public HeaderLine11 As Integer
Public LayoutSetting_just_changed As Boolean

Public COL_CAT As Integer


Public COL_PLI As Integer
Public COL_SPN As Integer
Public COL_SYS As Integer
Public COL_DE As Integer
Public COL_DD As Integer
Public COL_FII As Integer
Public COL_ART As Integer
Public COL_VPO As Integer
Public COL_BPL As Integer
Public COL_LEN As Integer
Public COL_QTY As Integer
Public COL_GT As Integer
Public COL_MAS As Integer
Public COL_CGX As Integer
Public COL_CGY As Integer
Public COL_CGZ As Integer
Public COL_CONM As Integer
Public COL_CONX As Integer
Public COL_CONY As Integer
Public COL_CONZ As Integer
Public COL_FLUID As Integer
Public COL_CONV As Integer
Public COL_TOTM As Integer
Public COL_TOTX As Integer
Public COL_TOTY As Integer
Public COL_TOTZ As Integer
Public COL_OBI As Integer
Public COL_PID As Integer
Public COL_CORP As Integer
Public COL_DIMT As Integer
Public COL_SLAVE As Integer
Public COL_MAT As Integer
Public COL_SPC As Integer
Public COL_CMD As Integer
Public COL_NAM As Integer
Public COL_LOX As Integer
Public COL_LOY As Integer
Public COL_LOZ As Integer
Public COL_HUL As Integer

Public COL_MTH As Integer


Public COL_SCO As Integer
Public COL_UNIT As Integer
Public COL_IDN As Integer
Public COL_MOT As Integer
Public COL_SPO As Integer
Public COL_BLK As Integer
Public COL_IPO As Integer
Public COL_CUST1 As Integer
Public COL_CUST2 As Integer
Public COL_CUST3 As Integer
Public COL_CUST4 As Integer
Public COL_CUST5 As Integer
Public COL_CUST6 As Integer
Public COL_CUST7 As Integer
Public COL_CUST8 As Integer
Public COL_CUST9 As Integer
Public COL_CUST10 As Integer
Public COL_CUST11 As Integer
Public COL_CUST12 As Integer
Public COL_CUST13 As Integer
Public COL_CUST14 As Integer
Public COL_CUST15 As Integer
Public COL_CUST16 As Integer
Public COL_CUST17 As Integer
Public COL_CUST18 As Integer
Public COL_CUST19 As Integer
Public COL_CUST20 As Integer
Public COL_CUST21 As Integer
Public COL_CUST22 As Integer
Public COL_CUST23 As Integer
Public COL_CUST24 As Integer
Public COL_CUST25 As Integer
Public COL_CUST26 As Integer
Public COL_CUST27 As Integer
Public COL_CUST28 As Integer
Public COL_CUST29 As Integer
Public COL_CUST30 As Integer
Public COL_CUST31 As Integer
Public COL_CUST32 As Integer
Public COL_CUST33 As Integer
Public COL_CUST34 As Integer
Public COL_CUST35 As Integer
Public COL_CUST36 As Integer
Public COL_CUST37 As Integer
Public COL_CUST38 As Integer
Public COL_CUST39 As Integer
Public COL_CUST40 As Integer
Public COL_CUST41 As Integer
Public COL_CUST42 As Integer
Public COL_OBIREF As Integer

Sub init(arg As String)

EbrowserInitialized = False
eBrowserSheet = "eBrowser"
eb_objname = "eBrowserObject"
PctDone = 0
PctDonePrev = 0
LayoutSetting_just_changed = False
Col_ArraySize = 91
f_extension = "_sum"
SheetHeaderLines = 0
SheetHeaderColumns = 0
ListStartLine = SheetHeaderLines + 3 ' begin-row of the list-area
ListStartCol = SheetHeaderColumns + 1 ' begin-column of the list-area
QueryLinesMax = 500
HeaderLines = 11
HeaderLine1 = 1 'contains the internal NAME of the column (COL_..)
HeaderLine2 = 2 'contains col POSITION (which is first col, second, third,
etc.)
HeaderLine3 = 3 'whether the column should be SHOWN or hidden
HeaderLine4 = 4 'FORMAT of the column and how many decimals (string / float0 /
float2 / date)
HeaderLine5 = 5 'the CUSTOM TAGS for the custom columns
HeaderLine6 = 6 '(MAX) WIDTH of the columns
' empty or "AUTOFIT" means autofit columnwidth
' value means fixed columnwidth
'MIN + value means MIN columnwidth
'MAX + value means MAX columnwidth
HeaderLine7 = 7 'Columns which should be SUMMED in case lines where merged.
Only for CUSTOM col!
HeaderLine8 = 8 'SETTINGS can be found in this row in the following cells:
' 1 - distr,
' 2 - SummingR1,
' 3 - SummingR2,
' 4 - SummingR3,
' 5 - SortR1,
' 6 - SortR2,
' 7 - SortR3,
' 8 - LayoutVersion
' 9 - SheetHeaderLines
' 10 - SheetHeaderColumns
' 11 - columnwidth_via_layoutsheet (if it has this value then
set col same as sheet)
' 12 - addtotalfields:
' Value | on every sheet | include summary sheet
' 0 | NO | NO
' 1 | YES | NO
' 2 | NO | YES
' 3 | YES | YES

' 13 - hidetitelrow (if it has this value then hide titelrow)


' 14 - CounterColumn (contains column that should be get
counter-values)
' 15 - UNIT_in_Meters Value | Meaning
' 0 | Unit in mm
' 1 | Unit in Meters
' 16 definition LeftHeader ,in layout of sheet
' 17 definition CenterHeader ,in layout of sheet
' 18 definition RightHeader ,in layout of sheet
' 19 definition LeftFooter ,in layout of sheet
' 20 definition CenterFooter ,in layout of sheet
' 21 definition RightFooter ,in layout of sheet
' 22-41 definition environment ,in layout of sheet

' 46 LeftHeader text ,in layout of sheet


' 47 CenterHeader text ,in layout of sheet
' 48 RightHeader text ,in layout of sheet
' 49 LeftFooter text ,in layout of sheet
' 50 CenterFooter text ,in layout of sheet
' 51 RightFooter text ,in layout of sheet
' 52-71 value-txt of environm ,in layout of sheet

' 42 fit width to the with of one page ( via scaling) 0 =


false / 1 = true
' 43-45 empty
' 71 - 75 empty

' 76 Current ReportProfile file (*.rpp) incl path


' 77 include Total Content Weigths:
' Value | on every sheet | on summary sheet
' 0 | NO | NO
' 1 | YES | NO
' 2 | NO | YES
' 3 | YES | YES
' 78 - SummingR4,
' 79 - SummingR5,
' 80 - Add Quantity ( in case no qty is used at object)
' Value |
' 1 | YES
' else| NO
' 81 - ExtraMaterial,
' Value |
' 0 | None
' 1 | Only Gaskets
' 2 | Only Bolts, Nuts, Washers
' 3 | Gaskets AND Bolts, Nuts, Washers
' 4 |
' 82 - Service pack ( of the piping macro)
' 83 - EbrowserFile
' 84 - csv-file; complete path
' 85 - csv-file; filename
' 86 - csv-file; used seperator character
' 87 - Defines which columns should be exported during export
to CSV file. For instance:
' COL_SYS,COL_PLI,COL_DE,COL_CUST9
' 88 - settings:
' 1st bit: 1=close excel after export to excel
' 2nd bit: 1=export to csv file
' 3rd bit: 1=delete sum-file (afterwards, which also can
be used as indicator that it's ready)
' 4th bit: 1=CleanUp: remove N-C Menu, and internal
database
' 5th bit: 1=CleanUp: remove internal VB-macro's

' 89 - named cell, and cell-address of the named cell ( with


comma in between)
' 90 - path to Report (xls-file)
' 91 - 0/1 sum empty fields during applying summing rules.
1=yes
' 91 - SumAccording 0 = "Use all rules, and if empty values
then don't sum"
' 1 = "Use all rules, and if empty values
then sum"
' 2 = "Use rules 1 & 2, and if empty then
accord. rule 3"
' 3 = "Use rules 1, if empty: use rule 2,
if empty: rule 3"

HeaderLine9 = 9 ' an object can be both on iso and on spool.


' this setting defines from where the info is retrieved:
' spool - pipe info retrieved only from SPOOL
' iso - pipe info retrieved only from ISO
' pm - Plant Modeller (is default)
' proj - attribuut retrieved from project
' hf_iso - Headerfile from iso
' hf_spool - Headerfile from spool
HeaderLine10 = 10 'DESCRTIPTION of the column customized values
HeaderLine11 = 11 'DESCRTIPTION default-values generated from software

' text in menu:


tagfrom_options(1, 1) = "Plant Modeller"
tagfrom_options(2, 1) = "Project"
tagfrom_options(3, 1) = "Pipe: Iso"
tagfrom_options(4, 1) = "Pipe: Spool"
tagfrom_options(5, 1) = "Pipe: IsoHeader"
tagfrom_options(6, 1) = "Pipe: SpoolHeader"
' text internal in rpp-file:
tagfrom_options(1, 2) = ""
tagfrom_options(2, 2) = "proj"
tagfrom_options(3, 2) = "iso"
tagfrom_options(4, 2) = "spool"
tagfrom_options(5, 2) = "hf_iso"
tagfrom_options(6, 2) = "hf_spool"

COL_CAT = 1
COL_PLI = 2
COL_SPN = 3
COL_SYS = 4
COL_DE = 5
COL_DD = 6
COL_FII = 7
COL_ART = 8
COL_VPO = 9
COL_BPL = 10
COL_LEN = 11
COL_QTY = 12
COL_GT = 13
COL_MAS = 14
COL_CGX = 15
COL_CGY = 16
COL_CGZ = 17
COL_CONM = 18
COL_CONX = 19
COL_CONY = 20
COL_CONZ = 21
COL_FLUID = 22
COL_CONV = 23
COL_TOTM = 24
COL_TOTX = 25
COL_TOTY = 26
COL_TOTZ = 27
COL_OBI = 28
COL_PID = 29
COL_CORP = 30
COL_DIMT = 31
COL_SLAVE = 32
COL_MAT = 33
COL_SPC = 34
COL_CMD = 35
COL_NAM = 36
COL_LOX = 37
COL_LOY = 38
COL_LOZ = 39
COL_HUL = 40
COL_MTH = 41
COL_SCO = 42
COL_UNIT = 43
COL_IDN = 44
COL_MOT = 45
COL_SPO = 46
COL_BLK = 47
COL_IPO = 48
COL_CUST1 = 49
COL_CUST2 = 50
COL_CUST3 = 51
COL_CUST4 = 52
COL_CUST5 = 53
COL_CUST6 = 54
COL_CUST7 = 55
COL_CUST8 = 56
COL_CUST9 = 57
COL_CUST10 = 58
COL_CUST11 = 59
COL_CUST12 = 60
COL_CUST13 = 61
COL_CUST14 = 62
COL_CUST15 = 63
COL_CUST16 = 64
COL_CUST17 = 65
COL_CUST18 = 66
COL_CUST19 = 67
COL_CUST20 = 68
COL_CUST21 = 69
COL_CUST22 = 70
COL_CUST23 = 71
COL_CUST24 = 72
COL_CUST25 = 73
COL_CUST26 = 74
COL_CUST27 = 75
COL_CUST28 = 76
COL_CUST29 = 77
COL_CUST30 = 78
COL_CUST31 = 79
COL_CUST32 = 80
COL_CUST33 = 81
COL_CUST34 = 82
COL_CUST35 = 83
COL_CUST36 = 84
COL_CUST37 = 85
COL_CUST38 = 86
COL_CUST39 = 87
COL_CUST40 = 88
COL_CUST41 = 89
COL_CUST42 = 90
COL_OBIREF = 91
End Sub

=================================================================================
Rem Attribute VBA_ModuleType=VBAModule
Option VBASupport 1
Sub addtotalfields(LastRowColA As Long, LastColRow1 As Long, SheetNr As Long)

'
' Define Total fields in sheet
'
Dim add_total_fields As Integer
add_total_fields_nr = arr_settings(HeaderLine8, 12)
If add_total_fields_nr > 3 Then add_total_fields_nr = 0
If add_total_fields_nr = 0 Then Exit Sub

Dim incl_cont_weight As Integer


incl_cont_weight_nr = arr_settings(HeaderLine8, 77)
If incl_cont_weight_nr > 3 Then incl_cont_weight_nr = 0

'
' First define which are the first 3 visible columns
'
Dim col_nr As Integer
ReDim ColPos_sorted(1 To Col_ArraySize) As Integer

'
'all col-positions in order (first column first, then second, etc)
For iCounter = 1 To Col_ArraySize
col_nr = arr_settings(HeaderLine2, iCounter) 'get column position
ColPos_sorted(col_nr) = iCounter
Next iCounter
'
'now the columns is sorted and check on for one if that columns is SHOWN
Dim COL_TOT0 As Integer, COL_TOT1 As Integer, col_tot2 As Integer
COL_TOT0 = 0
COL_TOT1 = 0
col_tot2 = 0
For iCounter = 1 To Col_ArraySize
col_nr = ColPos_sorted(iCounter)
If col_nr = 0 Then MsgBox "Warning, was not able to find a columnposition
for column " & iCounter & ". Possible cause is a non-unique description."
If arr_settings(HeaderLine3, col_nr) = "SHOW" Then
If COL_TOT0 = 0 Then
COL_TOT0 = arr_settings(HeaderLine2, col_nr) + ListStartCol - 1
Else
If COL_TOT1 = 0 Then
COL_TOT1 = arr_settings(HeaderLine2, col_nr) + ListStartCol - 1
Else
If col_tot2 = 0 Then col_tot2 = arr_settings(HeaderLine2,
col_nr) + ListStartCol - 1
End If
End If
End If
Next iCounter
'min values:
If COL_TOT0 < ListStartCol + 0 Then COL_TOT0 = ListStartCol + 0
If COL_TOT1 < ListStartCol + 1 Then COL_TOT1 = ListStartCol + 1
If col_tot2 < ListStartCol + 2 Then col_tot2 = ListStartCol + 2

'
'Put Border around it with double line and set format of cells to numbers
'
Range(Cells(LastRowColA + 7, COL_TOT1), Cells(LastRowColA + 10,
col_tot2)).Select
Call InnerNormal_OuterDouble_Border(1)
Selection.NumberFormat = "General"
Range(Cells(LastRowColA + 2, COL_TOT1), Cells(LastRowColA + 6,
col_tot2)).Select
Call InnerNormal_OuterDouble_Border(1)
Selection.NumberFormat = "General"
Range(Cells(LastRowColA + 2, COL_TOT1), Cells(LastRowColA + 19, COL_TOT1)) _
.Font.Italic = True
Range(Cells(LastRowColA + 2, col_tot2), Cells(LastRowColA + 19, col_tot2)) _
.NumberFormat = "General"

'
' Fill total fields onto sheet
'
Dim mm As Integer
Dim Cel_Formula1 As String, Cel_Formula2 As String, Cel_Formula3 As String
Dim Cel_Formula4 As String, Cel_Formula5 As String
Dim Cel_Formtxt1 As String, Cel_Formtxt2 As String, Cel_Formtxt3 As String
Dim Cel_Formtxt4 As String, Cel_Formtxt5 As String
Dim COL_char As String, COL_char_sum As String, COL_char_sum_cont As String
Dim TotLen As Double

'Unit in mm or meters, because total length is alway is Meters,


'so should be divided to 1000 only in case length is in mm
If Trim(arr_settings(HeaderLine8, 15)) = "1" Then
mm = 1
Else
mm = 1000
End If

If Columns(col_tot2).EntireColumn.Hidden = True Then col_tot2 = col_tot2 + 1

col_nr = arr_settings(HeaderLine2, COL_LEN) 'get column position


col_nr = col_nr + ListStartCol - 1
COL_char = Column2Char(col_nr)
Cel_Formula1 = "=ROUND(SUM(" & COL_char & ListStartLine & _
":" & COL_char & LastRowColA & ")/" & mm & ",2)"
Cel_Formtxt1 = "=ROUND(SUM(" & COL_char & ListStartLine & _
":" & COL_char & LastRowColA & ")/" & mm & ",2)& TEXT(""
m"",0)"
Cells(LastRowColA + 2, COL_TOT1).Value = " Total Length"
Cells(LastRowColA + 2, col_tot2).Formula = Cel_Formtxt1
Cells(LastRowColA + 11, COL_TOT1).Value = " Total Length"
Cells(LastRowColA + 11, col_tot2).Formula = Cel_Formula1

TotLen = WorksheetFunction.Sum(Range(Cells(ListStartLine, col_nr),


Cells(LastRowColA, col_nr))) 'Sum Column LEN

If TotLen < 0.1 Then


'clear Total length cell because value is 0
Cells(LastRowColA + 2, COL_TOT1).Value = " "
Cells(LastRowColA + 2, col_tot2).Value = " "
Cells(LastRowColA + 11, COL_TOT1).Value = " "
Cells(LastRowColA + 11, col_tot2).Value = " "
End If

' Define COL_char of the Weight and of the Total Weight (incl content weight)
'
col_nr = arr_settings(HeaderLine2, COL_MAS) 'get column position
col_nr = col_nr + ListStartCol - 1
COL_char_sum = Column2Char(col_nr)
'
col_nr = arr_settings(HeaderLine2, COL_TOTM) 'get column position
col_nr = col_nr + ListStartCol - 1
COL_char_sum_cont = Column2Char(col_nr)

'temp. put weight sum in field to be used to check if this value >0
Cel_Formula2 = "=SUM(" & COL_char_sum & ListStartLine & ":" & _
COL_char_sum & LastRowColA & ")"
Cells(LastRowColA + 3, col_tot2).Formula = Cel_Formula2

If Cells(LastRowColA + 3, col_tot2).Value > 0.1 Then


'Only show 'Total COG' if 'Total Mass' > 0, (to avoid dividing by 0)

'Total COG X
col_nr = arr_settings(HeaderLine2, COL_CGX) 'get column position
col_nr = col_nr + ListStartCol - 1
COL_char = Column2Char(col_nr)
Cells(LastRowColA + 4, COL_TOT1).Value = " COG x"
Cells(LastRowColA + 13, COL_TOT1).Value = " COG x"
Cel_Formtxt3 = _
"=ROUND(SUMPRODUCT(" & COL_char & ListStartLine & ":" & COL_char & _
LastRowColA & "," & COL_char_sum & ListStartLine & ":" & _
COL_char_sum & LastRowColA & " )/ SUM(" & COL_char_sum & _
ListStartLine & ":" & COL_char_sum & LastRowColA & _
")/" & mm & ",2)& TEXT("" m"",0)"
Cel_Formula3 = _
"=ROUND(SUMPRODUCT(" & COL_char & ListStartLine & ":" & COL_char & _
LastRowColA & "," & COL_char_sum & ListStartLine & ":" & _
COL_char_sum & LastRowColA & " )/ SUM(" & COL_char_sum & _
ListStartLine & ":" & COL_char_sum & LastRowColA & _
")/" & mm & ",2)"
Cells(LastRowColA + 4, col_tot2).Formula = Cel_Formtxt3
Cells(LastRowColA + 13, col_tot2).Formula = Cel_Formula3

'Total COG X (incl. content weight)


col_nr = arr_settings(HeaderLine2, COL_TOTX) 'get column position
col_nr = col_nr + ListStartCol - 1
COL_char = Column2Char(col_nr)
Cells(LastRowColA + 8, COL_TOT1).Value = " COG x (incl. content weight)"
Cells(LastRowColA + 17, COL_TOT1).Value = " COG x (incl. content weight)"
Cel_Formtxt3 = _
"=ROUND(SUMPRODUCT(" & COL_char & ListStartLine & ":" & COL_char & _
LastRowColA & "," & COL_char_sum_cont & ListStartLine & ":" & _
COL_char_sum_cont & LastRowColA & " )/ SUM(" & COL_char_sum_cont & _
ListStartLine & ":" & COL_char_sum_cont & LastRowColA & _
")/" & mm & ",2)& TEXT("" m"",0)"
Cel_Formula3 = _
"=ROUND(SUMPRODUCT(" & COL_char & ListStartLine & ":" & COL_char & _
LastRowColA & "," & COL_char_sum_cont & ListStartLine & ":" & _
COL_char_sum_cont & LastRowColA & " )/ SUM(" & COL_char_sum_cont & _
ListStartLine & ":" & COL_char_sum_cont & LastRowColA & _
")/" & mm & ",2)"
Cells(LastRowColA + 8, col_tot2).Formula = Cel_Formtxt3
Cells(LastRowColA + 17, col_tot2).Formula = Cel_Formula3

'Total COG Y
col_nr = arr_settings(HeaderLine2, COL_CGY) 'get column position
col_nr = col_nr + ListStartCol - 1
COL_char = Column2Char(col_nr)
Cells(LastRowColA + 5, COL_TOT1).Value = " COG y"
Cells(LastRowColA + 14, COL_TOT1).Value = " COG y"
Cel_Formtxt4 = _
"=ROUND(SUMPRODUCT(" & COL_char & ListStartLine & ":" & COL_char & _
LastRowColA & "," & COL_char_sum & ListStartLine & ":" & _
COL_char_sum & LastRowColA & " )/ SUM(" & COL_char_sum & _
ListStartLine & ":" & COL_char_sum & LastRowColA & _
")/" & mm & ",2)& TEXT("" m"",0)"
Cel_Formula4 = _
"=ROUND(SUMPRODUCT(" & COL_char & ListStartLine & ":" & COL_char & _
LastRowColA & "," & COL_char_sum & ListStartLine & ":" & _
COL_char_sum & LastRowColA & " )/ SUM(" & COL_char_sum & _
ListStartLine & ":" & COL_char_sum & LastRowColA & _
")/" & mm & ",2)"
Cells(LastRowColA + 5, col_tot2).Formula = Cel_Formtxt4
Cells(LastRowColA + 14, col_tot2).Formula = Cel_Formula4

'Total COG Y (incl. content weight)


col_nr = arr_settings(HeaderLine2, COL_TOTY) 'get column position
col_nr = col_nr + ListStartCol - 1
COL_char = Column2Char(col_nr)
Cells(LastRowColA + 9, COL_TOT1).Value = " COG y (incl. content weight)"
Cells(LastRowColA + 18, COL_TOT1).Value = " COG y (incl. content weight)"
Cel_Formtxt4 = _
"=ROUND(SUMPRODUCT(" & COL_char & ListStartLine & ":" & COL_char & _
LastRowColA & "," & COL_char_sum_cont & ListStartLine & ":" & _
COL_char_sum_cont & LastRowColA & " )/ SUM(" & COL_char_sum_cont & _
ListStartLine & ":" & COL_char_sum_cont & LastRowColA & _
")/" & mm & ",2)& TEXT("" m"",0)"
Cel_Formula4 = _
"=ROUND(SUMPRODUCT(" & COL_char & ListStartLine & ":" & COL_char & _
LastRowColA & "," & COL_char_sum_cont & ListStartLine & ":" & _
COL_char_sum_cont & LastRowColA & " )/ SUM(" & COL_char_sum_cont & _
ListStartLine & ":" & COL_char_sum_cont & LastRowColA & _
")/" & mm & ",2)"
Cells(LastRowColA + 9, col_tot2).Formula = Cel_Formtxt4
Cells(LastRowColA + 18, col_tot2).Formula = Cel_Formula4

'Total COG Z
col_nr = arr_settings(HeaderLine2, COL_CGZ) 'get column position
col_nr = col_nr + ListStartCol - 1
COL_char = Column2Char(col_nr)
Cells(LastRowColA + 6, COL_TOT1).Value = " COG z"
Cells(LastRowColA + 15, COL_TOT1).Value = " COG z"
Cel_Formtxt5 = _
"=ROUND(SUMPRODUCT(" & COL_char & ListStartLine & ":" & COL_char & _
LastRowColA & "," & COL_char_sum & ListStartLine & ":" & _
COL_char_sum & LastRowColA & " )/ SUM(" & COL_char_sum & _
ListStartLine & ":" & COL_char_sum & LastRowColA & _
")/" & mm & ",2)& TEXT("" m"",0)"
Cel_Formula5 = _
"=ROUND(SUMPRODUCT(" & COL_char & ListStartLine & ":" & COL_char & _
LastRowColA & "," & COL_char_sum & ListStartLine & ":" & _
COL_char_sum & LastRowColA & " )/ SUM(" & COL_char_sum & _
ListStartLine & ":" & COL_char_sum & LastRowColA & _
")/" & mm & ",2)"
Cells(LastRowColA + 6, col_tot2).Formula = Cel_Formtxt5
Cells(LastRowColA + 15, col_tot2).Formula = Cel_Formula5

'Total COG Z (incl. content weight)


col_nr = arr_settings(HeaderLine2, COL_TOTZ) 'get column position
col_nr = col_nr + ListStartCol - 1
COL_char = Column2Char(col_nr)
Cells(LastRowColA + 10, COL_TOT1).Value = " COG z (incl. content weight)"
Cells(LastRowColA + 19, COL_TOT1).Value = " COG z (incl. content weight)"
Cel_Formtxt5 = _
"=ROUND(SUMPRODUCT(" & COL_char & ListStartLine & ":" & COL_char & _
LastRowColA & "," & COL_char_sum_cont & ListStartLine & ":" & _
COL_char_sum_cont & LastRowColA & " )/ SUM(" & COL_char_sum_cont & _
ListStartLine & ":" & COL_char_sum_cont & LastRowColA & _
")/" & mm & ",2)& TEXT("" m"",0)"
Cel_Formula5 = _
"=ROUND(SUMPRODUCT(" & COL_char & ListStartLine & ":" & COL_char & _
LastRowColA & "," & COL_char_sum_cont & ListStartLine & ":" & _
COL_char_sum_cont & LastRowColA & " )/ SUM(" & COL_char_sum_cont & _
ListStartLine & ":" & COL_char_sum_cont & LastRowColA & _
")/" & mm & ",2)"
Cells(LastRowColA + 10, col_tot2).Formula = Cel_Formtxt5
Cells(LastRowColA + 19, col_tot2).Formula = Cel_Formula5

Else
Cells(LastRowColA + 4, COL_TOT1).Value = " "
Cells(LastRowColA + 4, col_tot2).Value = " "
Cells(LastRowColA + 5, COL_TOT1).Value = " "
Cells(LastRowColA + 5, col_tot2).Value = " "
Cells(LastRowColA + 6, COL_TOT1).Value = " "
Cells(LastRowColA + 6, col_tot2).Value = " "

Cells(LastRowColA + 13, COL_TOT1).Value = " "


Cells(LastRowColA + 13, col_tot2).Value = " "
Cells(LastRowColA + 14, COL_TOT1).Value = " "
Cells(LastRowColA + 14, col_tot2).Value = " "
Cells(LastRowColA + 15, COL_TOT1).Value = " "
Cells(LastRowColA + 15, col_tot2).Value = " "

Cells(LastRowColA + 8, COL_TOT1).Value = " "


Cells(LastRowColA + 8, col_tot2).Value = " "
Cells(LastRowColA + 9, COL_TOT1).Value = " "
Cells(LastRowColA + 9, col_tot2).Value = " "
Cells(LastRowColA + 10, COL_TOT1).Value = " "
Cells(LastRowColA + 10, col_tot2).Value = " "

Cells(LastRowColA + 17, COL_TOT1).Value = " "


Cells(LastRowColA + 17, col_tot2).Value = " "
Cells(LastRowColA + 18, COL_TOT1).Value = " "
Cells(LastRowColA + 18, col_tot2).Value = " "
Cells(LastRowColA + 19, COL_TOT1).Value = " "
Cells(LastRowColA + 19, col_tot2).Value = " "

Rows(LastRowColA + 4 & ":" & LastRowColA + 6).EntireRow.Hidden = True


Rows(LastRowColA + 8 & ":" & LastRowColA + 10).EntireRow.Hidden = True
End If

' Weight
Cells(LastRowColA + 3, COL_TOT1).Value = " Total Weight"
Cells(LastRowColA + 12, COL_TOT1).Value = " Total Weight"
Cells(LastRowColA + 3, col_tot2).Formula = _
"=ROUND(SUM(" & COL_char_sum & ListStartLine & ":" & COL_char_sum & _
LastRowColA & "),1)& TEXT("" Kg"",0)"
Cells(LastRowColA + 12, col_tot2).Formula = _
"=ROUND(SUM(" & COL_char_sum & ListStartLine & ":" & COL_char_sum & _
LastRowColA & "),1)"
' Weight (incl. content weight)
Cells(LastRowColA + 7, COL_TOT1).Value = " Total Weight (incl. content)"
Cells(LastRowColA + 16, COL_TOT1).Value = " Total Weight (incl. content)"
Cells(LastRowColA + 7, col_tot2).Formula = _
"=ROUND(SUM(" & COL_char_sum_cont & ListStartLine & ":" & COL_char_sum_cont
& _
LastRowColA & "),1)& TEXT("" Kg"",0)"
Cells(LastRowColA + 16, col_tot2).Formula = _
"=ROUND(SUM(" & COL_char_sum_cont & ListStartLine & ":" & COL_char_sum_cont
& _
LastRowColA & "),1)"

Rows(LastRowColA + 11 & ":" & LastRowColA + 19).EntireRow.Hidden = True


If add_total_fields_nr = 2 Then
Rows(LastRowColA + 2 & ":" & LastRowColA + 6).EntireRow.Hidden = True
End If

If incl_cont_weight_nr = 0 Or incl_cont_weight_nr = 2 Then


Rows(LastRowColA + 7 & ":" & LastRowColA + 10).EntireRow.Hidden = True
Else
Rows(LastRowColA + 7 & ":" & LastRowColA + 10).EntireRow.Hidden = False
End If

'
Dim curr_sheetn As String
curr_sheetn = ActiveSheet.Name
TotalFields(SheetNr, 1) = curr_sheetn
TotalFields(SheetNr, 2) = "='" & curr_sheetn & "'!" & Cells(LastRowColA + 11,
col_tot2).Address
TotalFields(SheetNr, 3) = "='" & curr_sheetn & "'!" & Cells(LastRowColA + 12,
col_tot2).Address
TotalFields(SheetNr, 4) = "='" & curr_sheetn & "'!" & Cells(LastRowColA + 13,
col_tot2).Address
TotalFields(SheetNr, 5) = "='" & curr_sheetn & "'!" & Cells(LastRowColA + 14,
col_tot2).Address
TotalFields(SheetNr, 6) = "='" & curr_sheetn & "'!" & Cells(LastRowColA + 15,
col_tot2).Address
TotalFields(SheetNr, 7) = "='" & curr_sheetn & "'!" & Cells(LastRowColA + 16,
col_tot2).Address
TotalFields(SheetNr, 8) = "='" & curr_sheetn & "'!" & Cells(LastRowColA + 17,
col_tot2).Address
TotalFields(SheetNr, 9) = "='" & curr_sheetn & "'!" & Cells(LastRowColA + 18,
col_tot2).Address
TotalFields(SheetNr, 10) = "='" & curr_sheetn & "'!" & Cells(LastRowColA + 19,
col_tot2).Address
TotalFields(SheetNr, 11) = ""
TotalFields(SheetNr, 12) = ""

End Sub

Sub sheet_total(SheetNr As Long)

Dim add_total_fields As Integer


add_total_fields_nr = arr_settings(HeaderLine8, 12)
If add_total_fields_nr > 3 Then add_total_fields_nr = 0
If add_total_fields_nr = 0 Then Exit Sub
If add_total_fields_nr = 1 Then Exit Sub

Dim incl_cont_weight As Integer


incl_cont_weight_nr = arr_settings(HeaderLine8, 77)
If incl_cont_weight_nr > 3 Then incl_cont_weight_nr = 0

If Not WorksheetExists("TOTAL") Then Exit Sub


Sheets("TOTAL").Activate

Dim startrow As Integer, startcol As Integer, endrow As Long, endcol As Integer


Dim Hlink As String, Hlink_txt As String
startrow = 9
startcol = 2
endrow = startrow + SheetNr - 1
endcol = startcol + UBound(TotalFields, 2) - 1
Range(Cells(startrow, startcol), Cells(endrow, endcol)).Formula = TotalFields

For rr = 1 To SheetNr
Hlink = "'" & TotalFields(rr, 1) & "'!A1"
Hlink_txt = TotalFields(rr, 1)
ActiveSheet.Hyperlinks.Add _
Anchor:=Cells(startrow + rr - 1, startcol + 12 - 1), Address:="", _
SubAddress:=Hlink, TextToDisplay:=Hlink_txt
Next rr

'
' Fill total fields onto sheet
'
Dim Cel_Formula1 As String, Cel_Formula2 As String, Cel_Formula3 As String
Dim Cel_Formula4 As String, Cel_Formula5 As String
Dim Cel_Formtxt1 As String, Cel_Formtxt2 As String, Cel_Formtxt3 As String
Dim Cel_Formtxt4 As String, Cel_Formtxt5 As String
Dim COL_char As String, COL_char2 As String, COL_char_sum As String
Dim TotLen As Double, COL_char_sum_cont As String
Dim col_tot As Integer, col_tot2 As Integer, row_tot As Integer, col_nr As
Integer

col_tot = 4
col_tot2 = 9
row_tot = 2
col_nr = col_tot - 1
COL_char = Column2Char(col_nr)
Cel_Formula1 = "=ROUND(SUM(" & COL_char & startrow & _
":" & COL_char & endrow & "),2)& TEXT("" m"",0)"
Cells(row_tot, col_tot).Formula = Cel_Formula1

TotLen = WorksheetFunction.Sum(Range(Cells(startrow, col_nr), Cells(endcol,


col_nr))) 'Sum Column LEN

If TotLen < -0.1 Then


'clear Total length cell because value is 0
Cells(row_tot, col_tot).Value = ""
End If

'temp. put weight sum in field to be used to check if this value >0
col_nr = startcol + 3 - 1
COL_char_sum = Column2Char(col_nr)
Cel_Formula2 = "=SUM(" & COL_char_sum & startrow & ":" & _
COL_char_sum & endrow & ")"
Cells(row_tot + 1, col_tot).Formula = Cel_Formula2

If Cells(row_tot + 1, col_tot).Value > 0.1 Then


'Only show 'Total COG' if 'Total Mass' > 0, (to avoid dividing by 0)

col_nr = startcol + 7 - 1
COL_char_sum_cont = Column2Char(col_nr)

'Total COG X
col_nr = startcol + 4 - 1
COL_char = Column2Char(col_nr)
Cel_Formula3 = _
"=ROUND(SUMPRODUCT(" & COL_char & startrow & ":" & COL_char & _
endrow & "," & COL_char_sum & startrow & ":" & _
COL_char_sum & endrow & " )/ SUM(" & COL_char_sum & _
startrow & ":" & COL_char_sum & endrow & _
"),2)& TEXT("" m"",0)"
Cells(row_tot + 2, col_tot).Formula = Cel_Formula3

'Total COG X (incl. content weight)


col_nr = startcol + 8 - 1
COL_char = Column2Char(col_nr)
Cel_Formula3 = _
"=ROUND(SUMPRODUCT(" & COL_char & startrow & ":" & COL_char & _
endrow & "," & COL_char_sum_cont & startrow & ":" & _
COL_char_sum_cont & endrow & " )/ SUM(" & COL_char_sum_cont & _
startrow & ":" & COL_char_sum_cont & endrow & _
"),2)& TEXT("" m"",0)"
Cells(row_tot + 2, col_tot2).Formula = Cel_Formula3

'Total COG Y
col_nr = startcol + 5 - 1
COL_char = Column2Char(col_nr)
Cel_Formula4 = _
"=ROUND(SUMPRODUCT(" & COL_char & startrow & ":" & COL_char & _
endrow & "," & COL_char_sum & startrow & ":" & _
COL_char_sum & endrow & " )/ SUM(" & COL_char_sum & _
startrow & ":" & COL_char_sum & endrow & _
"),2)& TEXT("" m"",0)"
Cells(row_tot + 3, col_tot).Formula = Cel_Formula4

'Total COG Y (incl. content weight)


col_nr = startcol + 9 - 1
COL_char = Column2Char(col_nr)
Cel_Formula4 = _
"=ROUND(SUMPRODUCT(" & COL_char & startrow & ":" & COL_char & _
endrow & "," & COL_char_sum_cont & startrow & ":" & _
COL_char_sum_cont & endrow & " )/ SUM(" & COL_char_sum_cont & _
startrow & ":" & COL_char_sum_cont & endrow & _
"),2)& TEXT("" m"",0)"
Cells(row_tot + 3, col_tot2).Formula = Cel_Formula4

'Total COG Z
col_nr = startcol + 6 - 1
COL_char = Column2Char(col_nr)
Cel_Formula5 = _
"=ROUND(SUMPRODUCT(" & COL_char & startrow & ":" & COL_char & _
endrow & "," & COL_char_sum & startrow & ":" & _
COL_char_sum & endrow & " )/ SUM(" & COL_char_sum & _
startrow & ":" & COL_char_sum & endrow & _
"),2)& TEXT("" m"",0)"
Cells(row_tot + 4, col_tot).Formula = Cel_Formula5

'Total COG Z (incl. content weight)


col_nr = startcol + 10 - 1
COL_char = Column2Char(col_nr)
Cel_Formula5 = _
"=ROUND(SUMPRODUCT(" & COL_char & startrow & ":" & COL_char & _
endrow & "," & COL_char_sum_cont & startrow & ":" & _
COL_char_sum_cont & endrow & " )/ SUM(" & COL_char_sum_cont & _
startrow & ":" & COL_char_sum_cont & endrow & _
"),2)& TEXT("" m"",0)"
Cells(row_tot + 4, col_tot2).Formula = Cel_Formula5

Else
Cells(row_tot + 2, col_tot).Value = ""
Cells(row_tot + 3, col_tot).Value = ""
Cells(row_tot + 4, col_tot).Value = ""
Cells(row_tot, col_tot2).Value = ""
Cells(row_tot, col_tot2).Value = ""
Cells(row_tot, col_tot2).Value = ""
Rows(endrow + 2 & ":" & endrow + 4).EntireRow.Hidden = True
End If

'weight
Cells(row_tot + 1, col_tot).Formula = _
"=ROUND(SUM(" & COL_char_sum & startrow & ":" & COL_char_sum & _
endrow & "),1)& TEXT("" Kg"",0)"

'weight (incl. content weight)


Cells(row_tot + 1, col_tot2).Formula = _
"=ROUND(SUM(" & COL_char_sum_cont & startrow & ":" & COL_char_sum_cont & _
endrow & "),1)& TEXT("" Kg"",0)"

'
'fill title of the column that contains the sheet-values
'
Dim sett As String, distr_col_name As String
sett = arr_settings(HeaderLine8, 1)
SheetDistr_Nr = conv_to_number(sett)
If SheetDistr_Nr <> 0 Then
distr_col_name = arr_settings(HeaderLine10, SheetDistr_Nr) 'get column desc
Else
distr_col_name = "Sheet"
End If

Cells(startrow - 1, startcol).Value = distr_col_name & Chr(10) 'e.G "System"


and <enter>

Dim endrow_b As Long


endrow_b = endrow
If endrow_b = startrow Then endrow_b = endrow + 1
Range(Cells(startrow, startcol), Cells(endrow_b, startcol + 10 - 1)).Select
Call NormalBorder(1)

' Hide the content colums


COL_char = Column2Char(startcol + 7 - 1)
COL_char2 = Column2Char(startcol + 10 - 1)
If incl_cont_weight_nr = 0 Or incl_cont_weight_nr = 1 Then
Columns(COL_char & ":" & COL_char2).EntireColumn.Hidden = True
Else
Columns(COL_char & ":" & COL_char2).EntireColumn.Hidden = False
End If

Cells(1, 1).Select 'just select "A1" in order to get active cel to so far down
End Sub

Sub totalsheet_clear(arg As Integer)


Dim startrow As Integer, endrow As Long, nr_of_rows As Long
Sheets("TOTAL").Activate
startrow = 9
endrow = Range("B65536").End(xlUp).row
nr_of_rows = endrow - startrow + 1
If nr_of_rows < 1 Then Exit Sub
Rows(startrow & ":" & endrow).Delete

End Sub
=============================================================================
Rem Attribute VBA_ModuleType=VBAModule
Option VBASupport 1
'
' eBrowser related stuff
'

Sub EbrowserInitialize(load_ebr As Boolean, incl_setup_ref As Boolean)

EbrowserInitialized = False
If Not WorksheetExists(eBrowserSheet) Then Exit Sub
Dim eb_file As String, Sh As String, cl As String, isLoaded
eb_file = arr_settings(HeaderLine8, 83)
If eb_file = "" Or File_Exists(eb_file) = False Then Exit Sub

Application.ScreenUpdating = False
Sh = ActiveSheet.Name
cl = ActiveCell.Address

If EbrowserObjectsIsAvailable(incl_setup_ref) = False Then


Call sheet_sel(Sh)
Range(cl).Select
Application.ScreenUpdating = True
Exit Sub
End If

With Sheets(eBrowserSheet).OLEObjects(eb_objname)
.Object.ptyModelFileName = "file:///" & eb_file
.Object.ptyAutoInit = False 'otherwise error when going to ebrowser
sheet! and search in ebm remains in loop
.Object.mthIsModelDataLoaded isLoaded
If isLoaded = True Then
EbrowserInitialized = True
Else
If load_ebr = True Then
Application.StatusBar = "Initializing eBrowser"
'do an Activate and InitializeAndDraw (both! and also in this
order!)
.Activate
.Object.mthInitializeAndDraw
.Object.mthEnableObjectEvents "Find Object in Report;", "xml"
Application.StatusBar = False 'Clear previous statusbar text
EbrowserInitialized = True
End If
End If
End With

Call sheet_sel(Sh)
Range(cl).Select
Application.ScreenUpdating = True
End Sub

Sub set_size_eb_object(arg As Integer)


'set size of eBrowser object to visible range of the sheet
Dim L As Integer, h As Integer, W As Integer, extra_edge As Integer,
extra_edge_W As Integer
If Sheets(eBrowserSheet).Cells(1, 1).Value = "button" Then
L = 16
Else
L = 0
End If
extra_edge_H = 6
extra_edge_W = 40 + L
h = ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Height -
extra_edge_H
W = ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Width -
extra_edge_W

With Sheets(eBrowserSheet).Buttons(1)
.Height = h
End With
With Sheets(eBrowserSheet).OLEObjects(eb_objname)
.Left = L
.Top = 0
.Height = h
.Width = W
End With

End Sub

Sub search_eb_object(arg As String)


Call EbrowserInitialize(True, False) 'initialize the connection to the
eBrowserfile

If EbrowserInitialized = False Then


Sheets(eBrowserSheet).Visible = False
Exit Sub
End If

Dim Act_Sheet As String, Act_SheetIndex As Integer, Act_Cell As String,


Act_Cell_r As Long
Dim field_vpo As String, Act_Cell_c As Integer, positionID As String, ObjectID
As String
Dim ColName As String, ObiRef As String, COL_OBIREF As Integer, col As Integer
Dim OneObi As String
Act_Sheet = ActiveSheet.Name
Act_SheetIndex = ActiveSheet.index
Act_Cell = ActiveCell.Address
Act_Cell_r = ActiveCell.row
Act_Cell_c = ActiveCell.Column
ColName = GetCurrentColumnName(Act_Cell_c)
If ColName = "" Then Exit Sub

positionID = get_positionID(Act_Cell_r)
If positionID <> "" Then
Call activate_ebrowser_sheet(Act_Sheet, Act_Cell)
Call FindPosID(positionID)
Call set_size_eb_object(1)
Exit Sub
End If

col = conv_to_number("COL_OBIREF")
If col <> 0 Then
col = arr_settings(HeaderLine2, col) + ListStartCol - 1 'get column
position
ObiRef = Act_SheetIndex & "_" & Cells(Act_Cell_r, col).Value
OneObi = ""
If FindObirefFromImportList(ObiRef, OneObi) = True Then
Call activate_ebrowser_sheet(Act_Sheet, Act_Cell)
Call ShowObirefInEbrowser(OneObi)
Call set_size_eb_object(1)
Else
' nothing found (for instance because of no obi at slaveparts)
Call sheet_sel(Act_Sheet)
Range(Act_Cell).Select
End If
Else
MsgBox "ReportGenerator debug f2" 'actually this should not occur, else:
find out what the leak is
End If

End Sub

Function get_positionID(RowNr As Long) As String


Dim field_vpo_c As Integer, field_nam_c As Integer, field_ipo_c As Integer, col
As Integer
get_positionID = ""

col = conv_to_number("COL_VPO")
If col <> 0 Then
field_vpo_c = arr_settings(HeaderLine2, col) + ListStartCol - 1
get_positionID = Cells(RowNr, field_vpo_c).Value
If get_positionID <> "" Then Exit Function
End If

col = conv_to_number("COL_NAM")
If col <> 0 Then
field_nam_c = arr_settings(HeaderLine2, col) + ListStartCol - 1
get_positionID = Cells(RowNr, field_nam_c).Value
If get_positionID <> "" Then Exit Function
End If

col = conv_to_number("COL_IPO")
If col <> 0 Then
field_ipo_c = arr_settings(HeaderLine2, col) + ListStartCol - 1
get_positionID = Cells(RowNr, field_ipo_c).Value
If get_positionID <> "" Then Exit Function
End If
End Function

Function get_objectID(RowNr As Long) As String


Dim field_obi_c As Integer, col As Integer
get_objectID = ""
col = conv_to_number("COL_OBI")
If col <> 0 Then
field_obi_c = arr_settings(HeaderLine2, col) + ListStartCol - 1
get_objectID = Cells(RowNr, field_obi_c).Value
If get_objectID <> "" Then Exit Function
End If
End Function

Sub activate_ebrowser_sheet(Act_Sheet As String, Act_Cell As String)


Sheets(eBrowserSheet).Visible = True
Sheets(eBrowserSheet).Activate
On Error Resume Next
Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthExitExamineMode ' works
from v6
On Error GoTo 0

Call set_size_eb_object(1)
Sheets(eBrowserSheet).Cells(1, 1).Value = "button"
Sheets(eBrowserSheet).Cells(1, 2).Value = Act_Sheet
Sheets(eBrowserSheet).Cells(1, 3).Value = Act_Cell
End Sub
Sub FindPosID(positionID As String)
Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthLocateByPosition
positionID, 0
Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthShowSidebar (True)
End Sub

Sub FindObjID(ObjectID As String)


Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthLocateById ObjectID
'ObjectId is now found, but in tree is still the last PositionId and also in
top of window
' there is the text about examining that PostionID. This is confusing: so
therefor we hide
'the eBrowser-mthShowSidebar
Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthShowSidebar (False)
End Sub

Function EbrowserObjectsIsAvailable(incl_setup_ref As Boolean) As Boolean


EbrowserObjectsIsAvailable = False
For Each eb_shape In Sheets(eBrowserSheet).Shapes
If eb_shape.Name = eb_objname Then
EbrowserObjectsIsAvailable = True
Exit For
End If
Next eb_shape

If EbrowserObjectsIsAvailable = True Then Exit Function


Sheets(eBrowserSheet).Visible = True
Sheets(eBrowserSheet).Select

If AddEbrowserObject(1) = True Then


EbrowserObjectsIsAvailable = True
Exit Function
End If

If incl_setup_ref = False Then


Sheets(eBrowserSheet).Visible = True
Exit Function
End If

If AddEbrowserReference(1) = False Then


Exit Function
End If

If AddEbrowserObject(1) = True Then


EbrowserObjectsIsAvailable = True
Exit Function
End If
Sheets(eBrowserSheet).Visible = False
MsgBox "Not succeeded to Add Ebrowser object"
End Function

Function AddEbrowserObject(arg As String) As Boolean


Dim ebrowser_object As OLEObject, h As Integer, extra_edge As Integer,
extra_edge_W As Integer
h = ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Height
extra_edge_H = 6
extra_edge_W = 40

On Error Resume Next


Set ebrowser_object =
ActiveSheet.OLEObjects.Add(classtype:="ebrowser.eBrowser.1", Link:=False, _
DisplayAsIcon:=False, _
Left:=0, Top:=0, _

Width:=ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Width -
extra_edge_H, _

Height:=ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Height -
extra_edge_W)
ebrowser_object.Name = eb_objname
If Err = 0 Then
AddEbrowserObject = True
Else
AddEbrowserObject = False
End If
On Error GoTo 0 ' set back to the default error handling in VB
End Function

Sub setup_eBrowserSheet_____this_function_is_not_used(arg As Integer)


If WorksheetExists(eBrowserSheet) Then Exit Sub
' actually this sheet is already defined as default (incl OLEobject and buton)

Dim remembered_activesheetname As String, remembered_activecell As String


Dim eb_file As String, RememberCurDir As String, ebrowser_object As OLEObject
Dim extra_edge As Integer, extra_edge_W As Integer
remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address

Sheets.Add 'Add new sheet


ActiveSheet.Name = eBrowserSheet 'Rename new sheet
ActiveSheet.Tab.ColorIndex = 41 ' some color
ActiveSheet.Move Before:=Sheets(1) 'move sheet to be first sheet
With ActiveWindow
.DisplayGridlines = False
.DisplayHeadings = False
End With

Dim btn As Button, h As Integer


h = ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Height
Set btn = ActiveSheet.Buttons.Add(Left:=0, Top:=0, Width:=16, Height:=h)
btn.Caption = "<<" 'buttontext
btn.Font.Bold = True
btn.Font.Underline = True
btn.OnAction = "button_switch_back_to_sheet"

extra_edge_H = 6
extra_edge_W = 25
Set ebrowser_object =
ActiveSheet.OLEObjects.Add(classtype:="ebrowser.eBrowser.1", Link:=False, _
DisplayAsIcon:=False, _
Left:=0, Top:=0, _

Width:=ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Width -
extra_edge_H, _

Height:=ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Height -
extra_edge_W)
ebrowser_object.Name = eb_objname

Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select
End Sub

'
' 'ask for location of eBrowserfile
'
Function get_ebfile() As String
Dim eb_file As String
If WorksheetExists(eBrowserSheet) Then
eb_file = arr_settings(HeaderLine8, 83)
Else
eb_file = ""
End If
If eb_file <> "" And File_Exists(eb_file) = True Then
If MsgBox("Connect to eBrowser-file:" & Chr(10) & Chr(10) & "< " & eb_file
& " >" & Chr(10) & _
Chr(10) & "OK ?" & Chr(10), _
vbQuestion + vbYesNo, "eBrowser link") = vbNo Then
'ask user to select the eBrowser file
eb_file = Application.GetOpenFilename("Select eBrowser file
(*.ebm), *.ebm")
End If
Else
Dim fname_tmp As String
fname_tmp = ThisWorkbook.Name
fname_tmp = ThisWorkbook.Path & "\" & Left(fname_tmp, Len(fname_tmp) - 4) &
".ebm"
If File_Exists(fname_tmp) Then
eb_file = fname_tmp
If MsgBox("Connect to eBrowser-file:" & Chr(10) & Chr(10) & "< " &
eb_file & " >" & Chr(10) & _
Chr(10) & "OK ?" & Chr(10), _
vbQuestion + vbYesNo, "eBrowser link") = vbNo Then
'ask user to select the eBrowser file
eb_file = Application.GetOpenFilename("Select eBrowser file
(*.ebm), *.ebm")
End If
Else
MsgBox "Could not find eBrowser-file <" & eb_file & " >"
'ask user to select the eBrowser file:
eb_file = Application.GetOpenFilename("Select eBrowser file (*.ebm),
*.ebm")
End If
End If

If eb_file <> "" And File_Exists(eb_file) = True Then


get_ebfile = eb_file
arr_settings(HeaderLine8, 83) = eb_file 'store eb_file
End If
End Function

Sub switch_to_eBrowsersheet(WithButton As Boolean)


If WithButton = True And ActiveSheet.Name <> eBrowserSheet Then
Sheets(eBrowserSheet).Cells(1, 1).Value = "button" 'signal field
Else
Sheets(eBrowserSheet).Cells(1, 1).Value = ""
End If
Sheets(eBrowserSheet).Cells(1, 2).Value = ActiveSheet.Name
Sheets(eBrowserSheet).Cells(1, 3).Value = ActiveCell.Address
Sheets(eBrowserSheet).Visible = True
Sheets(eBrowserSheet).Activate
Call set_size_eb_object(1)
End Sub

Private Sub button_switch_back_to_sheet()


Call init(1)
Dim remembered_activesheetname As String, remembered_activecell As String
remembered_activesheetname = Sheets(eBrowserSheet).Cells(1, 2).Text
remembered_activecell = Sheets(eBrowserSheet).Cells(1, 3).Text
Call sheet_sel(remembered_activesheetname)
If remembered_activecell <> "" Then Range(remembered_activecell).Select
End Sub

Function GetCurrentColumnName(ColNr As Integer) As String


GetCurrentColumnName = ""
For col = 1 To Col_ArraySize
col_position = arr_settings(HeaderLine2, col) + ListStartCol - 1
If col_position = ColNr Then
ColName = arr_settings(HeaderLine1, col)
End If
Next col

If ColName <> "" Then GetCurrentColumnName = ColName


End Function

Sub GotoObiRef(ObiRef As String)


Dim SheetNo As Integer, SheetRowGroup As Long, SheetRow As Long
pos = InStr(ObiRef, "_")
SheetNo = Left$(ObiRef, pos - 1)
SheetRowGroup = Mid$(ObiRef, pos + 1, Len(ObiRef))
Sheets(SheetNo).Visible = True
Sheets(SheetNo).Activate
SheetRow = GetSheetRow(SheetRowGroup, SheetNo)
Sheets(SheetNo).Rows(SheetRow & ":" & SheetRow).Select
End Sub

Function GetSheetRow(SheetRowGroup As Long, SheetNo As Integer) As Long


Dim arr_SheetRowGroups As Variant 'MUST be variant
Dim LastRowColA As Long, nr_of_rows As Long, col_nr As Integer
LastRowColA = last_row_nr(ListStartLine, ListStartCol)
nr_of_rows = LastRowColA - ListStartLine + 1
col_nr = arr_settings(HeaderLine2, COL_OBIREF) 'get column position
col_nr = col_nr + ListStartCol - 1

arr_SheetRowGroups = Range(Cells(ListStartLine, col_nr), Cells(LastRowColA,


col_nr)).Value
For rCounter = 1 To nr_of_rows
If arr_SheetRowGroups(rCounter, 1) = SheetRowGroup Then
GetSheetRow = rCounter + ListStartLine - 1
Exit Function
End If
Next rCounter
GetSheetRow = 1 'just the first line as default, because nothing was found
(which actually cannot occur)
End Function

Function FindObiFromImportList(obi As String, ObiRef As String) As Boolean


' IN: obi ( objectID )
' OUT: Obiref ( for instance 8_16 )
'
Application.ScreenUpdating = False
FindObiFromImportList = False
'Preparation for keeping track of objectID references
Dim Size_arr_obi As Long
Dim arr_obi As Variant 'MUST be variant
Dim arr_ObiRef As Variant 'MUST be variant
Sheets("import").Visible = True
Sheets("import").Activate
Size_arr_obi = last_row_nr(1, 1) 'call to function last_row_nr()
Call Fill_arr_obi(arr_obi, Size_arr_obi)
Call Fill_arr_obiRef(arr_ObiRef, Size_arr_obi)
For oCounter = 1 To Size_arr_obi
searchKey = "_" & obi & "_"
searchIn = "_" & arr_obi(oCounter, 1) & "_"
If InStr(searchIn, searchKey) > 0 Then ' search by trying to find
postion
ObiRef = arr_ObiRef(oCounter, 1)
If ObiRef <> "" Then
FindObiFromImportList = True
Exit For
End If
End If
Next oCounter
Sheets("import").Visible = False
Sheets(eBrowserSheet).Visible = True
Sheets(eBrowserSheet).Activate
Application.ScreenUpdating = True
End Function

Function FindObirefFromImportList(ObiRef As String, OneObiField As String) As


Boolean
' IN: Obiref ( for instance: 8_16 )
' OUT: arr_obi ( array of objectID's )
'
Application.ScreenUpdating = False
FindObirefFromImportList = False
'Preparation for keeping track of objectID references
Dim Size_arr_obi As Long, obi_sel_no As Long, pos As Integer
obi_sel_no = 0
Dim arr_obi As Variant 'MUST be variant
Dim arr_ObiRef As Variant 'MUST be variant
Dim arr_obi_sel As Variant 'MUST be variant

Sheets("import").Visible = True
Sheets("import").Activate
Size_arr_obi = last_row_nr(1, 1) 'call to function last_row_nr()
ReDim arr_obi_sel(1 To Size_arr_obi) As String
Call Fill_arr_obi(arr_obi, Size_arr_obi)
Call Fill_arr_obiRef(arr_ObiRef, Size_arr_obi)
Sheets("import").Visible = False

For oCounter = 1 To Size_arr_obi


If arr_ObiRef(oCounter, 1) = ObiRef Then
If arr_obi(oCounter, 1) <> "" Then
obi_sel_no = obi_sel_no + 1
arr_obi_sel(obi_sel_no) = arr_obi(oCounter, 1)
End If
End If
Next oCounter

If obi_sel_no = 0 Then ' no objects in set, so exit


FindObirefFromImportList = False
Exit Function
End If

If obi_sel_no = 1 Then 'if one object in set, we can exit because that one obi
will be searched
OneObiField = arr_obi_sel(1)
pos = InStr(OneObiField, "_") ' search by trying to find postion Then, if
not found this means there is only one obi in this field
If pos = 0 Then
FindObirefFromImportList = True
Exit Function
End If
End If

If WriteObisToATextFile(arr_obi_sel, obi_sel_no) = False Then


Exit Function
End If

FindObirefFromImportList = True
Application.ScreenUpdating = True
End Function

Function WriteObisToATextFile(arr_obi_sel As Variant, obi_sel_no As Long) As


Boolean
WriteObisToATextFile = False

Dim LocalPath As String, ebm_filename As String, ObiFile As String


LocalPath = RegKeyRead("HKLM\SOFTWARE\Cadmatic\eBrowser\LocalPath")
If LocalPath = "" Or FolderExists(LocalPath) = False Then
MsgBox "Cannot find the LocalPath of the eBrowser: " & LocalPath
Exit Function
End If
ebm_filename = arr_settings(HeaderLine8, 83)
ebm_filename = GetFilenameFromPath(ebm_filename)
ebm_filename = GetFilenameWithoutExtension(ebm_filename)
ObiFile = LocalPath & "\" & ebm_filename & "\ReportGeneratorSet.set"
If File_Exists(ObiFile) = True Then
Kill ObiFile
If File_Exists(ObiFile) = True Then
MsgBox "Failed to delete file: " & ObiFile
Exit Function
End If
End If

'Open and write file


Dim str As String, obi_before As String, pos As Integer
fnum = FreeFile() 'set and open file for output
Open ObiFile For Output As fnum
For counter = 1 To obi_sel_no
str = arr_obi_sel(counter)
Do ' if there are several obi's (seperated with "_") then get them one
by one in this loop
pos = InStr(str, "_")
If pos = 0 Then
Print #fnum, str
Exit Do
Else
obi_before = Left$(str, pos - 1) ' part before the "_"
str = Mid$(str, pos + 1, Len(str)) ' part after the "_"
Print #fnum, obi_before
End If
Loop
Next counter
Close #fnum

WriteObisToATextFile = True
End Function

'reads the value for the registry key i_RegKey


'if the key cannot be found, the return value is ""
Function RegKeyRead(i_RegKey As String) As String
Dim myWS As Object
On Error Resume Next
Set myWS = CreateObject("WScript.Shell") 'access Windows scripting
RegKeyRead = myWS.RegRead(i_RegKey) 'read key from registry
End Function

Function GetFilenameFromPath(ByVal strPath As String) As String


' Returns the rightmost characters of a string upto but not including the rightmost
'\'
' e.g. 'c:\winnt\win.ini' returns 'win.ini'
If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1))
+ Right$(strPath, 1)
End If
End Function
Function GetFilenameWithoutExtension(ByVal strPath As String) As String
'get filename without extension
Dim posn As Integer
posn = InStr(strPath, ".")
If posn <> 0 Then
GetFilenameWithoutExtension = Left(strPath, posn - 1)
Else
GetFilenameWithoutExtension = strPath
End If
End Function

Sub ShowObirefInEbrowser(OneObi As String)


Dim position As Integer
position = InStr(OneObi, "_") ' search by trying to find postion Then, if not
found this means there is only one obi in this field
If OneObi <> "" And position = 0 Then
Call FindObjID(OneObi)
Exit Sub
End If

Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthEnableModel (False)
Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthSetSetVisibility
"ReportGeneratorSet", 1
'Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthShowSidebar (False)

End Sub

=================================================================
Rem Attribute VBA_ModuleType=VBAModule
Option VBASupport 1
'
' About References
' Reference to ebrowser.dll (checkin and setting up incl setting
TrustVBProject)
'

Function VB_References_OK(arg As String)

'Enable setting TrustAccessToVB (to be able use VBProject functions)


Dim SettingChanged As Boolean, RemovedBrokenEbrowserRef As Boolean
If SettingTrustAccessToVB(SettingChanged) = True Then
VB_References_OK = CheckReferences(RemovedBrokenEbrowserRef)
If SettingChanged Then Disable_TrustAccessToVB 'set setting back as it was
If RemovedBrokenEbrowserRef = True Then
Call RemoveEbrowserObject(1)
End If
End If

'Not succeeded to enable tempory the setting SettingTrustAccessToVB for some


reason (some unclear security settings?)
'anyway if there is a broken reference, an syntax error will be triggered with
below function
Call TriggerErrorInCaseOfBrokenReferences(1)

'when the program survives previous call then apparently there is no broken
references
VB_References_OK = True

End Function

Sub TriggerErrorInCaseOfBrokenReferences(arg As String)


'if this subroutine causes an error then possible cause is a broken reference.
'solution is to manually set the settings 'TrustAccess to VBProject", becuase
then program is able to delete broken ref.
Dim str As String
str = Left("abc", 1)
End Sub

Function CheckReferences(RemovedBrokenEbrowserRef As Boolean)


Dim i As Integer, RefCount As Integer, RefCounRemovedBrokenEbrowserReft As
Integer
Dim brokenrefs_arr(1 To 2, 1 To 99) As String
RemovedBrokenEbrowserRef = False
CheckReferences = True
On Error Resume Next
With ThisWorkbook.VBProject
'try to remove ebrowser reference, in case its broken
RefCount = .References.Count
For i = 1 To RefCount
If .References(i).IsBroken = True Then
brokenrefs_arr(1, i) = .References(i).Name
brokenrefs_arr(2, i) = .References(i).FullPath
.References.Remove .References(i) 'remove reference to
eBrowser.dll
End If
Next i

'check if all broken reference are now cleared an not any broken references
is left
For i = 1 To .References.Count
If .References(i).IsBroken = True Then
MsgBox "Warning, following reference is broken: " &
.References(i).Name _
& " (" & .References(i).FullPath & ")"
CheckReferences = False
End If
Next i
End With

On Error GoTo 0 ' set back to the default error handling in VB


If CheckReferences = False Then Exit Function
Call InformUserAboutRemovedRef(brokenrefs_arr, RefCount,
RemovedBrokenEbrowserRef)
End Function

Sub InformUserAboutRemovedRef(brokenrefs_arr, RefCount, RemovedBrokenEbrowserRef)


For i = 1 To RefCount
If brokenrefs_arr(2, i) <> "" Then
'see if fullpath points to ebrowser.dll
If InStr(brokenrefs_arr(2, i), "ebrowser.dll") > 0 Then
RemovedBrokenEbrowserRef = True
Else
MsgBox "Could not find the reference: " & Chr(10) & _
brokenrefs_arr(1, i) & " ( " & brokenrefs_arr(2, i) & " )" &
Chr(10) & _
"Fortunatly, removing of this broken reference has succeeded," &
Chr(10) & _
"if there will be any error in excel further on, please fix this
first." & _
"[perhaps this reference is available but onder other version
number]"
'for instance in case of other office version.
End If
End If
Next i
End Sub

Sub RemoveEbrowserObject(arg As String)


If Not WorksheetExists(eBrowserSheet) Then Exit Sub
If EbrowserObjectExists(1) = True Then
Sheets(eBrowserSheet).Shapes(eb_objname).Delete
End If
Sheets(eBrowserSheet).Visible = False
End Sub

Function EbrowserObjectExists(arg As Integer) As Boolean


Dim shape_obj As sHape
On Error Resume Next
Set shape_obj = Sheets(eBrowserSheet).Shapes(eb_objname)
On Error GoTo 0

If shape_obj Is Nothing Then


EbrowserObjectExists = False
Else
EbrowserObjectExists = True
End If
End Function

Function AddEbrowserReference(arg As String) As Boolean


AddEbrowserReference = False
Dim ebrowserDLL_file As String
If getEbrowserDLL_file(ebrowserDLL_file) = False Then
Exit Function
End If

'Enable setting TrustAccessToVB (to be able use VBProject functions)


Dim SettingChanged As Boolean, RemovedBrokenRef As Boolean
If SettingTrustAccessToVB(SettingChanged) = False Then
MsgBox "To use eBrowser link, there is needed a reference to ebrowser.dll,
" & _
Chr(10) & " first attempt to add this reference automatically did not
succeeded. " & _
Chr(10) & " Possible reason is that the setting 'Trust VBProject' is not
enabled." & _
Chr(10) & " Please enable this setting in excel ( you can google how to do
this)"
If SettingChanged Then Disable_TrustAccessToVB 'set setting back as it was
Exit Function
End If

If SettingChanged Then Disable_TrustAccessToVB 'set setting back as it was


ThisWorkbook.VBProject.References.AddFromFile ebrowserDLL_file 'Add ref.
AddEbrowserReference = True
End Function

Function getEbrowserDLL_file(ebrowserDLL_file As String) As Boolean


getEbrowserDLL_file = False
ebrowserDLL_file = Environ("SystemRoot") & "\system32\ebrowser.dll" 'v5.x
If File_Exists(ebrowserDLL_file) = True Then
getEbrowserDLL_file = True
Exit Function
End If

ebrowserDLL_file = Environ("ProgramFiles") & "\Cadmatic\ebrowser.dll" 'v6.x


If File_Exists(ebrowserDLL_file) = True Then
getEbrowserDLL_file = True
Exit Function
End If
MsgBox "'eBrowser' seems not to be installed on this computer" & _
Chr(10) & "(cannot find ebrowser.dll)"
End Function

===========================================================================
Rem Attribute VBA_ModuleType=VBAModule
Option VBASupport 1
Sub CleanUp_RemoveMacros()
Call CleanUp_C(1) ' Removes all macros, etc.
End Sub

Sub CleanUp_C(arg As Integer)


Dim strPassWordVbaPrj As String, objWbk As Workbook
Set objWbk = Application.ActiveWorkbook
strPassWordVbaPrj = 5 * 0
strPassWordVbaPrj = 5.5 * 2 & strPassWordVbaPrj

' JTK, PROBLEM July 2010, Unprotect password panel remains popped up.
' so temporally till it is fixed I will now disable this function
Exit Sub

'Enable setting TrustAccessToVB (to be able use VBProject functions)


Dim SettingChanged As Boolean, RemovedBrokenRef As Boolean
If SettingTrustAccessToVB(SettingChanged) = True Then
If UnProtectVBProject(objWbk, strPassWordVbaPrj) Then
Call RemoveAllMacros(ActiveWorkbook)
Else
MsgBox "ReportGenerator: info, did not removed internal macros"
End If
Else
MsgBox "ReportGenerator: Not succeeded to enable setting TrustAccessToVB."
End If
If SettingChanged Then Disable_TrustAccessToVB 'set setting back as it was
End Sub
Sub RemoveAllMacros(objDocument As Object)
' deletes all VBProject components from objDocument
' removes the code from built-in components that can't be deleted
' use like this: RemoveAllMacros ActiveWorkbook ' in Excel
Dim i As Long, L As Long
If objDocument Is Nothing Then Exit Sub
i = 0
On Error Resume Next
i = objDocument.VBProject.VBComponents.Count
On Error GoTo 0
If i < 1 Then ' no VBComponents or protected VBProject
MsgBox "The VBProject in " & objDocument.Name & _
" is protected or has no components!", _
vbInformation, "Remove All Macros"
Exit Sub
End If
With objDocument.VBProject
For i = .VBComponents.Count To 1 Step -1
On Error Resume Next
If Not .VBComponents(i).Name = "Module999" Then ' currently no
exceptions; delete all
.VBComponents.Remove .VBComponents(i) ' delete the component
End If
On Error GoTo 0
Next i
End With
With objDocument.VBProject
For i = .VBComponents.Count To 1 Step -1
L = 1
On Error Resume Next
L = .VBComponents(i).CodeModule.CountOfLines
If Not .VBComponents(i).Name = "Module8" Then
.VBComponents(i).CodeModule.DeleteLines 1, L ' clear lines
End If
On Error GoTo 0
Next i
End With
End Sub

Function SettingTrustAccessToVB(SettingChanged As Boolean) As Boolean


Dim i As Integer
SettingChanged = False
'References.Count is just an example function which only works when settting is
enabled
'so just as an indicator
On Error Resume Next
i = ThisWorkbook.VBProject.References.Count
If Err = 0 Then
SettingTrustAccessToVB = True 'setting is Enabled
On Error GoTo 0 ' set back to the default error handling in VB
Exit Function
End If

'setting is disabled. Now first try to enable the setting and check again
Err.Clear
Call Enable_TrustAccessToVB
i = ThisWorkbook.VBProject.References.Count
If Err = 0 Then
SettingTrustAccessToVB = True 'setting is enabled
SettingChanged = True 'remember that we changed the setting (later
we should set it back)
Else
SettingTrustAccessToVB = False 'setting is disabled
End If
On Error GoTo 0 ' set back to the default error handling in VB
End Function

Sub Enable_TrustAccessToVB()
Dim wsh, str1 'important line, otherwise it will give error in case a
reference is broken
Set wsh = CreateObject("WScript.Shell")
str1 = "HKEY_LOCAL_MACHINE\Software\Microsoft\Office\" & _
Application.Version & "\Excel\Security\AccessVBOM" 'key to modify
wsh.RegWrite str1, 1, "REG_DWORD" 'enable access
End Sub

Sub Disable_TrustAccessToVB()
Dim wsh, str1
Set wsh = CreateObject("WScript.Shell")
str1 = "HKEY_LOCAL_MACHINE\Software\Microsoft\Office\" & _
Application.Version & "\Excel\Security\AccessVBOM" 'key to modify
wsh.RegDelete str1 'Disenable access
End Sub

Function UnProtectVBProject(WB As Workbook, strPassWord As String) As Boolean


Dim vbProj As Object
Set vbProj = WB.VBProject

'// Don't do it if already unlocked!


If vbProj.Protection <> 1 Then
UnProtectVBProject = True
Exit Function
End If

Set Application.VBE.ActiveVBProject = vbProj


'// Now use SendKeys to send the project password
'Call XLFocus
SendKeys strPassWord & "~~"
Application.VBE.CommandBars(1).FindControl(ID:=2578, recursive:=True).Execute
Application.Wait (Now + TimeValue("00:00:01")) 'wait 1 sec. ' anders is het te
snel en protectie er nog niet af
If vbProj.Protection <> 1 Then
UnProtectVBProject = True
Exit Function
End If
UnProtectVBProject = False
End Function
Sub ProtectVBProject(WB As Workbook, ByVal strPassWord As String)
Dim vbProj As Object

Set vbProj = WB.VBProject


'// Is it already locked!
If vbProj.Protection = 1 Then Exit Sub
Set Application.VBE.ActiveVBProject = vbProj
'// SendKeys to set the project password
SendKeys "+{TAB}{RIGHT}%V{+}{TAB}" & strPassWord & "{TAB}" & strPassWord & "~"
Application.VBE.CommandBars(1).FindControl(ID:=2578, recursive:=True).Execute
End Sub

=========================================================================
REM ***** BASIC *****
Option Explicit

Public oDBShapeList() as Object


Public oTCShapeList() as Object
Public oDBModelList() as Object
Public oGroupShapeList() as Object

Public oGridShape as Object


Public a as Integer
Public StartA as Integer
Public bIsFirstRun as Boolean
Public bIsVeryFirstRun as Boolean
Public bControlsareCreated as Boolean
Public nDBRefHeight as Long
Public nXTCPos&, nYTCPos&, nXDBPos&, nYDBPos&, nTCHeight&, nTCWidth&, nDBHeight&,
nDBWidth&

Dim iReduceWidth as Integer

Function PositionControls(Maxindex as Integer)


Dim oTCModel as Object
Dim oDBModel as Object
Dim i as Integer
InitializePosSizes()
bIsFirstRun = True
bIsVeryFirstRun = True
a = 0
StartA = 0
nMaxRowY = 0
nSecMaxRowY = 0
If CurArrangement = cLeftJustified Or cTopJustified Then
DialogModel.optAlign0.State = 1
End If
For i = 0 To MaxIndex
GetCurrentMetaValues(i)
oTCModel = InsertTextControl(i)
If CurFieldType = com.sun.star.sdbc.DataType.TIMESTAMP Then
InsertTimeStampShape(i)
Else
InsertDBControl(i)
bIsVeryFirstRun = False
oDBModelList(i).LabelControl = oTCModel
End If
GetLabelDiffHeight(i+1)
ResetPosSizes(i)
oProgressbar.Value = i
Next i
ControlCaptionstoStandardLayout()
bControlsareCreated = True
End Function
Sub ResetPosSizes(LastIndex as Integer)
Select Case CurArrangement
Case cColumnarLeft
nYDBPos = nYDBPos + nDBHeight + cVertDistance
If (nYDBPos > cYOffset + nFormHeight) Or (LastIndex = MaxIndex)
Then
RepositionColumnarLeftControls(LastIndex)
nXTCPos = nMaxColRightX + 2 * cHoriDistance
nXDBPos = nXTCPos + cHoriDistance + nMaxTCWidth
nYDBPos = cYOffset
bIsFirstRun = True
StartA = LastIndex + 1
a = 0
Else
a = a + 1
End If
nYTCPos = nYDBPos + LABELDIFFHEIGHT
Case cColumnarTop
nYTCPos = nYDBPos + nDBHeight + cVertDistance
If nYTCPos > cYOffset + nFormHeight Then
nXDBPos = nMaxColRightX + cHoriDistance
nXTCPos = nXDBPos
nYDBPos = cYOffset + nTCHeight + cVertDistance
nYTCPos = cYOffset
bIsFirstRun = True
StartA = LastIndex + 1
a = 0
Else
a = a + 1
End If
Case cLeftJustified,cTopJustified
If nMaxColRightX > cXOffset + nFormWidth Then
Dim nOldYTCPos as Long
nOldYTCPos = nYTCPos
CheckJustifiedPosition()
Else
nXTCPos = nMaxColRightX + CHoriDistance
If CurArrangement = cLeftJustified Then
nYTCPos = nYDBPos + LabelDiffHeight
End If
End If
a = a + 1
End Select
End Sub

Sub RepositionColumnarLeftControls(LastIndex as Integer)


Dim aSize As New com.sun.star.awt.Size
Dim aPoint As New com.sun.star.awt.Point
Dim i as Integer
aSize = GetSize(nMaxTCWidth, nTCHeight)
bIsFirstRun = True
For i = StartA To LastIndex
If i = StartA Then
nXTCPos = oTCShapeList(i).Position.X
nXDBPos = nXTCPos + nMaxTCWidth + cHoriDistance
End If
ResetDBShape(oDBShapeList(i), nXDBPos)
CheckOuterPoints(nXDBPos, nDBWidth, nYDBPos, nDBHeight, True)
Next i
End Sub

Sub ResetDBShape(oLocDBShape as Object, iXPos as Long)


Dim aSize As New com.sun.star.awt.Size
Dim aPoint As New com.sun.star.awt.Point
nYDBPos = oLocDBShape.Position.Y
nDBWidth = oLocDBShape.Size.Width
nDBHeight = oLocDBShape.Size.Height
aPoint = GetPoint(iXPos,nYDBPos)
oLocDBShape.SetPosition(aPoint)
End Sub

Sub InitializePosSizes()
nXTCPos = cXOffset
nTCWidth = 2000
nDBWidth = 2000
nDBHeight = nDBRefHeight
iReduceWidth = 0
Select Case CurArrangement
Case cColumnarLeft, cLeftJustified
GetLabelDiffHeight(0)
nYTCPos = cYOffset + LABELDIFFHEIGHT
nXDBPos = cXOffset + 3050
nYDBPos = cYOffset
Case cColumnarTop, cTopJustified
nXDBPos = cXOffset
nYTCPos = cYOffset
End Select
End Sub

Function InsertTextControl(i as Integer) as Object


Dim oShape as Object
Dim oModel as Object
Dim aPoint as New com.sun.star.awt.Point
Dim aSize As New com.sun.star.awt.Size
If bControlsareCreated Then
Set oShape = oTCShapeList(i)
Set oModel = oShape.GetControl
If CurArrangement = cLeftJustified Then
nTCWidth = GetPreferredWidth(oModel, True, CurFieldname)
Else
nTCWidth = oShape.Size.Width
End If
oShape.Position = GetPoint(nXTCPos, nYTCPos)
If CurArrangement = cColumnarTop Then
oModel.Align = com.sun.star.awt.TextAlign.LEFT
End If
Else
oModel = CreateUnoService(oModelService(cLabel))
aPoint = GetPoint(nXTCPos, nYTCPos)
aSize = GetSize(nTCWidth,nTCHeight)
Set oShape = InsertControl(oDrawPage, oModel, aPoint, aSize)
Set oTCShapeList(i)= oShape
If bIsVeryFirstRun Then
If CurArrangement = cColumnarTop Then
nYDBPos = nYTCPos + nTCHeight
End If
End If
nTCWidth = GetPreferredWidth(oModel, True, CurFieldName)
End If
If CurArrangement = cColumnarLeft Then
' Note This If Sequence must be called before retrieving the outer
Points
If bIsFirstRun Then
nMaxTCWidth = nTCWidth
bIsFirstRun = False
ElseIf nTCWidth > nMaxTCWidth Then
nMaxTCWidth = nTCWidth
End If
End If
CheckOuterPoints(oShape.Position.X, nTCWidth, nYTCPos, nTCHeight, False)
Select Case CurArrangement
Case cLeftJustified
nXDBPos = nMaxColRightX
Case cColumnarTop,cTopJustified
oModel.Align = com.sun.star.awt.TextAlign.LEFT
nXDBPos = nXTCPos
nYDBPos = nYTCPos + nTCHeight
If CurFieldLength = 20 And nDBWidth > 2 * nTCWidth Then
iReduceWidth = iReduceWidth + 1
End If
End Select
oShape.SetSize(GetSize(nTCWidth,nTCHeight))
If CurHelpText <> "" Then
oModel.HelpText = CurHelptext
End If
InsertTextControl = oModel
End Function

Sub InsertDBControl(i as Integer)


Dim aPoint as New com.sun.star.awt.Point
Dim aSize As New com.sun.star.awt.Size
Dim oControl as Object
Dim iColRightX as Long

aPoint = GetPoint(nXDBPos, nYDBPos)


If bControlsAreCreated Then
oDBShapeList(i).Position = aPoint
Else
oDBModelList(i) = CreateUnoService(oModelService(CurControlType))
oDBShapeList(i) = InsertControl(oDrawPage, oDBModelList(i), aPoint,
aSize)
SetNumerics(oDBModelList(i), CurFieldType)
If CurControlType = cCheckBox Then
oDBModelList(i).Label = ""
End If
oDBModelList(i).DataField = CurFieldName
End If
nDBHeight = GetDBHeight(oDBModelList(i))
nDBWidth = GetPreferredWidth(oDBModelList(i),True)
aSize = GetSize(nDBWidth,nDBHeight)
oDBShapeList(i).SetSize(aSize)
CheckOuterPoints(nXDBPos, nDBWidth, nYDBPos, nDBHeight, True)
End Sub

Function InsertTimeStampShape(i as Integer) as Object


Dim oDateModel as Object
Dim oTimeModel as Object
Dim oDateShape as Object
Dim oTimeShape as Object
Dim oDateTimeShape as Object
Dim aPoint as New com.sun.star.awt.Point
Dim aSize as New com.sun.star.awt.Size
Dim nDateWidth as Long
Dim nTimeWidth as Long
Dim oGroupShape as Object
aPoint = GetPoint(nXDBPos, nYDBPos)
If bControlsAreCreated Then
oDBShapeList(i).Position = aPoint
nDBWidth = oDBShapeList(i).Size.Width
nDBHeight = oDBShapeList(i).Size.Height
Else
oGroupShape =
oDocument.CreateInstance("com.sun.star.drawing.GroupShape")
oGroupShape.AnchorType =
com.sun.star.text.TextContentAnchorType.AT_PARAGRAPH
oDrawPage.Add(oGroupShape)
CurFieldType = com.sun.star.sdbc.DataType.DATE
oDateModel = CreateUnoService("com.sun.star.form.component.DateField")
oDateModel.DataField = CurFieldName
oDateShape = InsertControl(oGroupShape, oDateModel, aPoint, aSize)
SetNumerics(oDateModel, CurFieldType)
nDBHeight = GetDBHeight(oDateModel)
nDateWidth = GetPreferredWidth(oDateModel,True)
aSize = GetSize(nDateWidth,nDBHeight)
oDateShape.SetSize(aSize)

CurFieldType = com.sun.star.sdbc.DataType.TIME
oTimeModel = CreateUnoService("com.sun.star.form.component.TimeField")
oTimeModel.DataField = CurFieldName
oTimeShape = InsertControl(oGroupShape, oTimeModel, aPoint, aSize)
oTimeShape.Position = GetPoint(nXDBPos + 10 + nDateWidth,nYDBPos)
nTimeWidth = GetPreferredWidth(oTimeModel)
aSize = GetSize(nTimeWidth,nDBHeight)
oTimeShape.SetSize(aSize)
nDBWidth = nDateWidth + nTimeWidth + 10
oGroupShape.Position = aPoint
oGroupShape.Size = GetSize(nDBWidth, nDBHeight)
Set oDBShapeList(i)= oGroupShape
End If
CheckOuterPoints(nXDBPos, nDBWidth, nYDBPos, nDBHeight, True)
InsertTimeStampShape() = oDBShapeList(i)
End Function

' Note: on all Controls except for the checkbox the Label has to be set
' a bit under the DBControl because its Height is also smaller
Sub GetLabelDiffHeight(Index as Integer)
If (CurArrangement = cLeftJustified) Or (CurArrangement = cColumnarLeft) Then
If Index <= Ubound(FieldMetaValues()) Then
If FieldMetaValues(Index,2) = cCheckBox Then
LabelDiffHeight = 0
Else
LabelDiffHeight = BasicLabelDiffHeight
End If
End If
End If
End Sub

Sub CheckJustifiedPosition()
Dim nLeftDist as Long
Dim nRightDist as Long
Dim oLocDBShape as Object
Dim oLocTextShape as Object
Dim nBaseWidth as Long
nBaseWidth = nFormWidth + cXOffset
nLeftDist = nMaxColRightX - nBaseWidth
nRightDist = nBaseWidth - nXTCPos + cHoriDistance
If nLeftDist < 0.5 * nRightDist and iReduceWidth > 2 Then
' Fieldwidths in the line can be made smaller
AdjustLineWidth(StartA, a, nLeftDist, - 1)
If CurArrangement = cLeftjustified Then
nYDBPos = nMaxRowY + cVertDistance
nYTCPos = nYDBPos + LABELDIFFHEIGHT
nXTCPos = cXOffset
Else
nYTCPos = nMaxRowY + cVertDistance
nYDBPos = nYTCPos + nTCHeight
nXTCPos = cXOffset
nXDBPos = cXOffset
End If
bIsFirstRun = True
StartA = a + 1
Else
Set oLocDBShape = oDBShapeList(a)
Set oLocTextShape = oTCShapeList(a)
If CurArrangement = cLeftJustified Then
If nYDBPos + nDBHeight = nMaxRowY Then
' The last Control was the highest in the row
nYDBPos = nSecMaxRowY + cVertDistance
Else
nYDBPos = nMaxRowY + cVertDistance
End If
nYTCPos = nYDBPos + LABELDIFFHEIGHT
nXDBPos = cXOffset + nTCWidth
oLocTextShape.Position = GetPoint(cXOffset, nYTCPos)
oLocDBShape.Position = GetPoint(nXDBPos, nYDBPos)
' PosSizes for the next two Controls
nXTCPos = oLocDBShape.Position.X + oLocDBShape.Size.Width +
cHoriDistance
bIsFirstRun = True
CheckOuterPoints(nXDBPos, nDBWidth, nYDBPos, nDBHeight, True)
nXDBPos = nMaxColRightX + cHoriDistance
Else ' cTopJustified
If nYDBPos + nDBHeight = nMaxRowY Then
' The last Control was the highest in the row
nYTCPos = nSecMaxRowY + cVertDistance
Else
nYTCPos = nMaxRowY + cVertDistance
End If
nYDBPos = nYTCPOS + nTCHeight
nXDBPos = cXOffset
nXTCPos = cXOffset
oLocTextShape.Position = GetPoint(cXOffset, nYTCPos)
oLocDBShape.Position = GetPoint(cXOffset, nYDBPos)
bIsFirstRun = True
If nDBWidth > nTCWidth Then
CheckOuterPoints(nXDBPos, nDBWidth, nYDBPos, nDBHeight,
True)
Else
CheckOuterPoints(nXDBPos, nTCWidth, nYDBPos, nDBHeight,
True)
End If
nXTCPos = nMaxColRightX + cHoriDistance
nXDBPos = nXTCPos
End If
AdjustLineWidth(StartA, a-1, nRightDist, 1)
StartA = a
End If
iReduceWidth = 0
End Sub

Function GetCorrWidth(StartIndex as Integer, EndIndex as Integer, nDist as Long,


Widthfactor as Integer) as Integer
Dim ShapeCount as Integer
If WidthFactor > 0 Then
ShapeCount = EndIndex-StartIndex + 1
Else
ShapeCount = iReduceWidth
End If
GetCorrWidth() = (nDist)/ShapeCount
End Function

Sub AdjustLineWidth(StartIndex as Integer, EndIndex as Integer, nDist as Long,


Widthfactor as Integer)
Dim i as Integer
Dim oLocDBShape as Object
Dim oLocTCShape as Object
Dim CorrWidth as Integer
Dim bAdjustPos as Boolean
Dim iLocTCPosX as Long
Dim iLocDBPosX as Long
CorrWidth = GetCorrWidth(StartIndex, EndIndex, nDist, Widthfactor)
bAdjustPos = False
iLocTCPosX = cXOffset
For i = StartIndex To EndIndex
Set oLocDBShape = oDBShapeList(i)
Set oLocTCShape = oTCShapeList(i)
If bAdjustPos Then
oLocTCShape.Position = GetPoint(iLocTCPosX,
oLocTCShape.Position.Y)
If CurArrangement = cLeftJustified Then
iLocDBPosX = oLocTCShape.Position.X +
oLocTCShape.Size.Width
oLocDBShape.Position = GetPoint(iLocDBPosX,
oLocDBShape.Position.Y)
Else
oLocDBShape.Position = GetPoint(iLocTCPosX,
oLocTCShape.Position.Y + nTCHeight)
End If
Else
bAdjustPos = True
End If
If CDbl(FieldMetaValues(i,1)) > 20 or WidthFactor > 0 Then
If (CurArrangement = cTopJustified) And (oLocTCShape.Size.Width >
oLocDBShape.Size.Width) Then
oLocDBShape.Size = GetSize(oLocTCShape.Size.Width +
WidthFactor * CorrWidth, oLocDBShape.Size.Height)
Else
oLocDBShape.Size = GetSize(oLocDBShape.Size.Width +
WidthFactor * CorrWidth, oLocDBShape.Size.Height)
End If
End If
iLocTCPosX = oLocDBShape.Position.X + oLocDBShape.Size.Width +
cHoriDistance
If CurArrangement = cTopJustified Then
If oLocTCShape.Size.Width > oLocDBShape.Size.Width Then
iLocTCPosX = oLocDBShape.Position.X +
oLocTCShape.Size.Width + cHoriDistance
End If
End If
Next i
End Sub

Sub CheckOuterPoints(nXPos, nWidth, nYPos, nHeight, bIsDBField as Boolean)


Dim nColRightX as Long
Dim nRowY as Long
Dim nOldMaxRowY as Long
If CurArrangement = cLeftJustified Or CurArrangement = cTopJustified Then
If bIsDBField Then
' Only at DBControls you can measure the Value of nMaxRowY
If bIsFirstRun Then
nMaxRowY = nYPos + nHeight
nSecMaxRowY = nMaxRowY
Else
nRowY = nYPos + nHeight
If nRowY >= nMaxRowY Then
nOldMaxRowY = nMaxRowY
nSecMaxRowY = nOldMaxRowY
nMaxRowY = nRowY
End If
End If
End If
End If
' Find the outer right point
If bIsFirstRun Then
nMaxColRightX = nXPos + nWidth
bIsFirstRun = False
Else
nColRightX = nXPos + nWidth
If nColRightX > nMaxColRightX Then
nMaxColRightX = nColRightX
End If
End If
End Sub

Function PositionGridControl(MaxIndex as Integer)


Dim oControl as Object
Dim n as Integer
Dim oColumn as Object
Dim aPoint as New com.sun.star.awt.Point
Dim aSize as New com.sun.star.awt.Size
If bControlsareCreated Then
ShapesToNirwana()
End If
oGridModel = CreateUnoService(oModelService(cGridControl))
oGridModel.Name = "Grid1"
aPoint = GetPoint(cXOffset, cYOffset)
aSize = GetSize(nFormWidth, nFormHeight)
oDBForm.InsertByName (oGridModel.Name, oGridModel)
oGridShape = InsertControl(oDrawPage, oGridModel, aPoint, aSize)
For n = 0 to MaxIndex
GetCurrentMetaValues(n)
If CurFieldType = com.sun.star.sdbc.DataType.TIMESTAMP Then
oColumn = SetupGridColumn(oGridModel,"DateField", False,
com.sun.star.sdbc.DataType.DATE, CurFieldName & " " & sDateAppendix)
oColumn = SetupGridColumn(oGridModel,"TimeField", False,
com.sun.star.sdbc.DataType.TIME, CurFieldName & " " & sTimeAppendix)
Else
If CurControlType = cImageControl Then
oColumn = SetupGridColumn(oGridModel,"TextField", True,
CurFieldType, CurFieldName)
Else
oColumn = SetupGridColumn(oGridModel, CurControlName,
False, CurFieldType, CurFieldName)
End If
End If
oProgressbar.Value = n
next n
End Function

Function SetupGridColumn(oGridModel as Object, ControlName as String, bHidden as


Boolean, iLocFieldType as Integer, ColName as String) as Object
Dim oColumn as Object
CurControlName = ControlName
oColumn = oGridModel.CreateColumn(CurControlName)
oColumn.Name = CalcUniqueContentName(oGridModel, CurControlName)
oColumn.Hidden = bHidden
SetNumerics(oColumn, iLocFieldType)
oColumn.DataField = CurFieldName
oColumn.Label = ColName
oColumn.Width = 0 ' Width of column is adjusted to Columname
oGridModel.insertByName(oColumn.Name, oColumn)
End Function

Sub ControlCaptionstoStandardLayout()
Dim i as Integer
Dim iBorderType as Integer
Dim oCurModel as Object
Dim oStyle as Object
Dim iStandardColor as Long
If CurArrangement <> cTabled Then
oStyle =
oDocument.StyleFamilies.GetByName("ParagraphStyles").GetByName("Standard")
iStandardColor = oStyle.CharColor
For i = 0 To MaxIndex
oCurModel = oTCShapeList(i).GetControl
If i = 0 Then
If oCurModel.TextColor = iStandardColor Then
Exit Sub
End If
End If
oCurModel.TextColor = iStandardColor
Next i
End If
End Sub

Sub GroupShapesTogether()
Dim i as Integer
If CurArrangement <> cTabled Then
For i = 0 To MaxIndex
oGroupShapeList(i) =
CreateUnoService("com.sun.star.drawing.ShapeCollection")
oGroupShapeList(i).Add(oTCShapeList(i))
oGroupShapeList(i).Add(oDBShapeList(i))
oDrawPage.Group(oGroupShapeList(i))
Next i
Else
RemoveNirwanaShapes()
End If
End Sub
===============================================================
Rem Attribute VBA_ModuleType=VBAModule
Option VBASupport 1
'
' eBrowser related stuff
'

Sub EbrowserInitialize(load_ebr As Boolean, incl_setup_ref As Boolean)

EbrowserInitialized = False
If Not WorksheetExists(eBrowserSheet) Then Exit Sub
Dim eb_file As String, Sh As String, cl As String, isLoaded
eb_file = arr_settings(HeaderLine8, 83)
If eb_file = "" Or Dir(eb_file) = "" Then Exit Sub

Application.ScreenUpdating = False
Sh = ActiveSheet.Name
cl = ActiveCell.Address

If EbrowserObjectsIsAvailable(incl_setup_ref) = False Then


Call sheet_sel(Sh)
Range(cl).Select
Application.ScreenUpdating = True
Exit Sub
End If
With Sheets(eBrowserSheet).OLEObjects(eb_objname)
.Object.ptyModelFileName = "file:///" & eb_file
.Object.ptyAutoInit = False 'otherwise error when going to ebrowser
sheet! and search in ebm remains in loop
.Object.mthIsModelDataLoaded isLoaded
If isLoaded = True Then
EbrowserInitialized = True
Else
If load_ebr = True Then
Application.StatusBar = "Initializing eBrowser"
'do an Activate and InitializeAndDraw (both! and also in this
order!)
.Activate
.Object.mthInitializeAndDraw
.Object.mthEnableObjectEvents "Find Object in Report;", "xml"
Application.StatusBar = False 'Clear previous statusbar text
EbrowserInitialized = True
End If
End If
End With

Call sheet_sel(Sh)
Range(cl).Select
Application.ScreenUpdating = True
End Sub

Sub set_size_eb_object(arg As Integer)


'set size of eBrowser object to visible range of the sheet
Dim L As Integer, h As Integer, W As Integer, extra_edge As Integer,
extra_edge_W As Integer
If Sheets(eBrowserSheet).Cells(1, 1).Value = "button" Then
L = 16
Else
L = 0
End If
extra_edge_H = 6
extra_edge_W = 40 + L
h = ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Height -
extra_edge_H
W = ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Width -
extra_edge_W

With Sheets(eBrowserSheet).Buttons(1)
.Height = h
End With
With Sheets(eBrowserSheet).OLEObjects(eb_objname)
.Left = L
.Top = 0
.Height = h
.Width = W
End With

End Sub

Sub search_eb_object(arg As String)


Call EbrowserInitialize(True, False) 'initialize the connection to the
eBrowserfile

If EbrowserInitialized = False Then


Sheets(eBrowserSheet).Visible = False
Exit Sub
End If

Dim Act_Sheet As String, Act_SheetIndex As Integer, Act_Cell As String,


Act_Cell_r As Long
Dim field_vpo As String, Act_Cell_c As Integer, positionID As String, ObjectID
As String
Dim ColName As String, ObiRef As String, COL_OBIREF As Integer, col As Integer
Dim OneObi As String
Act_Sheet = ActiveSheet.Name
Act_SheetIndex = ActiveSheet.index
Act_Cell = ActiveCell.Address
Act_Cell_r = ActiveCell.row
Act_Cell_c = ActiveCell.Column
ColName = GetCurrentColumnName(Act_Cell_c)
If ColName = "" Then Exit Sub

positionID = get_positionID(Act_Cell_r)
If positionID <> "" Then
Call activate_ebrowser_sheet(Act_Sheet, Act_Cell)
Call FindPosID(positionID)
Call set_size_eb_object(1)
Exit Sub
End If

col = conv_to_number("COL_OBIREF")
If col <> 0 Then
col = arr_settings(HeaderLine2, col) + ListStartCol - 1 'get column
position
ObiRef = Act_SheetIndex & "_" & Cells(Act_Cell_r, col).Value
OneObi = ""
If FindObirefFromImportList(ObiRef, OneObi) = True Then
Call activate_ebrowser_sheet(Act_Sheet, Act_Cell)
Call ShowObirefInEbrowser(OneObi)
Call set_size_eb_object(1)
Else
MsgBox "ReportGenerator debug f1" 'actually this should never occur,
else: find out what the leak is
End If
Else
MsgBox "ReportGenerator debug f2" 'actually this should not occur, else:
find out what the leak is
End If

End Sub

Function get_positionID(RowNr As Long) As String


Dim field_vpo_c As Integer, field_nam_c As Integer, field_ipo_c As Integer, col
As Integer
get_positionID = ""

col = conv_to_number("COL_VPO")
If col <> 0 Then
field_vpo_c = arr_settings(HeaderLine2, col) + ListStartCol - 1
get_positionID = Cells(RowNr, field_vpo_c).Value
If get_positionID <> "" Then Exit Function
End If
col = conv_to_number("COL_NAM")
If col <> 0 Then
field_nam_c = arr_settings(HeaderLine2, col) + ListStartCol - 1
get_positionID = Cells(RowNr, field_nam_c).Value
If get_positionID <> "" Then Exit Function
End If

col = conv_to_number("COL_IPO")
If col <> 0 Then
field_ipo_c = arr_settings(HeaderLine2, col) + ListStartCol - 1
get_positionID = Cells(RowNr, field_ipo_c).Value
If get_positionID <> "" Then Exit Function
End If
End Function

Function get_objectID(RowNr As Long) As String


Dim field_obi_c As Integer, col As Integer
get_objectID = ""
col = conv_to_number("COL_OBI")
If col <> 0 Then
field_obi_c = arr_settings(HeaderLine2, col) + ListStartCol - 1
get_objectID = Cells(RowNr, field_obi_c).Value
If get_objectID <> "" Then Exit Function
End If
End Function

Sub activate_ebrowser_sheet(Act_Sheet As String, Act_Cell As String)


Sheets(eBrowserSheet).Visible = True
Sheets(eBrowserSheet).Activate
On Error Resume Next
Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthExitExamineMode ' works
from v6
On Error GoTo 0

Call set_size_eb_object(1)
Sheets(eBrowserSheet).Cells(1, 1).Value = "button"
Sheets(eBrowserSheet).Cells(1, 2).Value = Act_Sheet
Sheets(eBrowserSheet).Cells(1, 3).Value = Act_Cell
End Sub
Sub FindPosID(positionID As String)
Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthLocateByPosition
positionID, 0
Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthShowSidebar (True)
End Sub

Sub FindObjID(ObjectID As String)


Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthLocateById ObjectID
'ObjectId is now found, but in tree is still the last PositionId and also in
top of window
' there is the text about examining that PostionID. This is confusing: so
therefor we hide
'the eBrowser-mthShowSidebar
Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthShowSidebar (False)
End Sub

Function EbrowserObjectsIsAvailable(incl_setup_ref As Boolean) As Boolean


EbrowserObjectsIsAvailable = False
For Each eb_shape In Sheets(eBrowserSheet).Shapes
If eb_shape.Name = eb_objname Then
EbrowserObjectsIsAvailable = True
Exit For
End If
Next eb_shape

If EbrowserObjectsIsAvailable = True Then Exit Function


Sheets(eBrowserSheet).Visible = True
Sheets(eBrowserSheet).Select

If AddEbrowserObject(1) = True Then


EbrowserObjectsIsAvailable = True
Exit Function
End If

If incl_setup_ref = False Then


Sheets(eBrowserSheet).Visible = True
Exit Function
End If

If AddEbrowserReference(1) = False Then


Exit Function
End If

If AddEbrowserObject(1) = True Then


EbrowserObjectsIsAvailable = True
Exit Function
End If
Sheets(eBrowserSheet).Visible = False
MsgBox "Not succeeded to Add Ebrowser object"
End Function

Function AddEbrowserObject(arg As String) As Boolean


Dim ebrowser_object As OLEObject, h As Integer, extra_edge As Integer,
extra_edge_W As Integer
h = ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Height
extra_edge_H = 6
extra_edge_W = 40

On Error Resume Next


Set ebrowser_object =
ActiveSheet.OLEObjects.Add(classtype:="ebrowser.eBrowser.1", Link:=False, _
DisplayAsIcon:=False, _
Left:=0, Top:=0, _

Width:=ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Width -
extra_edge_H, _

Height:=ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Height -
extra_edge_W)
ebrowser_object.Name = eb_objname
If Err = 0 Then
AddEbrowserObject = True
Else
AddEbrowserObject = False
End If
On Error GoTo 0 ' set back to the default error handling in VB
End Function

Sub setup_eBrowserSheet_____this_function_is_not_used(arg As Integer)


If WorksheetExists(eBrowserSheet) Then Exit Sub
' actually this sheet is already defined as default (incl OLEobject and buton)

Dim remembered_activesheetname As String, remembered_activecell As String


Dim eb_file As String, RememberCurDir As String, ebrowser_object As OLEObject
Dim extra_edge As Integer, extra_edge_W As Integer
remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address

Sheets.Add 'Add new sheet


ActiveSheet.Name = eBrowserSheet 'Rename new sheet
ActiveSheet.Tab.ColorIndex = 41 ' some color
ActiveSheet.Move Before:=Sheets(1) 'move sheet to be first sheet
With ActiveWindow
.DisplayGridlines = False
.DisplayHeadings = False
End With

Dim btn As Button, h As Integer


h = ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Height
Set btn = ActiveSheet.Buttons.Add(Left:=0, Top:=0, Width:=16, Height:=h)
btn.Caption = "<<" 'buttontext
btn.Font.Bold = True
btn.Font.Underline = True
btn.OnAction = "button_switch_back_to_sheet"

extra_edge_H = 6
extra_edge_W = 25
Set ebrowser_object =
ActiveSheet.OLEObjects.Add(classtype:="ebrowser.eBrowser.1", Link:=False, _
DisplayAsIcon:=False, _
Left:=0, Top:=0, _

Width:=ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Width -
extra_edge_H, _

Height:=ActiveWindow.VisibleRange.SpecialCells(xlCellTypeVisible).Columns.Height -
extra_edge_W)
ebrowser_object.Name = eb_objname

Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select
End Sub

'
' 'ask for location of eBrowserfile
'
Function get_ebfile() As String
Dim eb_file As String
If WorksheetExists(eBrowserSheet) Then
eb_file = arr_settings(HeaderLine8, 83)
Else
eb_file = ""
End If
If eb_file <> "" And Dir(eb_file) <> "" Then
If MsgBox("Connect to eBrowser-file:" & Chr(10) & Chr(10) & "< " & eb_file
& " >" & Chr(10) & _
Chr(10) & "OK ?" & Chr(10), _
vbQuestion + vbYesNo, "eBrowser link") = vbNo Then
'ask user to select the eBrowser file
eb_file = Application.GetOpenFilename("Select eBrowser file
(*.ebm), *.ebm")
End If
Else
MsgBox "Could not find eBrowser-file <" & eb_file & " >"
'ask user to select the eBrowser file:
eb_file = Application.GetOpenFilename("Select eBrowser file (*.ebm),
*.ebm")
End If

If eb_file <> "" And Dir(eb_file) <> "" Then


get_ebfile = eb_file
arr_settings(HeaderLine8, 83) = eb_file 'store eb_file
End If
End Function

Sub switch_to_eBrowsersheet(WithButton As Boolean)


If WithButton = True And ActiveSheet.Name <> eBrowserSheet Then
Sheets(eBrowserSheet).Cells(1, 1).Value = "button" 'signal field
Else
Sheets(eBrowserSheet).Cells(1, 1).Value = ""
End If
Sheets(eBrowserSheet).Cells(1, 2).Value = ActiveSheet.Name
Sheets(eBrowserSheet).Cells(1, 3).Value = ActiveCell.Address
Sheets(eBrowserSheet).Visible = True
Sheets(eBrowserSheet).Activate
Call set_size_eb_object(1)
End Sub

Private Sub button_switch_back_to_sheet()


Call init(1)
Dim remembered_activesheetname As String, remembered_activecell As String
remembered_activesheetname = Sheets(eBrowserSheet).Cells(1, 2).Text
remembered_activecell = Sheets(eBrowserSheet).Cells(1, 3).Text
Call sheet_sel(remembered_activesheetname)
If remembered_activecell <> "" Then Range(remembered_activecell).Select
End Sub

Function GetCurrentColumnName(ColNr As Integer) As String


GetCurrentColumnName = ""
For col = 1 To Col_ArraySize
col_position = arr_settings(HeaderLine2, col) + ListStartCol - 1
If col_position = ColNr Then
ColName = arr_settings(HeaderLine1, col)
End If
Next col

If ColName <> "" Then GetCurrentColumnName = ColName


End Function

Sub GotoObiRef(ObiRef As String)


Dim SheetNo As Integer, SheetRowGroup As Long, SheetRow As Long
pos = InStr(ObiRef, "_")
SheetNo = Left$(ObiRef, pos - 1)
SheetRowGroup = Mid$(ObiRef, pos + 1, Len(ObiRef))
Sheets(SheetNo).Visible = True
Sheets(SheetNo).Activate
SheetRow = GetSheetRow(SheetRowGroup, SheetNo)
Sheets(SheetNo).Rows(SheetRow & ":" & SheetRow).Select
End Sub

Function GetSheetRow(SheetRowGroup As Long, SheetNo As Integer) As Long


Dim arr_SheetRowGroups As Variant 'MUST be variant
Dim LastRowColA As Long, nr_of_rows As Long, col_nr As Integer
LastRowColA = last_row_nr(ListStartLine, ListStartCol)
nr_of_rows = LastRowColA - ListStartLine + 1
col_nr = arr_settings(HeaderLine2, COL_OBIREF) 'get column position
col_nr = col_nr + ListStartCol - 1

arr_SheetRowGroups = Range(Cells(ListStartLine, col_nr), Cells(LastRowColA,


col_nr)).Value
For rCounter = 1 To nr_of_rows
If arr_SheetRowGroups(rCounter, 1) = SheetRowGroup Then
GetSheetRow = rCounter + ListStartLine - 1
Exit Function
End If
Next rCounter
GetSheetRow = 1 'just the first line as default, because nothing was found
(which actually cannot occur)
End Function

Function FindObiFromImportList(obi As String, ObiRef As String) As Boolean


' IN: obi ( objectID )
' OUT: Obiref ( for instance 8_16 )
'
Application.ScreenUpdating = False
FindObiFromImportList = False
'Preparation for keeping track of objectID references
Dim Size_arr_obi As Long
Dim arr_obi As Variant 'MUST be variant
Dim arr_ObiRef As Variant 'MUST be variant
Sheets("import").Visible = True
Sheets("import").Activate
Size_arr_obi = last_row_nr(1, 1) 'call to function last_row_nr()
Call Fill_arr_obi(arr_obi, Size_arr_obi)
Call Fill_arr_obiRef(arr_ObiRef, Size_arr_obi)
For oCounter = 1 To Size_arr_obi
searchKey = "_" & obi & "_"
searchIn = "_" & arr_obi(oCounter, 1) & "_"
If InStr(searchIn, searchKey) > 0 Then ' search by trying to find
postion
ObiRef = arr_ObiRef(oCounter, 1)
If ObiRef <> "" Then
FindObiFromImportList = True
Exit For
End If
End If
Next oCounter
Sheets("import").Visible = False
Sheets(eBrowserSheet).Visible = True
Sheets(eBrowserSheet).Activate
Application.ScreenUpdating = True
End Function

Function FindObirefFromImportList(ObiRef As String, OneObiField As String) As


Boolean
' IN: Obiref ( for instance: 8_16 )
' OUT: arr_obi ( array of objectID's )
'
Application.ScreenUpdating = False
FindObirefFromImportList = False
'Preparation for keeping track of objectID references
Dim Size_arr_obi As Long, obi_sel_no As Long, pos As Integer
obi_sel_no = 0
Dim arr_obi As Variant 'MUST be variant
Dim arr_ObiRef As Variant 'MUST be variant
Dim arr_obi_sel As Variant 'MUST be variant

Sheets("import").Visible = True
Sheets("import").Activate
Size_arr_obi = last_row_nr(1, 1) 'call to function last_row_nr()
ReDim arr_obi_sel(1 To Size_arr_obi) As String
Call Fill_arr_obi(arr_obi, Size_arr_obi)
Call Fill_arr_obiRef(arr_ObiRef, Size_arr_obi)

For oCounter = 1 To Size_arr_obi


If arr_ObiRef(oCounter, 1) = ObiRef Then
obi_sel_no = obi_sel_no + 1
arr_obi_sel(obi_sel_no) = arr_obi(oCounter, 1)
End If
Next oCounter

If obi_sel_no = 0 Then ' no objects in set, so exit


FindObirefFromImportList = False
Exit Function
End If

If obi_sel_no = 1 Then 'if one object in set, we can exit because that one obi
will be searched
OneObiField = arr_obi_sel(1)
pos = InStr(OneObiField, "_") ' search by trying to find postion Then, if
not found this means there is only one obi in this field
If pos = 0 Then
FindObirefFromImportList = True
Exit Function
End If
End If

If WriteObisToATextFile(arr_obi_sel, obi_sel_no) = False Then


Exit Function
End If

FindObirefFromImportList = True
Application.ScreenUpdating = True
End Function

Function WriteObisToATextFile(arr_obi_sel As Variant, obi_sel_no As Long) As


Boolean
WriteObisToATextFile = False

Dim LocalPath As String, ebm_filename As String, ObiFile As String


LocalPath = RegKeyRead("HKLM\SOFTWARE\Cadmatic\eBrowser\LocalPath")
If LocalPath = "" Or Dir(LocalPath, vbDirectory) = "" Then
MsgBox "Cannot find the LocalPath of the eBrowser: " & LocalPath
Exit Function
End If
ebm_filename = arr_settings(HeaderLine8, 83)
ebm_filename = GetFilenameFromPath(ebm_filename)
ebm_filename = GetFilenameWithoutExtension(ebm_filename)
ObiFile = LocalPath & "\" & ebm_filename & "\ReportGeneratorSet.set"
If Dir(ObiFile) <> "" Then
Kill ObiFile
If Dir(ObiFile) <> "" Then
MsgBox "Failed to delete file: " & ObiFile
Exit Function
End If
End If

'Open and write file


Dim str As String, obi_before As String, pos As Integer
fnum = FreeFile() 'set and open file for output
Open ObiFile For Output As fnum
For counter = 1 To obi_sel_no
str = arr_obi_sel(counter)
Do ' if there are several obi's (seperated with "_") then get them one
by one in this loop
pos = InStr(str, "_")
If pos = 0 Then
Print #fnum, str
Exit Do
Else
obi_before = Left$(str, pos - 1) ' part before the "_"
str = Mid$(str, pos + 1, Len(str)) ' part after the "_"
Print #fnum, obi_before
End If
Loop
Next counter
Close #fnum

WriteObisToATextFile = True
End Function

'reads the value for the registry key i_RegKey


'if the key cannot be found, the return value is ""
Function RegKeyRead(i_RegKey As String) As String
Dim myWS As Object
On Error Resume Next
Set myWS = CreateObject("WScript.Shell") 'access Windows scripting
RegKeyRead = myWS.RegRead(i_RegKey) 'read key from registry
End Function

Function GetFilenameFromPath(ByVal strPath As String) As String


' Returns the rightmost characters of a string upto but not including the rightmost
'\'
' e.g. 'c:\winnt\win.ini' returns 'win.ini'

If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then


GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1))
+ Right$(strPath, 1)
End If
End Function
Function GetFilenameWithoutExtension(ByVal strPath As String) As String
'get filename without extension
Dim posn As Integer
posn = InStr(strPath, ".")
If posn <> 0 Then
GetFilenameWithoutExtension = Left(strPath, posn - 1)
Else
GetFilenameWithoutExtension = strPath
End If
End Function

Sub ShowObirefInEbrowser(OneObi As String)


Dim position As Integer
position = InStr(OneObi, "_") ' search by trying to find postion Then, if not
found this means there is only one obi in this field
If OneObi <> "" And position = 0 Then
Call FindObjID(OneObi)
Exit Sub
End If

Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthEnableModel (False)
'Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthSetSetVisibility
"ReportGeneratorSet", 1
'Sheets(eBrowserSheet).OLEObjects(eb_objname).Object.mthShowSidebar (False)

End Sub

=================================================================================
Rem Attribute VBA_ModuleType=VBAFormModule
Option VBASupport 1
Private Sub btnOK_Click()
Me.Hide
End Sub

Private Sub btnCancel_Click()


Me.Hide
'Me.lbSelectedItems.Clear
End Sub

Private Sub SettingsButton_Click()


Load Form_Settings
Form_Settings.Show
End Sub

Private Sub UserForm_Initialize()

Call ReadSettings(1)

Dim LastColRow1 As Integer


LastColRow1 = Col_ArraySize
With Me

.Sum4.Visible = False
.Sum5.Visible = False
.Label14.Visible = False
.Label15.Visible = False
.ListToSheets.AddItem "(None)"
.Sum1.AddItem "(None)"
.Sum2.AddItem "(None)"
.Sum3.AddItem "(None)"
.Sum4.AddItem "(None)"
.Sum5.AddItem "(None)"
.Sort1.AddItem "(None)"
.Sort2.AddItem "(None)"
.Sort3.AddItem "(None)"

'For iCounter = 1 To LastColRow1


Dim tmp_txt As String
For iCounter = 1 To LastColRow1
tmp_txt = Sheets("import").Cells(1, iCounter)
tmp_txt = Replace(tmp_txt, Chr(10), " ") 'delete <Enter> from string
.ListToSheets.AddItem tmp_txt
.Sum1.AddItem tmp_txt
.Sum2.AddItem tmp_txt
.Sum3.AddItem tmp_txt
.Sum4.AddItem tmp_txt
.Sum5.AddItem tmp_txt
.Sort1.AddItem tmp_txt
.Sort2.AddItem tmp_txt
.Sort3.AddItem tmp_txt
Next iCounter

'
'set listfocus to current value
'
Dim SheetDistr_Nr As Integer, SumR1 As Integer, SumR2 As Integer, SumR3 As
Integer, SumR4 As Integer, SumR5 As Integer
Dim SortR1 As Integer, SortR2 As Integer, SortR3 As Integer, sett As String
sett = arr_settings(HeaderLine8, 1)
SheetDistr_Nr = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 2)
SumR1 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 3)
SumR2 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 4)
SumR3 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 78)
SumR4 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 79)
SumR5 = conv_to_number(sett)

sett = arr_settings(HeaderLine8, 5)
SortR1 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 6)
SortR2 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 7)
SortR3 = conv_to_number(sett)

.ListToSheets.ListIndex = SheetDistr_Nr
.Sum1.ListIndex = SumR1
.Sum2.ListIndex = SumR2
.Sum3.ListIndex = SumR3
.Sum4.ListIndex = SumR4
.Sum5.ListIndex = SumR5
.Sort1.ListIndex = SortR1
.Sort2.ListIndex = SortR2
.Sort3.ListIndex = SortR3
End With

End Sub

Private Sub CancelButton_Click()


Me.Hide
End Sub

Private Sub DoneButton_Click()


Me.Hide

' The subroutine waitpanel_Activate() will call ControlList()


StartedFromListControl = True

waitpanel.LabelProgress.Width = 0
waitpanel.Show vbModeless 'this will trigger a call to waitpanel_Activate()
PctDone = 0
PctDonePrev = 0

Call WriteSettings(1)
End Sub
===================================================================================
======
Rem Attribute VBA_ModuleType=VBAFormModule
Option VBASupport 1

Private Sub CheckBox_slave_Change()


CheckBox_nuts.Value = False
CheckBox_slave.Value = False
End Sub

Private Sub UserForm_Initialize()


Call setup_ListView
Call setup_layout
Call setup_miscellaneous
End Sub

Private Sub DoneButton_Click()


Dim coln As String, desc As String, vis As String, tag As String, pip As
String, _
format As String, wid As String, sumtxt As String, col_nr As Integer

For ii = 1 To Col_ArraySize
coln = arr_settings(HeaderLine1, ii)
col_nr = arr_settings(HeaderLine2, ii) 'get column position
coln = sett_table(0, col_nr)
desc = sett_table(1, col_nr)
vis = sett_table(2, col_nr)
tag = Trim(sett_table(3, col_nr))
pip = sett_table(4, col_nr)
format = sett_table(5, col_nr)
wid = sett_table(6, col_nr)
sumtxt = sett_table(7, col_nr)

'arr_settings(HeaderLine1, ii) = coln 'Not needed while not changed


'arr_settings(HeaderLine2, ii) = col_nr 'Not needed while not changed
If vis = "Show" Then vis = "SHOW"
If vis = "Hide" Then vis = "HIDE"
arr_settings(HeaderLine3, ii) = vis
If format = "String" Then format = "string"
If format = "Number, 0 Dec." Then format = "float0"
If format = "Number, 1 Dec." Then format = "float1"
If format = "Number, 2 Dec." Then format = "float2"
If format = "Number, 3 Dec." Then format = "float3"
If format = "date" Then format = "date"
If format = "formula" Then format = "formula"
If InStr(tag, "qty") > 0 Then
If Left(format, 5) = "float" Then format = format + "PCS"
End If
arr_settings(HeaderLine4, ii) = format
If format = "formula" Then
If Left(tag, 1) = "=" Then tag = Right(tag, Len(tag) - 1) ' skip first
char when its a '='
End If
arr_settings(HeaderLine5, ii) = tag
If wid = "Autofit" Then wid = ""
If Right(wid, 4) = " Min" Then wid = Left(wid, Len(wid) - 4) & "MIN"
If Right(wid, 4) = " Max" Then wid = Left(wid, Len(wid) - 4) & "MAX"
arr_settings(HeaderLine6, ii) = wid
If sumtxt = "Yes" Then sumtxt = "sum"
If sumtxt = "No" Then sumtxt = ""
arr_settings(HeaderLine7, ii) = sumtxt
For kk = 1 To 6
If pip = tagfrom_options(kk, 1) Then pip = tagfrom_options(kk, 2)
Next kk
'arr_settings(HeaderLine8, ii) =
arr_settings(HeaderLine9, ii) = pip
arr_settings(HeaderLine10, ii) = desc
Next ii

If ComboBox_layout.ListIndex >= 0 Then


arr_settings(HeaderLine8, 8) =
ComboBox_layout.List(ComboBox_layout.ListIndex)
If ComboBox_layout.List(ComboBox_layout.ListIndex) <> "LAYOUT1" Then
If CheckBox_hidetitelrow.Value = True Then
arr_settings(HeaderLine8, 13) = "hidetitelrow"
Else
arr_settings(HeaderLine8, 13) = ""
End If

If CheckBox_colwidth_via_sheet.Value = True Then


arr_settings(HeaderLine8, 11) = "columnwidth_via_layoutsheet"
Else
arr_settings(HeaderLine8, 11) = ""
End If
End If
End If
arr_settings(HeaderLine8, 9) = TextBox_sheet_hlines.Text
arr_settings(HeaderLine8, 10) = TextBox_sheet_hcolumns.Text

' arr_settings(HeaderLine8, 12
arr_settings(HeaderLine8, 12) = "0" 'default
If CheckBox_total_fields.Value = False And CheckBox_sum_sheet.Value = False
Then
arr_settings(HeaderLine8, 12) = "0"
End If
If CheckBox_total_fields.Value = True And CheckBox_sum_sheet.Value = False Then
arr_settings(HeaderLine8, 12) = "1"
End If
If CheckBox_total_fields.Value = False And CheckBox_sum_sheet.Value = True Then
arr_settings(HeaderLine8, 12) = "2"
End If
If CheckBox_total_fields.Value = True And CheckBox_sum_sheet.Value = True Then
arr_settings(HeaderLine8, 12) = "3"
End If

If CheckBox_unit.Value = True Then


arr_settings(HeaderLine8, 15) = "1"
Else
arr_settings(HeaderLine8, 15) = "0"
End If

' arr_settings(HeaderLine8, 77)


If CheckBox_contweight1.Value = False And CheckBox_contweight2.Value = False
Then
arr_settings(HeaderLine8, 77) = "0"
End If
If CheckBox_contweight1.Value = True And CheckBox_contweight2.Value = False
Then
arr_settings(HeaderLine8, 77) = "1"
End If
If CheckBox_contweight1.Value = False And CheckBox_contweight2.Value = True
Then
arr_settings(HeaderLine8, 77) = "2"
End If
If CheckBox_contweight1.Value = True And CheckBox_contweight2.Value = True Then
arr_settings(HeaderLine8, 77) = "3"
End If

' arr_settings(HeaderLine8, 80)


If CheckBox_add_qty.Value = True Then
arr_settings(HeaderLine8, 80) = "1"
Else
arr_settings(HeaderLine8, 80) = "0"
End If

' arr_settings(HeaderLine8, 81)


If CheckBox_gaskets.Value = False And CheckBox_nuts.Value = False Then
arr_settings(HeaderLine8, 81) = "0"
End If
If CheckBox_gaskets.Value = True And CheckBox_nuts.Value = False Then
arr_settings(HeaderLine8, 81) = "1"
End If
If CheckBox_gaskets.Value = False And CheckBox_nuts.Value = True Then
arr_settings(HeaderLine8, 81) = "2"
End If
If CheckBox_gaskets.Value = True And CheckBox_nuts.Value = True Then
arr_settings(HeaderLine8, 81) = "3"
End If
If CheckBox_slave.Value = False Then
arr_settings(HeaderLine8, 81) = "4"
End If

' arr_settings(HeaderLine8, 88)


Dim all_bits As String, bit1 As String, bit2 As String, bit3 As String
bit1 = "0"
bit2 = "0"
bit3 = "0"
If CheckBox_CloseExcel.Value = True Then bit1 = "1"
If CheckBox_exportCSV.Value = True Then bit2 = "1"
If CheckBox_DelSumFile.Value = True Then bit3 = "1"
all_bits = bit1 & bit2 & bit3
arr_settings(HeaderLine8, 88) = all_bits

' settings about CSV-file export


arr_settings(HeaderLine8, 84) = TextBox_Path.Text
arr_settings(HeaderLine8, 87) = TextBox_columns.Text

col_nr = ComboBox_countcol.ListIndex
arr_settings(HeaderLine8, 14) = conv_colnr_to_colname(col_nr)

'report path
arr_settings(HeaderLine8, 90) = TextBox_reppath.Text

' Header / Footer -definitions


arr_settings(HeaderLine8, 16) = TextBox_lheader.Text
arr_settings(HeaderLine8, 17) = TextBox_cheader.Text
arr_settings(HeaderLine8, 18) = TextBox_rheader.Text
arr_settings(HeaderLine8, 19) = TextBox_lfooter.Text
arr_settings(HeaderLine8, 20) = TextBox_cfooter.Text
arr_settings(HeaderLine8, 21) = TextBox_rfooter.Text

'Write headerlines from array to the cells of the settings-sheet

Call WriteSettings(1)
Call ReadSettings(1) 'to re-set public settings

Unload Form_Settings
End Sub

Private Sub CancelButton_Click()

Unload Form_Settings
'Form_Settings.Show
End Sub

Sub setup_ListView()
ListView1.ListItems.Clear
ListView1.ColumnHeaders.Clear

ListView1.ColumnHeaders.Add , , "", 20
ListView1.ColumnHeaders.Add , , "Title", 100
ListView1.ColumnHeaders.Add , , "Visibility", 38
ListView1.ColumnHeaders.Add , , "Tag", 80
ListView1.ColumnHeaders.Add , , "Tag from", 63
ListView1.ColumnHeaders.Add , , "Format", 65
ListView1.ColumnHeaders.Add , , "Width", 50
ListView1.ColumnHeaders.Add , , "Sum", 25
ListView1.ColumnHeaders.Add , , "Col_nr", 0

ReDim sett_table(0 To 9, 1 To Col_ArraySize) As Variant


Dim coln As String, desc As String, vis As String, tag As String, pip As
String, _
format As String, wid As String, sumtxt As String

For ii = 1 To Col_ArraySize
coln = arr_settings(HeaderLine1, ii)
col_nr = arr_settings(HeaderLine2, ii) 'get column position
desc = arr_settings(HeaderLine10, ii)
desc = Replace(desc, Chr(10), " ") 'delete <Enter> from string
vis = "Hide"
If arr_settings(HeaderLine3, ii) = "SHOW" Then vis = "Show"
tag = Trim(arr_settings(HeaderLine5, ii))
If LCase(arr_settings(HeaderLine7, ii)) = "sum" Then
sumtxt = "Yes"
Else
sumtxt = "No"
End If

' convert internal-text to menu-text:


Select Case Trim(LCase(arr_settings(HeaderLine9, ii)))
Case tagfrom_options(1, 2)
pip = tagfrom_options(1, 1)
Case tagfrom_options(2, 2)
pip = tagfrom_options(2, 1)
Case tagfrom_options(3, 2)
pip = tagfrom_options(3, 1)
Case tagfrom_options(4, 2)
pip = tagfrom_options(4, 1)
Case tagfrom_options(5, 2)
pip = tagfrom_options(5, 1)
Case tagfrom_options(6, 2)
pip = tagfrom_options(6, 1)
Case Else
pip = tagfrom_options(1, 1) ' Plant Modeller
End Select

Select Case Trim(Left(LCase(arr_settings(HeaderLine4, ii)), 7))


Case "string", ""
format = "String"
Case "float0" 'float
format = "Number, 0 Dec."
Case "float1" 'float
format = "Number, 1 Dec."
Case "float2" 'float
format = "Number, 2 Dec."
Case "float3" 'float
format = "Number, 3 Dec."
Case "date" 'date
format = "Date"
Case "formula" 'formula
format = "formula"
If Left(tag, 1) <> "=" Then tag = "=" & tag ' add a '=' as first
char in the formula
Case Else
format = "String"
End Select

wid = Trim(UCase(arr_settings(HeaderLine6, ii)))


If wid = "" Then wid = "Autofit"
If Right(wid, 3) = "MIN" Then
wid = Left(wid, Len(wid) - 3) & " Min"
End If
If Right(wid, 3) = "MAX" Then
wid = Left(wid, Len(wid) - 3) & " Max"
End If

sett_table(0, col_nr) = coln


sett_table(1, col_nr) = desc
sett_table(2, col_nr) = vis
sett_table(3, col_nr) = tag
sett_table(4, col_nr) = pip
sett_table(5, col_nr) = format
sett_table(6, col_nr) = wid
sett_table(7, col_nr) = sumtxt

Next ii

Dim iCounter As Long, AddListviewLine As Boolean, lv_nr As Long


lv_nr = 0
For iCounter = 1 To Col_ArraySize
AddListviewLine = False
If OptionButton1.Value Then
'Visible columns only
If sett_table(2, iCounter) = "Show" Then
AddListviewLine = True
End If
End If
If OptionButton2.Value Then
'Customised Columns only
If Left$(sett_table(0, iCounter), 8) = "COL_CUST" Then
AddListviewLine = True
End If
End If
If OptionButton3.Value Then
'All Columns
AddListviewLine = True
End If

If (AddListviewLine = True) Then


lv_nr = lv_nr + 1
With ListView1
.ListItems.Add , , iCounter
.ListItems(lv_nr).SubItems(1) = sett_table(1, iCounter)
.ListItems(lv_nr).SubItems(2) = sett_table(2, iCounter)
.ListItems(lv_nr).SubItems(3) = sett_table(3, iCounter)
.ListItems(lv_nr).SubItems(4) = sett_table(4, iCounter)
.ListItems(lv_nr).SubItems(5) = sett_table(5, iCounter)
.ListItems(lv_nr).SubItems(6) = sett_table(6, iCounter)
.ListItems(lv_nr).SubItems(7) = sett_table(7, iCounter)
.ListItems(lv_nr).SubItems(8) = iCounter
End With
End If

Next iCounter

End Sub

Private Sub OptionButton1_Click()


setup_ListView
End Sub

Private Sub OptionButton2_Click()


Call setup_ListView
End Sub

Private Sub OptionButton3_Click()


setup_ListView
End Sub

Private Sub Button_EditRow_Click()


Call edit_row
End Sub

Private Sub ListView1_DblClick()


Call edit_row
End Sub

Private Sub ListView1_Click()


If ListView1.SelectedItem > 0 Then
Button_EditRow.Locked = False
Button_EditRow.Enabled = True
Else
Button_EditRow.Locked = True
Button_EditRow.Enabled = False
End If
End Sub

Sub edit_row()
Button_EditRow.Locked = True
Button_EditRow.Enabled = False
'Set ListView1.SelectedItem = ListView1.ListItems(3)
Load Form_settings2
Form_settings2.Show

End Sub

'=======================================================================
' SETTINGS-SHEET LAYOUT
'
Sub setup_layout()

Dim LastColRow1 As Integer


LastColRow1 = Col_ArraySize

ComboBox_layout.AddItem "LAYOUT1"
For Each WorkSh In ActiveWorkbook.Worksheets
If (UCase(Left(WorkSh.Name, 6)) = "LAYOUT") Then
ComboBox_layout.AddItem WorkSh.Name
End If
Next

'
'set listfocus to current value
'
Dim sett As String, nr As Integer, item As String
nr = 0
sett = arr_settings(HeaderLine8, 8)
With Me.ComboBox_layout
.ListIndex = 0 'default
For i = 0 To .ListCount - 1
item = .List(i)
If item = sett Then
.ListIndex = nr
End If
nr = nr + 1
Next i
End With

TextBox_sheet_hlines.Text = arr_settings(HeaderLine8, 9)
TextBox_sheet_hcolumns.Text = arr_settings(HeaderLine8, 10)

If arr_settings(HeaderLine8, 13) = "hidetitelrow" Then


CheckBox_hidetitelrow.Value = True
Else
CheckBox_hidetitelrow.Value = False
End If

If arr_settings(HeaderLine8, 11) = "columnwidth_via_layoutsheet" Then


CheckBox_colwidth_via_sheet.Value = True
Else
CheckBox_colwidth_via_sheet.Value = False
End If

' Header / Footer -definitions


TextBox_lheader.Text = arr_settings(HeaderLine8, 16)
TextBox_cheader.Text = arr_settings(HeaderLine8, 17)
TextBox_rheader.Text = arr_settings(HeaderLine8, 18)
TextBox_lfooter.Text = arr_settings(HeaderLine8, 19)
TextBox_cfooter.Text = arr_settings(HeaderLine8, 20)
TextBox_rfooter.Text = arr_settings(HeaderLine8, 21)

End Sub

Private Sub ComboBox_layout_Change()


If ComboBox_layout.ListIndex = 0 Then
'LAYOUT1 is selected
TextBox_sheet_hlines.Text = "0"
TextBox_sheet_hlines.Locked = True
TextBox_sheet_hlines.BackColor = &H80000011
TextBox_sheet_hcolumns.Text = "0"
TextBox_sheet_hcolumns.Locked = True
TextBox_sheet_hcolumns.BackColor = &H80000011

CheckBox_hidetitelrow.Locked = True
CheckBox_hidetitelrow.Enabled = False
CheckBox_colwidth_via_sheet.Locked = True
CheckBox_colwidth_via_sheet.Enabled = False
Label5.Enabled = False
Label6.Enabled = False
Else
TextBox_sheet_hlines.Text = arr_settings(HeaderLine8, 9)
TextBox_sheet_hlines.Locked = False
TextBox_sheet_hlines.BackColor = &H80000005
TextBox_sheet_hcolumns.Text = arr_settings(HeaderLine8, 10)
TextBox_sheet_hcolumns.Locked = False
TextBox_sheet_hcolumns.BackColor = &H80000005
CheckBox_hidetitelrow.Locked = False
CheckBox_hidetitelrow.Enabled = True
CheckBox_colwidth_via_sheet.Locked = False
CheckBox_colwidth_via_sheet.Enabled = True
Label5.Enabled = True
Label6.Enabled = True
End If
End Sub

Private Sub TextBox_sheet_hcolumns_KeyPress(ByVal KeyAscii As


MSForms.ReturnInteger)
ch = Chr$(KeyAscii)
If Not (ch >= "0" And ch <= "9") Then
' Cancel the character.
KeyAscii = 0
MsgBox ("Enter numbers only")
End If
End Sub

Private Sub TextBox_sheet_hlines_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)


ch = Chr$(KeyAscii)
If Not (ch >= "0" And ch <= "9") Then
' Cancel the character.
KeyAscii = 0
MsgBox ("Enter numbers only")
End If
End Sub

'=======================================================================
' SETTINGS-SHEET Miscellaneous
'
Sub setup_miscellaneous()

Select Case Trim(arr_settings(HeaderLine8, 12))


Case "0"
CheckBox_total_fields.Value = False
CheckBox_sum_sheet.Value = False
CheckBox_contweight1.Enabled = False
CheckBox_contweight2.Enabled = False
Case "1"
CheckBox_total_fields.Value = True
CheckBox_sum_sheet.Value = False
CheckBox_contweight1.Enabled = True
CheckBox_contweight2.Enabled = False
Case "2"
CheckBox_total_fields.Value = False
CheckBox_sum_sheet.Value = True
CheckBox_contweight1.Enabled = False
CheckBox_contweight2.Enabled = True
Case "3"
CheckBox_total_fields.Value = True
CheckBox_sum_sheet.Value = True
CheckBox_contweight1.Enabled = True
CheckBox_contweight2.Enabled = True
Case Else
CheckBox_total_fields.Value = False
CheckBox_sum_sheet.Value = False
CheckBox_contweight1.Enabled = False
CheckBox_contweight2.Enabled = False
End Select

Select Case Trim(arr_settings(HeaderLine8, 77))


Case "0"
CheckBox_contweight1.Value = False
CheckBox_contweight2.Value = False
Case "1"
CheckBox_contweight1.Value = True
CheckBox_contweight2.Value = False
Case "2"
CheckBox_contweight1.Value = False
CheckBox_contweight2.Value = True
Case "3"
CheckBox_contweight1.Value = True
CheckBox_contweight2.Value = True
Case Else
CheckBox_contweight1.Value = False
CheckBox_contweight2.Value = False
End Select

Select Case Trim(arr_settings(HeaderLine8, 80))


Case "1"
CheckBox_add_qty.Value = True
Case Else
CheckBox_add_qty.Value = False
End Select

Select Case Trim(arr_settings(HeaderLine8, 81))


Case "0"
CheckBox_gaskets.Value = False
CheckBox_nuts.Value = False
CheckBox_slave.Value = True
Case "1"
CheckBox_gaskets.Value = True
CheckBox_nuts.Value = False
CheckBox_slave.Value = True
Case "2"
CheckBox_gaskets.Value = False
CheckBox_nuts.Value = True
CheckBox_slave.Value = True
Case "3"
CheckBox_gaskets.Value = True
CheckBox_nuts.Value = True
CheckBox_slave.Value = True
Case "4"
CheckBox_gaskets.Value = False
CheckBox_nuts.Value = False
CheckBox_slave.Value = False
Case Else
CheckBox_gaskets.Value = False
CheckBox_nuts.Value = False
CheckBox_slave.Value = True
End Select

TextBox_Path.Text = arr_settings(HeaderLine8, 84)


TextBox_seperator.Text = arr_settings(HeaderLine8, 86)
TextBox_columns.Text = arr_settings(HeaderLine8, 87)

TextBox_reppath.Text = arr_settings(HeaderLine8, 90)


Dim all_bits As String, bit1 As String, bit2 As String, bit3 As String
all_bits = arr_settings(HeaderLine8, 88)
bit1 = Mid(all_bits, 1, 1)
bit2 = Mid(all_bits, 2, 1)
bit3 = Mid(all_bits, 3, 1)
If bit1 = "1" Then
CheckBox_CloseExcel.Value = True
Else
CheckBox_CloseExcel.Value = False
End If
If bit2 = "1" Then
CheckBox_exportCSV.Value = True
Else
CheckBox_exportCSV.Value = False
End If
If bit3 = "1" Then
CheckBox_DelSumFile.Value = True
Else
CheckBox_DelSumFile.Value = False
End If

' Freeze / not freeze


If CheckBox_exportCSV.Value = False Then
Label36.Enabled = False
TextBox_seperator.Enabled = False
Label37.Enabled = False
TextBox_columns.Enabled = False
Label38.Enabled = False
DirButton.Enabled = False

TextBox_seperator.Locked = True
TextBox_columns.Locked = True
DirButton.Locked = True
Else
Label36.Enabled = True
TextBox_seperator.Enabled = True
Label37.Enabled = True
TextBox_columns.Enabled = True
Label38.Enabled = True
DirButton.Enabled = True

TextBox_seperator.Locked = False
TextBox_columns.Locked = False
DirButton.Locked = False
End If

Dim SP As Integer, SP_str As String


SP_str = Trim(arr_settings(HeaderLine8, 82))
If SP_str <> "" Then
SP = Val(SP_str)
Else
SP = 0
End If
If SP < 1 Then CheckBox_gaskets.Enabled = False

If Trim(arr_settings(HeaderLine8, 15)) = "1" Then


CheckBox_unit.Value = True
Else
CheckBox_unit.Value = False
End If

Dim tmp_txt As String


ComboBox_countcol.AddItem "(None)"
For iCounter = 1 To Col_ArraySize
tmp_txt = arr_settings(HeaderLine10, iCounter)
tmp_txt = Replace(tmp_txt, Chr(10), " ") 'delete <Enter> from string
ComboBox_countcol.AddItem tmp_txt
Next iCounter

Dim sett As String, col_nr As Integer


sett = Trim(arr_settings(HeaderLine8, 14))
col_nr = conv_to_number(sett)
ComboBox_countcol.ListIndex = col_nr
End Sub

Private Sub CheckBox_total_fields_Click()


If CheckBox_total_fields.Value = False Then
CheckBox_contweight1.Enabled = False
Else
CheckBox_contweight1.Enabled = True
End If
End Sub
Private Sub CheckBox_sum_sheet_Click()
If CheckBox_sum_sheet.Value = False Then
CheckBox_contweight2.Enabled = False
Else
CheckBox_contweight2.Enabled = True
End If
End Sub

Private Sub CheckBox_exportCSV_Click()


If CheckBox_exportCSV.Value = False Then
Label36.Enabled = False
TextBox_seperator.Enabled = False
Label37.Enabled = False
TextBox_columns.Enabled = False
Label38.Enabled = False
DirButton.Enabled = False

TextBox_seperator.Locked = True
TextBox_columns.Locked = True
DirButton.Locked = True
Else
Label36.Enabled = True
TextBox_seperator.Enabled = True
Label37.Enabled = True
TextBox_columns.Enabled = True
Label38.Enabled = True
DirButton.Enabled = True

TextBox_seperator.Locked = False
TextBox_columns.Locked = False
DirButton.Locked = False
End If
End Sub

Private Sub DirButton_click()


Dim DirName
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
DirName = .SelectedItems(1)
End If
End With
If DirName <> "" Then
TextBox_Path.Text = DirName & "\"
End If
End Sub

Private Sub RepDirButton_click()


Dim DirName
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
DirName = .SelectedItems(1)
End If
End With
If DirName <> "" Then
TextBox_reppath.Text = DirName & "\"
End If
End Sub
=================================================================================
Rem Attribute VBA_ModuleType=VBAFormModule
Option VBASupport 1
Private Sub CancelButton_Click()
Unload Form_settings2

End Sub

Private Sub DoneButton_Click()


Dim row As Integer, str As String, index As Integer, col_nr As Integer
row = TextBox_nr.Text
col_nr = Form_Settings.ListView1.ListItems(row).SubItems(8)

sett_table(1, col_nr) = TextBox_Title.Text


'sett_table(2, col_nr) = 'not saving Visabillity, while it doesn't change
Call read_tag_fields(str)
sett_table(3, col_nr) = str
index = ComboBox_TagFrom.ListIndex
str = ComboBox_TagFrom.Column(0, index)
sett_table(4, col_nr) = str
index = ComboBox_Format.ListIndex
str = ComboBox_Format.Column(0, index)
sett_table(5, col_nr) = str
str = TextBox_width.Text
If str = "" Then str = "8" 'default in case it was forgotten to fill in the
field
If ComboBox_width.ListIndex = 0 Then str = "Autofit"
If ComboBox_width.ListIndex = 1 Then str = str
If ComboBox_width.ListIndex = 2 Then str = str & " Min"
If ComboBox_width.ListIndex = 3 Then str = str & " Max"
sett_table(6, col_nr) = str
index = ComboBox_sum.ListIndex
str = ComboBox_sum.Column(0, index)
sett_table(7, col_nr) = str

'Fill ListItems in panel


For i = 1 To 7
With Form_Settings.ListView1
.ListItems(row).SubItems(i) = sett_table(i, col_nr)
End With
Next i

Unload Form_settings2
End Sub

Private Sub ComboBox_width_Change()


If ComboBox_width.ListIndex = 0 Then
TextBox_width.Locked = True
TextBox_width.BackColor = &H80000011
CommandButton_width.Enabled = False
Else
TextBox_width.Locked = False
TextBox_width.BackColor = &H80000005
CommandButton_width.Enabled = True
End If
End Sub

Private Sub CommandButton_width_Click()


Dim retrieve_width As Integer, col As Integer
col = TextBox_nr.Text + ListStartCol - 1
retrieve_width = Columns(col).ColumnWidth
TextBox_width.Value = retrieve_width
End Sub

Private Sub ComboBox_Format_Change()


Call ini_formula
End Sub

Private Sub TextBox_Title_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)


ch = Chr$(KeyAscii)
If ch = ";" Then
' Cancel the semicolon character.
KeyAscii = 0
MsgBox ("Sorry, Semicolon not allowed " & Chr(10) & _
"(Because semicolon will be used as seperator-sign) ")
End If
End Sub

Private Sub TextBox_width_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)


ch = Chr$(KeyAscii)
If Not (ch >= "0" And ch <= "9") Then
' Cancel the character.
KeyAscii = 0
MsgBox ("Enter numbers only")
End If
End Sub

Private Sub TextBox7_Change()


End Sub

Private Sub TextBox6_Change()

End Sub

Private Sub UserForm_Initialize()


Dim selected_index As Long
Dim row As Long, tagstring As String, TagFrom As Integer, formatnr As Integer,
_
sumnr As Integer, widnr As Integer, width_value As Integer, width_str As String
Dim col_nr As Integer
With Form_Settings.ListView1
'loop to find which item is selected, because using "row = .SelectedItem"
'gave problem.
For i = .ListItems.Count To 1 Step -1
If (.ListItems(i).Selected = True) Then row = i
Next i
TextBox_nr.Text = row
TextBox_Title.Text = .ListItems(row).SubItems(1)
TextBox_vis.Text = .ListItems(row).SubItems(2)
tagstring = .ListItems(row).SubItems(3)

Select Case .ListItems(row).SubItems(4)


Case tagfrom_options(1, 1)
TagFrom = 0
Case tagfrom_options(2, 1)
TagFrom = 1
Case tagfrom_options(3, 1)
TagFrom = 2
Case tagfrom_options(4, 1)
TagFrom = 3
Case tagfrom_options(5, 1)
TagFrom = 4
Case tagfrom_options(6, 1)
TagFrom = 5
Case Else
TagFrom = 0
End Select

Select Case .ListItems(row).SubItems(5)


Case "String"
formatnr = 0
Case "Number, 0 Dec."
formatnr = 1
Case "Number, 1 Dec."
formatnr = 2
Case "Number, 2 Dec."
formatnr = 3
Case "Number, 3 Dec."
formatnr = 4
Case "Date"
formatnr = 5
Case "formula"
formatnr = 6
Case Else
formatnr = 0
End Select
width_str = .ListItems(row).SubItems(6)
Select Case Right(width_str, 3)
Case "fit" 'Autofit
widnr = 0
width_value = -1
Case "Min"
widnr = 2
width_value = Left(width_str, Len(width_str) - 4)
Case "Max"
widnr = 3
width_value = Left(width_str, Len(width_str) - 4)
Case Else
widnr = 1
width_value = width_str
End Select

If Right(width_str, 3) = "Min" Then


widnr = 2
width_value = Left(width_str, Len(width_str) - 4)
End If

If .ListItems(row).SubItems(7) = "Yes" Then


sumnr = 1
Else
sumnr = 0
End If

col_nr = .ListItems(row).SubItems(8)
End With

If formatnr = 6 Then ' Choosen format is "formula"


TextBox_Formula.Text = tagstring
Else
Dim t1 As String, t2 As String, t3 As String, t4 As String, t5 As String, _
t6 As String, t7 As String, t8 As String, t9 As String, t10 As String
Call gettag(tagstring, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10)
TextBox_tag1.Text = t1
TextBox_tag2.Text = t2
TextBox_tag3.Text = t3
TextBox_tag4.Text = t4
TextBox_tag5.Text = t5
TextBox_tag6.Text = t6
TextBox_tag7.Text = t7
TextBox_tag8.Text = t8
TextBox_tag9.Text = t9
TextBox_tag10.Text = t10
End If

ComboBox_TagFrom.AddItem tagfrom_options(1, 1)
ComboBox_TagFrom.AddItem tagfrom_options(2, 1)
ComboBox_TagFrom.AddItem tagfrom_options(3, 1)
ComboBox_TagFrom.AddItem tagfrom_options(4, 1)
ComboBox_TagFrom.AddItem tagfrom_options(5, 1)
ComboBox_TagFrom.AddItem tagfrom_options(6, 1)
ComboBox_TagFrom.ListIndex = TagFrom

ComboBox_sum.AddItem "No"
ComboBox_sum.AddItem "Yes"
ComboBox_sum.ListIndex = sumnr
ComboBox_width.AddItem "Autofit"
ComboBox_width.AddItem "Fixed"
ComboBox_width.AddItem "Min."
ComboBox_width.AddItem "Max."
ComboBox_width.ListIndex = widnr
If widnr = 0 Then
TextBox_width.Locked = True
TextBox_width.BackColor = &H80000011
CommandButton_width.Enabled = False
Else
TextBox_width.Locked = False
TextBox_width.BackColor = &H80000005
CommandButton_width.Enabled = True
End If

' unfreeze some fields in case of CUSTOMISED COLUMNS


If Left$(sett_table(0, col_nr), 8) = "COL_CUST" Then
TextBox_tag1.Locked = False
TextBox_tag2.Locked = False
TextBox_tag3.Locked = False
TextBox_tag4.Locked = False
TextBox_tag5.Locked = False
TextBox_tag6.Locked = False
TextBox_tag7.Locked = False
TextBox_tag8.Locked = False
TextBox_tag9.Locked = False
TextBox_tag10.Locked = False
ComboBox_TagFrom.Locked = False 'ComboBox
ComboBox_Format.Locked = False 'ComboBox
ComboBox_sum.Locked = False 'ComboBox
TextBox_tag1.BackColor = &H80000005
TextBox_tag2.BackColor = &H80000005
TextBox_tag3.BackColor = &H80000005
TextBox_tag4.BackColor = &H80000005
TextBox_tag5.BackColor = &H80000005
TextBox_tag6.BackColor = &H80000005
TextBox_tag7.BackColor = &H80000005
TextBox_tag8.BackColor = &H80000005
TextBox_tag9.BackColor = &H80000005
TextBox_tag10.BackColor = &H80000005
ComboBox_TagFrom.BackColor = &H80000005 'ComboBox
ComboBox_Format.BackColor = &H80000005 'ComboBox
ComboBox_sum.BackColor = &H80000005 'ComboBox
End If

ComboBox_Format.AddItem "String"
ComboBox_Format.AddItem "Number, 0 Dec."
ComboBox_Format.AddItem "Number, 1 Dec."
ComboBox_Format.AddItem "Number, 2 Dec."
ComboBox_Format.AddItem "Number, 3 Dec."
ComboBox_Format.AddItem "Date"
ComboBox_Format.AddItem "formula"
ComboBox_Format.ListIndex = formatnr

Call ini_formula

End Sub
Private Sub ini_formula()
If ComboBox_Format.ListIndex = 6 Then ' Choosen format is "formula"
Frame1.Visible = False
TextBox_Formula.Visible = True
Label33.Visible = True
ValidateFormulaButton.Visible = True
TextBoxHelpFormula.Visible = True
Else
Frame1.Visible = True
TextBox_Formula.Visible = False
Label33.Visible = False
ValidateFormulaButton.Visible = False
TextBoxHelpFormula.Visible = False
End If
End Sub

Sub gettag(tagstr As String, t1 As String, t2 As String, t3 As String, _


t4 As String, t5 As String, t6 As String, t7 As String, t8 As String, _
t9 As String, t10 As String)

'get t9 and t10 ( the part after the ~)


Dim t9_t10 As String
Dim SplitStringA() As String, SplitStringB() As String, SplitString() As String
If InStr(tagstr, "~") > 0 Then
SplitStringA = Split(tagstr, "~")
tagstr = SplitStringA(0)
t9_t10 = SplitStringA(1)
If InStr(t9_t10, "+") > 0 Then
SplitStringB = Split(t9_t10, "+")
t9 = Trim(SplitStringB(0))
t10 = Trim(SplitStringB(1))
Else
t9 = Trim(t9_t10)
End If
End If

If InStr(tagstr, "+") > 0 Then


SplitString = Split(tagstr, "+")
CountOccurances = UBound(SplitString) - LBound(SplitString) + 1
t1 = Trim(SplitString(0))
If CountOccurances > 1 Then t2 = Trim(SplitString(1))
If CountOccurances > 2 Then t3 = Trim(SplitString(2))
If CountOccurances > 3 Then t4 = Trim(SplitString(3))
If CountOccurances > 4 Then t5 = Trim(SplitString(4))
If CountOccurances > 5 Then t6 = Trim(SplitString(5))
If CountOccurances > 6 Then t7 = Trim(SplitString(6))
If CountOccurances > 7 Then t8 = Trim(SplitString(7))
Else
t1 = Trim(tagstr)
End If

End Sub

Sub read_tag_fields(tag As String)


If ComboBox_Format.ListIndex = 6 Then ' Choosen format is "formula"
tag = TextBox_Formula.Text
Exit Sub
End If
Dim t1 As String, t2 As String, t3 As String, t4 As String, t5 As String, _
t6 As String, t7 As String, t8 As String, t9 As String, t10 As String
t1 = Trim(TextBox_tag1.Text)
t2 = Trim(TextBox_tag2.Text)
t3 = Trim(TextBox_tag3.Text)
t4 = Trim(TextBox_tag4.Text)
t5 = Trim(TextBox_tag5.Text)
t6 = Trim(TextBox_tag6.Text)
t7 = Trim(TextBox_tag7.Text)
t8 = Trim(TextBox_tag8.Text)
t9 = Trim(TextBox_tag9.Text)
t10 = Trim(TextBox_tag10.Text)

' when tag begins with a "=" then put a space in front of it to avoid
interpretation as formula
If Left(t1, 1) = "=" Then t1 = " " & t1
If Left(t2, 1) = "=" Then t2 = " " & t2
If Left(t3, 1) = "=" Then t3 = " " & t3
If Left(t4, 1) = "=" Then t4 = " " & t4
If Left(t5, 1) = "=" Then t5 = " " & t5
If Left(t6, 1) = "=" Then t6 = " " & t6
If Left(t7, 1) = "=" Then t7 = " " & t7
If Left(t8, 1) = "=" Then t8 = " " & t8
If Left(t9, 1) = "=" Then t9 = " " & t9
If Left(t10, 1) = "=" Then t10 = " " & t10

tag = t1
If t1 = "" Then
Exit Sub
Else
If t2 <> "" Then
tag = tag & "+" & t2
If t3 <> "" Then
tag = tag & "+" & t3
If t4 <> "" Then
tag = tag & "+" & t4
If t5 <> "" Then
tag = tag & "+" & t5
If t6 <> "" Then
tag = tag & "+" & t6
If t7 <> "" Then
tag = tag & "+" & t7
If t8 <> "" Then
tag = tag & "+" & t8
End If
End If
End If
End If
End If
End If
End If
End If
If t9 <> "" Then
tag = tag & "~" & t9
If t10 <> "" Then tag = tag & "+" & t10
End If

'Fix: if first char is ' then put space before it otherwise excel will
' skip this when putting value to a cell.
If Left(tag, 1) = "'" Then tag = " " & tag
End Sub

Private Sub ValidateFormulaButton_Click()


Dim tagstring As String, ListStartRow As String, str As String
ListStartRow = Trim(arr_settings(HeaderLine8, 9))
If ListStartRow = "" Or ListStartRow = "0" Then ListStartRow = "3"
tagstring = TextBox_Formula.Text
tagstring = Replace(tagstring, "[R]", ListStartRow)

On Error GoTo ErrorHandlingLabel


Range("HH1").NumberFormat = "General"
Range("HH1").Formula = tagstring
On Error GoTo 0 ' set back to the default error handling in VB
Range("HH1").Value = ""
MsgBox "Formula is OK"
Exit Sub

ErrorHandlingLabel:
MsgBox "Warning, formula is NOT valid: " & tagstring
Range("HH1").Value = ""
On Error GoTo 0 ' set back to the default error handling in VB
End Sub
============================================================================
Rem Attribute VBA_ModuleType=VBAFormModule
Option VBASupport 1
Dim ListContent(1 To 91) As Variant

Private Sub Label2_Click()

End Sub

Private Sub UserForm_Initialize()

Dim item As String


Call ReadSettings(1)

Me.LabelVisibleCol.Clear ' remove existing content


Me.LabelHiddenCol.Clear

' fill ColTitel() array retrieved from arr_settings


For iCounter = 1 To Col_ArraySize
col_nr = arr_settings(HeaderLine2, iCounter) 'get column position
item = arr_settings(HeaderLine10, iCounter)
item = Replace(item, Chr(10), " ") 'delete <Enter> from string
ColTitel(col_nr) = item
'remember all column positions
ColPos(iCounter) = col_nr
Next iCounter

' fill ColHideShow() array retrieved from current sheet and setup panel
For iCounter = 1 To Col_ArraySize
item = ColTitel(iCounter)
If Columns(iCounter + ListStartCol - 1).EntireColumn.Hidden = True Then
Me.LabelHiddenCol.AddItem item
Else
Me.LabelVisibleCol.AddItem item
End If
Next iCounter

End Sub

Private Sub btnOK_Click()


'get last column
Dim LastRowColA As Long, LastColRow1 As Long

Application.ScreenUpdating = False
Me.Hide
Dim WorkSh As Worksheet
Dim remembered_activesheetname As String, remembered_activecell As String
remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address

'
'scan which items are selected to be shown, and fill array
'

Dim c_nr As Integer, titel_desc As String


c_nr = 0
With Me.LabelVisibleCol
For i = 0 To .ListCount - 1
c_nr = c_nr + 1
item = .List(i)
For iCounter = 1 To Col_ArraySize
titel_desc = arr_settings(HeaderLine10, iCounter)
titel_desc = Replace(titel_desc, Chr(10), " ") 'delete <Enter> from
string
If item = titel_desc Then
arr_settings(HeaderLine2, iCounter) = c_nr 'set new column
number
arr_settings(HeaderLine3, iCounter) = "SHOW" 'set Show/Hide
End If
Next iCounter
Next i
End With

With Me.LabelHiddenCol
For i = 0 To .ListCount - 1
c_nr = c_nr + 1
item = .List(i)
For iCounter = 1 To Col_ArraySize
titel_desc = arr_settings(HeaderLine10, iCounter)
titel_desc = Replace(titel_desc, Chr(10), " ") 'delete <Enter> from
string
If item = titel_desc Then
arr_settings(HeaderLine2, iCounter) = c_nr 'set new column
number
arr_settings(HeaderLine3, iCounter) = "HIDE" 'set Show/Hide
End If
Next iCounter
Next i
End With

' Declaration
Dim nr_of_sheets As Long
nr_of_sheets = Sheets.Count
ReDim TotalFields(1 To nr_of_sheets, 1 To 12) As Variant

Dim SheetNr As Long


SheetNr = 0
For Each WorkSh In ActiveWorkbook.Worksheets
If (filtersheets(WorkSh.Name) = False) Then
SheetNr = SheetNr + 1
WorkSh.Select
LastRowColA = last_row_nr_methodB(ListStartLine, ListStartCol) 'call to
function last_row_nr()
LastColRow1 = last_col_nr(ListStartCol) 'call to function
last_col_nr()

'
' re-arrange complete sheet according new position and show/hide
'
Call ReArrange(LastRowColA, LastColRow1, SheetNr)

'activate cell A1, to avoid that previous selection is still active


Range("A1").Select
'set active window to left upper corner
ActiveWindow.ScrollRow = 1
ActiveWindow.ScrollColumn = 1

End If
Next

Call WriteSettings(0)

'HIDE sheets
Call HideSheets(1)

Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select

Application.ScreenUpdating = True
Me.Hide
Unload Form_ShowColumns
End Sub

Private Sub btnCancel_Click()


Me.Hide
Unload Form_ShowColumns

End Sub

Private Sub btnSelect1_Click()


' moves selected items from the HiddenColumns listbox to the Visible Columns
listbox
Dim i As Integer
Application.ScreenUpdating = False

'deselect first all items in visible column ( to see clearly which one is
added)
With Me.LabelVisibleCol
For i = .ListCount - 1 To 0 Step -1
If .Selected(i) Then
.Selected(i) = False
End If
Next i
End With

With Me.LabelHiddenCol
For i = .ListCount - 1 To 0 Step -1
If .Selected(i) Then
.Selected(i) = False
item = .List(i)
Me.LabelVisibleCol.AddItem item
Me.LabelVisibleCol.Selected(Me.LabelVisibleCol.ListCount - 1) =
True
.RemoveItem i

End If
Next i

End With
Application.ScreenUpdating = True
End Sub

Private Sub btnDeSelect1_Click()


' moves selected items from the VisibleColumns listbox to the HiddenColumns listbox

Dim i As Integer
Application.ScreenUpdating = False

'deselect first all items in visible column ( to see clearly which one is
added)
With Me.LabelHiddenCol
For i = .ListCount - 1 To 0 Step -1
If .Selected(i) Then
.Selected(i) = False
End If
Next i
End With

With Me.LabelVisibleCol
'li = .ListIndex
For i = .ListCount - 1 To 0 Step -1
If .Selected(i) Then
item = .List(i)
Me.LabelHiddenCol.AddItem item
Me.LabelHiddenCol.Selected(Me.LabelHiddenCol.ListCount - 1) = True
.RemoveItem i

End If
Next i

'If li >= .ListCount Then li = .ListCount - 1


'.ListIndex = li
End With
Application.ScreenUpdating = True
End Sub

Private Sub btnSelectAll_Click()


' moves all selected items from the HiddenColumns listbox to the VisibleColumns
listbox
Dim i As Integer
With Me.LabelHiddenCol
If .ListCount > 0 Then
Application.ScreenUpdating = False
For i = 0 To .ListCount - 1
Me.LabelVisibleCol.AddItem .List(i)
Next i
.Clear
Application.ScreenUpdating = True
End If
End With
End Sub

Private Sub btnDeSelectAll_Click()


' moves all selected items from the VisibleColumns listbox to the HiddenColumns
listbox

Dim i As Integer
With Me.LabelVisibleCol
If .ListCount > 0 Then
Application.ScreenUpdating = False
For i = 0 To .ListCount - 1
Me.LabelHiddenCol.AddItem .List(i)
Next i
.Clear
Application.ScreenUpdating = True
End If
End With
End Sub

Private Sub LabelHiddenCol_DblClick(ByVal Cancel As MSForms.ReturnBoolean)


btnSelect1_Click
End Sub

Private Sub LabelVisibleCol_DblClick(ByVal Cancel As MSForms.ReturnBoolean)


btnDeSelect1_Click
End Sub

Private Sub btnDown_Click()


Dim i As Integer
Dim leaveAlone As Boolean
Dim pos As Long
Dim Temp As String

pos = LabelVisibleCol.ListCount - 1

For i = LabelVisibleCol.ListCount - 1 To 0 Step -1

leaveAlone = False
If LabelVisibleCol.Selected(i) Then

If i = pos Then
leaveAlone = True
End If

pos = pos - 1
If Not leaveAlone Then
Temp = LabelVisibleCol.List(i + 1)
LabelVisibleCol.List(i + 1) = LabelVisibleCol.List(i)
LabelVisibleCol.List(i) = Temp
LabelVisibleCol.ListIndex = i + 1
LabelVisibleCol.Selected(i) = False
LabelVisibleCol.Selected(i + 1) = True
End If
End If
Next

End Sub

Private Sub btnUp_Click()


Dim i As Long
Dim leaveAlone As Boolean
Dim pos As Long
Dim Temp As String

pos = 0

For i = 0 To LabelVisibleCol.ListCount - 1
leaveAlone = False

If LabelVisibleCol.Selected(i) Then

If i = pos Then
leaveAlone = True
End If
pos = pos + 1

If leaveAlone = False Then


Temp = LabelVisibleCol.List(i - 1)
LabelVisibleCol.List(i - 1) = LabelVisibleCol.List(i)
LabelVisibleCol.List(i) = Temp
LabelVisibleCol.ListIndex = i - 1
LabelVisibleCol.Selected(i) = False
LabelVisibleCol.Selected(i - 1) = True
End If
End If
Next
End Sub

Sub ReArrange(LastRowColA As Long, LastColRow1 As Long, SheetNr As Long)


'
're-arrange current sheet to new col-postions and hide/show settings
' this according the settings retrieved from settings-array
'

'get last row and column


Dim nr_of_rows As Long, nr_of_cols As Integer, Titel_row_nr As Integer
Titel_row_nr = ListStartLine - 2
If Titel_row_nr < 2 Then Titel_row_nr = 1
nr_of_rows = LastRowColA - ListStartLine + 1
nr_of_cols = LastColRow1 - ListStartCol + 1

'read in whole sheet into an array


Dim arr_in As Variant 'MUST be variant
ReDim arr_outB(1 To nr_of_rows, 1 To nr_of_cols) As Variant
arr_in = Range(Cells(ListStartLine, ListStartCol), Cells(LastRowColA,
LastColRow1)).Value

'
' Just before writing the array to the sheet we now (re-)arrange the order of
the columns
'
Dim ColNr_old As Integer, ColNr_new As Integer
For iCol = 1 To nr_of_cols
ColNr_old = ColPos(iCol)
ColNr_new = arr_settings(HeaderLine2, iCol)

For iRow = 1 To nr_of_rows


arr_outB(iRow, ColNr_new) = arr_in(iRow, ColNr_old)
Next iRow
Next iCol

'
'write back to the sheet the array arr_outB
'
Call SetColFormat(1) 'set format correct otherwise value might get mutilated
(0011 becomes 11)
Range(Cells(ListStartLine, ListStartCol), Cells(LastRowColA,
LastColRow1)).Value = arr_outB
'Call Rounding(LastRowColA)

Dim nr_of_sheets As Long


nr_of_sheets = Sheets.Count
ReDim TotalFields(1 To nr_of_sheets, 1 To 12) As Variant

Call Layout_general(ActiveSheet, True, SheetNr)

Cells(1, 1).Select 'just select "A1" in order to get active cel to so far down

End Sub

===================================================================================
========
Rem Attribute VBA_ModuleType=VBAFormModule
Option VBASupport 1
Private Sub UserForm_activate()

If StartedFromListControl = True Then


'wait 1 sec. to give system enough time for last call which hides the panel
Application.Wait (Now + TimeValue("00:00:01")) 'wait 1 sec.

Dim remembered_activesheetname As String, remembered_activecell As String


remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address

'Turn off calculation and screenupdating to speed up the macro.


Application.ScreenUpdating = False

Dim SheetDistr_Nr As Integer


SheetDistr_Nr = Form_ListControl.ListToSheets.ListIndex
Dim SumR1 As Integer, SumR2 As Integer, SumR3 As Integer, SumR4 As Integer,
SumR5 As Integer
SumR1 = Form_ListControl.Sum1.ListIndex
SumR2 = Form_ListControl.Sum2.ListIndex
SumR3 = Form_ListControl.Sum3.ListIndex
SumR4 = Form_ListControl.Sum4.ListIndex
SumR5 = Form_ListControl.Sum5.ListIndex

Dim SortR1 As Integer, SortR2 As Integer, SortR3 As Integer


SortR1 = Form_ListControl.Sort1.ListIndex
SortR2 = Form_ListControl.Sort2.ListIndex
SortR3 = Form_ListControl.Sort3.ListIndex

arr_settings(HeaderLine8, 1) = conv_colnr_to_colname(SheetDistr_Nr)
arr_settings(HeaderLine8, 2) = conv_colnr_to_colname(SumR1)
arr_settings(HeaderLine8, 3) = conv_colnr_to_colname(SumR2)
arr_settings(HeaderLine8, 4) = conv_colnr_to_colname(SumR3)
arr_settings(HeaderLine8, 5) = conv_colnr_to_colname(SortR1)
arr_settings(HeaderLine8, 6) = conv_colnr_to_colname(SortR2)
arr_settings(HeaderLine8, 7) = conv_colnr_to_colname(SortR3)
arr_settings(HeaderLine8, 78) = conv_colnr_to_colname(SumR4)
arr_settings(HeaderLine8, 79) = conv_colnr_to_colname(SumR5)

Call WriteSettings(0)

PctDone = 0 'set how much procent is done in pogress-bar


Call Progress(PctDone)
Call ListControl(SheetDistr_Nr, SumR1, SumR2, SumR3, SumR4, SumR5, SortR1,
SortR2, SortR3, False)

Call Progress(1)
'wait 1 sec. to give user enough time to see that 100% is reached.
'Application.Wait (Now + TimeValue("00:00:01")) 'wait 1 sec.
Unload waitpanel

On Error Resume Next


AppActivate ("Microsoft excel")

Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select

Application.ScreenUpdating = True

End If

End Sub

Private Sub CancelButton_Click()

MsgBox "flag test1"


End Sub

===================================================================================
Rem Attribute VBA_ModuleType=VBAModule
Option VBASupport 1
Sub Macro_Main_Import()

'
'initialize
'
If NotAllowedToStartMacroFromHere(True) Then Exit Sub
StartedFromListControl = False
Call init(1)

' Define Importfile-name: same as current workbook, only without the extension
".sum"
Dim ThisWorkbookPath As String, ThisWorkbookName As String, Importfile As
String
ThisWorkbookPath = ThisWorkbook.Path
ThisWorkbookName = ThisWorkbook.Name
ThisWorkbookName = Left(ThisWorkbookName, Len(ThisWorkbookName) - 4) 'cut off
the extension ".xls"
Importfile = ThisWorkbookPath & "\" & ThisWorkbookName & ".sum"
'check if importfile exists:
If Dir(Importfile) = "" Then
MsgBox "Warning, Could not find file " & Importfile
Exit Sub
End If

Application.ScreenUpdating = False
Application.Visible = False 'hide excel application, so only wait-panel is
visible

waitpanel.LabelProgress.Width = 0
Load waitpanel
waitpanel.Show vbModeless
Call Progress(0.01)

Call ImportSettings(ThisWorkbookName, Importfile)


Call Progress(0.02)

' Open Importfile as semicolon seprated file


' name is same as current excel workbook, only without the extension ".sum"
Workbooks.OpenText Filename:=Importfile, Origin:=xlWindows,
startrow:=QueryLines + HeaderLines _
, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=True, Comma:=False _
, Space:=False, Other:=False, FieldInfo:=Array(Array(1, frm(1)), _
Array(2, frm(2)), Array(3, frm(3)), Array(4, frm(4)), Array(5, frm(5)),
Array(6, frm(6)), _
Array(7, frm(7)), Array(8, frm(8)), Array(9, frm(9)), Array(10, frm(10)),
Array(11, frm(11)), _
Array(12, frm(12)), Array(13, frm(13)), Array(14, frm(14)), Array(15,
frm(15)), Array(16, frm(16)), _
Array(17, frm(17)), Array(18, frm(18)), Array(19, frm(19)), Array(20,
frm(20)), Array(21, frm(21)), _
Array(22, frm(22)), Array(23, frm(23)), Array(24, frm(24)), Array(25,
frm(25)), Array(26, frm(26)), _
Array(27, frm(27)), Array(28, frm(28)), Array(29, frm(29)), Array(30,
frm(30)), Array(31, frm(31)), _
Array(32, frm(32)), Array(33, frm(33)), Array(34, frm(34)), Array(35,
frm(35)), Array(36, frm(36)), _
Array(37, frm(37)), Array(38, frm(38)), Array(39, frm(39)), Array(40,
frm(40)), Array(41, frm(41)), _
Array(42, frm(42)), Array(43, frm(43)), Array(44, frm(44)), Array(45,
frm(45)), Array(46, frm(46)), _
Array(47, frm(47)), Array(48, frm(48)), Array(49, frm(49)), Array(50,
frm(50)), Array(51, frm(51)), _
Array(52, frm(52)), Array(53, frm(53)), Array(54, frm(54)), Array(55,
frm(55)), Array(56, frm(56)), _
Array(57, frm(57)), Array(58, frm(58)), Array(59, frm(59)), Array(60,
frm(60)), Array(61, frm(61)), _
Array(62, frm(62)), Array(63, frm(63)), Array(64, frm(64)), Array(65,
frm(65)), Array(66, frm(66)), _
Array(67, frm(67)), Array(68, frm(68)), Array(69, frm(69)), Array(70,
frm(70)), Array(71, frm(71)), _
Array(72, frm(72)), Array(73, frm(73)), Array(74, frm(74)), Array(75,
frm(75)), Array(76, frm(76)), _
Array(77, frm(77)), Array(78, frm(78)), Array(79, frm(79)), Array(80,
frm(80)), Array(81, frm(81)), _
Array(82, frm(82)), Array(83, frm(83)), Array(84, frm(84)), Array(85,
frm(85)), Array(86, frm(86)), _
Array(87, frm(87)), Array(88, frm(88)), Array(89, frm(89)), Array(90,
frm(90))), _
DecimalSeparator:=".", ThousandsSeparator:=" "

Call Progress(0.03)

'
'Copy content of this imported excel workbook into current sheet and delete
that workbook
'
Dim Importfile_excel As String
Importfile_excel = ThisWorkbookName & ".sum"
Application.DisplayAlerts = False 'to avoid message about clipboard when
coping
Windows(Importfile_excel).Activate 'activate imported excel workbook
Cells.Select 'select whole sheet
Selection.Copy 'copy whole sheet to clipboard
Windows(ThisWorkbook.Name).Activate 'activate current workbook
If Not WorksheetExists("import") Then
Sheets.Add 'Add new sheet
ActiveSheet.Name = "import" 'Rename new sheet
End If
Sheets("import").Select 'select the sheet with the name "import"
Cells.Select 'select whole sheet
ActiveSheet.Paste 'paste content of clipboard to the sheet
Windows(Importfile_excel).Activate 'activate imported excel workbook
'
Call Progress(0.04)
Application.CutCopyMode = False 'Clear Clipboard. VERY GOOD LINE: it will
fasten up
' following SAVE/CLOSE very much (no time
instead of 2 sec)
ActiveWindow.Close savechanges:=0 'close imported excel workbook
Call Progress(0.05)
Application.DisplayAlerts = True 'set original value back ("True")

'
'setup sheets; distribute import sheets to the differen sheets and setup layout
'
Dim SheetDistr_Nr As Integer, SumR1 As Integer, SumR2 As Integer, SumR3 As
Integer, SumR4 As Integer
Dim SumR5 As Integer, SortR1 As Integer, SortR2 As Integer, SortR3 As Integer,
sett As String
sett = arr_settings(HeaderLine8, 1)
SheetDistr_Nr = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 2)
SumR1 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 3)
SumR2 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 4)
SumR3 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 78)
SumR4 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 79)
SumR5 = conv_to_number(sett)

sett = arr_settings(HeaderLine8, 5)
SortR1 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 6)
SortR2 = conv_to_number(sett)
sett = arr_settings(HeaderLine8, 7)
SortR3 = conv_to_number(sett)

Call ListControl(SheetDistr_Nr, SumR1, SumR2, SumR3, SumR4, SumR5, SortR1,


SortR2, SortR3, True)

Dim all_bits As String, bit1 As String, bit2 As String, bit3 As String


all_bits = arr_settings(HeaderLine8, 88)
bit1 = Mid(all_bits, 1, 1)
bit2 = Mid(all_bits, 2, 1)
bit3 = Mid(all_bits, 3, 1)
If bit2 = "1" Then
Call ExportToCSV(False) ' export to CSV (and repress messages popping up)

End If

'SAVE
Application.CutCopyMode = False 'Clear Clipboard. VERY GOOD LINE: it
will fasten up
' following SAVE/CLOSE vermy much (no
time instead of 2 sec)
ActiveWorkbook.Save
Application.CutCopyMode = True ' set value back to orginal value

Call Progress(1)
'wait 1 sec. to give user enough time to see that 100% is reached.
'Application.Wait (Now + TimeValue("00:00:01")) 'wait 1 sec.

Unload waitpanel

If bit1 = "1" Then


If Workbooks.Count = 1 Then
Application.DisplayAlerts = False
Application.Quit
Application.DisplayAlerts = True
Else
Application.WindowState = xlMinimized ' just minimize window while
there are still other workbooks active
Application.ScreenUpdating = True
Application.Visible = True
Application.DisplayAlerts = False
ThisWorkbook.Close savechanges:=False
Application.DisplayAlerts = True

End If
Else
Application.WindowState = xlMaximized 'Maxmize excel window
Application.ScreenUpdating = True
Application.Visible = True
End If
End Sub

Function conv_to_number(sett As String) As Integer


conv_to_number = 0
If sett = "" Or sett = "0" Then Exit Function
For iCounter = 1 To Col_ArraySize
If UCase(sett) = arr_settings(HeaderLine1, iCounter) Then
conv_to_number = iCounter
End If
Next iCounter
End Function

Function conv_colnr_to_colname(ColNr As Integer) As String


conv_colnr_to_colname = "0"
If ColNr > 0 And ColNr <= Col_ArraySize Then
conv_colnr_to_colname = arr_settings(HeaderLine1, ColNr)
End If
End Function

Sub closing(arg As String)


'clean up
Unload waitpanel
'Application.WindowState = xlMinimized 'Minimize excel window
Application.WindowState = xlMaximized 'Maxmize excel window
Application.ScreenUpdating = True
Application.Visible = True
Application.CutCopyMode = True

End Sub

'Distribute the list from sheet "import" to the different sheets,


'this distributed groups will be defined according DistrColNr
Sub SetupSheets(DistrColNr As Integer, setup_importsheet As Boolean)

'setup lautout of import sheet (much layout is copied to other sheets form
there)
If (setup_importsheet) Then Call Layout_of_import_sheet

'Distribute the list from sheet "import" to the different sheets


Call DistributeTosHeets(DistrColNr) 'according DistrColNr

'create or update custom menu


Call CreateMenu(1)

PctDone = 0.25
Call Progress(PctDone) 'set how much procent is done in pogress-bar

End Sub

Sub DistributeTosHeets(DistrColNr As Integer)


'Distribute the list from sheet "import" to the different sheets,
'this distributed groups will be defined according defined DistrColNr

'first DELETE existing SHEETS, except sheet "import" & "settings"

'un-hide sheet "import", because we only can delete the old sheets when
'there is at least one sheet left visible
Sheets("import").Visible = True

Dim WorkSh As Worksheet


For Each WorkSh In ActiveWorkbook.Worksheets
If UCase(WorkSh.Name) = "TOTAL" Then Call totalsheet_clear(1)
If (filtersheets(WorkSh.Name) = False) Then
Application.DisplayAlerts = False
WorkSh.Delete
Application.DisplayAlerts = True
End If
Next

'get last row and last column of sheet "import"


Dim LastRowColA As Long, LastColRow1 As Integer
Sheets("import").Activate
LastRowColA = last_row_nr(1, 1) 'call to function last_row_nr()
LastColRow1 = last_col_nr(1)

If (LastRowColA > 65536 - 10) Then


MsgBox "Warning: Imported material-file contains more rows then excel can
handle (65536)."
End If

If DistrColNr = 0 Then
'selected DistrColNr is 0 (= None)
Rows(2 & ":" & LastRowColA).Select
Range("A" & 2 & ":" & Column2Char(LastColRow1) & LastRowColA).Select
Selection.Copy
Sheets.Add 'Add new sheet
ActiveSheet.Name = "All" 'Rename new sheet
Range(Column2Char(ListStartCol) & ListStartLine).Select
ActiveSheet.Paste
Call Progress(0.25)
'exit Subroutine:
Exit Sub
End If

PctDone = 0.09
Call Progress(PctDone)

'First Sort that column in sheet "import" in order to find the unique values
Dim SortCelValue As String, SortCelValuePrev As String
Rows("2:" & LastRowColA).Select
Selection.Sort Key1:=Cells(2, DistrColNr), Order1:=xlAscending,
Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom

'scan every cell in (sorted) column 'DistrColNr' and if value changes,


'then copy that range into new sheet
Dim BeginRow As Long, endrow As Long, PctDoneTemp As Single, iCounter As Long
Dim celvalue As String, ValuePrev As String
BeginRow = 2
For iCounter = 2 To LastRowColA + 1
Sheets("import").Select
ValuePrev = celvalue 'store previous celvalue
celvalue = Cells(iCounter, DistrColNr).Value
If celvalue = "" And iCounter <> LastRowColA + 1 Then
celvalue = "empty"
End If
If ((LCase(celvalue) <> LCase(ValuePrev)) And (iCounter > 2)) Then
endrow = iCounter - 1
Range("A" & BeginRow & ":" & Column2Char(LastColRow1) & endrow).Select
Selection.Copy
If WorksheetExists(ValuePrev) Then
MsgBox ("Warning, Could not add sheet <" & ValuePrev & ">.")
Exit Sub
End If
Sheets.Add 'Add new sheet
Call RenameCurrSheet(ValuePrev) 'Rename new sheet
Range(Column2Char(ListStartCol) & ListStartLine).Select
ActiveSheet.Paste
BeginRow = iCounter
End If

'set how much procent is done in pogress-bar (Fill till 0.25 )


PctDoneTemp = PctDone + ((0.25 - PctDone) * iCounter / LastRowColA)
Call Progress(PctDoneTemp)
Next iCounter

End Sub

Private Sub RenameCurrSheet(sheet_name As String)

'get rid of strange character in sheetname which excel cannot handle when
renaming sheet

Dim i As Long
For i = 1 To Len(sheet_name)
Select Case Mid$(sheet_name, i, 1)
Case "?"
Mid$(sheet_name, i, 1) = "."
Case "/"
Mid$(sheet_name, i, 1) = "."
Case "\"
Mid$(sheet_name, i, 1) = "."
Case "*"
Mid$(sheet_name, i, 1) = "."
Case "["
Mid$(sheet_name, i, 1) = "."
Case "]"
Mid$(sheet_name, i, 1) = "."
Case Else

End Select
Next

If Len(sheet_name) > 31 Then sheet_name = Left$(sheet_name, 30) + "~"

If WorksheetExists(sheet_name) Then
MsgBox ("Warning, Could not add sheet <" & sheet_name & "> because this
sheet already exists.")
sheet_name = sheet_name & "_WARNING_"
End If
ActiveSheet.Name = sheet_name 'Rename new sheet
End Sub

Private Sub Layout_of_import_sheet()


'arrange layout of the sheet, like borders. Here only the sheet named "import" will
be set up
' Because later when copying from this sheet to another sheet then the layout is
copied along

'get last row and last column


Dim LastRowColA As Long, LastColRow1 As Long
LastRowColA = last_row_nr(1, 1) 'call to function last_row_nr()
LastColRow1 = last_col_nr(1)

If (LastColRow1 < 3) Then


MsgBox ("Warning, expected a bit more columns then only " & LastColRow1 _
& " , in sheet:" & sheetname & "aborting ,layout setup in this sheet.")
'When there is only 2 column then excel give error at 'xlInsideVertical'
Exit Sub
End If

Call Progress(0.06)

If UCase(arr_settings(HeaderLine8, 8)) <> "LAYOUT2" Then


'
' make boxlines around all cells
'
' Layout whole range: Borders (thin thickness)
Range(Cells(1, 1), Cells(LastRowColA, LastColRow1)).Select
Call NormalBorder(1)

'
' Layout rows: make left & right -borders of every row thick
'
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With

Call Progress(0.07)

'thick outer border:


'OuterBorderThick

'add sort-buttons in title-row


For Each cel In Range(Cells(1, 1), Cells(1, LastColRow1))
ActiveSheet.Buttons.Add(0, 0, 0, 0).Select
With Selection
.Top = cel.Top
.Left = cel.Left
.Height = cel.Height
.Width = cel.Width
.Text = cel.Value
.Font.Bold = True
.OnAction = "'MacroSort """ & cel.Address & """'"

End With
Next cel

End If

'
' Layout title row: make bold text, filling, and thick outer Border
'
Range(Cells(1, 1), Cells(1, LastColRow1)).Select
Selection.RowHeight = 35
'bold text:
For Each cel In Selection
cel.Font.Bold = True
Next cel
' filling:
With Selection.Interior
.ColorIndex = 15 'light-gray
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With

'Freeze titel-row when scrolling:


ActiveWindow.splitrow = 1
ActiveWindow.FreezePanes = True

Call Progress(0.08)

End Sub

Sub Layout_general(sheetname As Worksheet, quick As Boolean, SheetNr As Long)


'arrange layout of the sheet, like borders,

'get last row and column


Dim LastRowColA As Long, LastColRow1 As Long, nr_of_rows As Long, nr_of_cols As
Integer
Dim layoutsheet As String, hidetitelrow As Boolean
Dim columnwidth_via_layoutsheet As Boolean

LastRowColA = last_row_nr(ListStartLine, ListStartCol) 'call to function


last_row_nr()
LastColRow1 = last_col_nr(ListStartCol) 'call to function last_col_nr()
nr_of_rows = LastRowColA - ListStartLine + 1
nr_of_cols = LastColRow1 - ListStartCol + 1

'
'Read settings
'
layoutsheet = UCase(arr_settings(HeaderLine8, 8))
If LCase(arr_settings(HeaderLine8, 11)) = "columnwidth_via_layoutsheet" Then
columnwidth_via_layoutsheet = True
Else
columnwidth_via_layoutsheet = False
End If

If LCase(arr_settings(HeaderLine8, 13)) = "hidetitelrow" Then


hidetitelrow = True
Else
hidetitelrow = False
End If

Dim col_nr As Integer, titel As String, Titel_row_nr As Integer


ReDim Titel_row(1 To 1, 1 To nr_of_cols) As Variant
For nCounter = 1 To Col_ArraySize
titel = arr_settings(HeaderLine10, nCounter)
col_nr = arr_settings(HeaderLine2, nCounter) 'get column position
Titel_row(1, col_nr) = titel
Next nCounter
Titel_row_nr = SheetHeaderLines + 1

'
'copy headerlines of the layoutsheet to current sheet (content and width)
'
If WorksheetExists(layoutsheet) Then
Sheets(layoutsheet).Visible = True
Call sheet_sel(layoutsheet) 'select the sheet with that name

If columnwidth_via_layoutsheet = True Then


Dim iCounter As Long
ReDim c_width(1 To LastColRow1) As Integer
For iCounter = 1 To LastColRow1
c_width(iCounter) = Columns(iCounter).ColumnWidth
Next iCounter
End If

'selecting the rows and copy it


Application.DisplayAlerts = False 'to avoid message about clipboard
when coping
If SheetHeaderLines > 0 Then Rows(1 & ":" & SheetHeaderLines).Copy
Sheets(sheetname.Name).Activate
Range("A1").Select
If SheetHeaderLines > 0 Then ActiveSheet.Paste 'paste
content of clipboard to the sheet
Sheets(sheetname.Name).Activate
Application.DisplayAlerts = False 'to avoid message about clipboard
when coping

If columnwidth_via_layoutsheet = True Then


For iCounter = 1 To LastColRow1
Columns(iCounter).ColumnWidth = c_width(iCounter)
Next iCounter
End If
End If

'
'Titel-labels: description
'
Range(Cells(Titel_row_nr, ListStartCol), Cells(Titel_row_nr,
LastColRow1)).Value = Titel_row
'
' Titel-labels: make bold text, filling, and thick outer Border
'
Range(Cells(Titel_row_nr, ListStartCol), Cells(Titel_row_nr,
LastColRow1)).Select
Selection.RowHeight = 35
'bold text:
For Each cel In Selection
cel.Font.Bold = True
Next cel

If hidetitelrow = False Then


'so skip this when Titelrow is hidden anyway, because the outerline messes
up
'then bottom-line of the row directly above it
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With

OuterBorderThick

End If

'Titel row: pattern filling:


With Selection.Interior
.ColorIndex = 36 'light-yellow
.ColorIndex = 15 'light-gray
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With

'Titel-row: HIDE
If hidetitelrow = True Then
Rows(Titel_row_nr).Select
Selection.EntireRow.Hidden = True
End If

'
' Select layoutsheet additional sheet definitions
'
Select Case layoutsheet
Case "LAYOUT1"
Call Layout1(sheetname, LastRowColA, LastColRow1, quick) 'default
layout

Case "LAYOUT2"
Call Layout2(sheetname, LastRowColA, LastColRow1, quick)

Case Else
Call Layout1(sheetname, LastRowColA, LastColRow1, quick) 'default
layout
End Select

Call set_named_cell(sheetname)

'
' Add total fields (like total mass total length, total COG)
' (also activates that sheet
'
Call addtotalfields(LastRowColA, LastColRow1, SheetNr)

'
' Column width
'
If columnwidth_via_layoutsheet = False Then
Call Columns_Width(Titel_row_nr, LastRowColA, LastColRow1)
End If

'
'DECIMALS presenting ( and also assign formula )
'
Call Rounding(LastRowColA)

'
'HIDE / SHOW the columns
'
Call Columns_HideShow(LastRowColA, LastColRow1)

If quick = False Then


'Freeze titelrow. In oder to leave the titels presented when scrolling down
Dim splitrow As Integer
splitrow = ListStartLine - 2
If splitrow < 1 Then splitrow = 1
ActiveWindow.splitrow = splitrow
ActiveWindow.FreezePanes = True
End If

'Fill_counter_column
Dim counter As Long, sett As String, cc As Integer
sett = arr_settings(HeaderLine8, 14)
counter_col_nr = conv_to_number(sett)
If counter_col_nr > 0 Then
cc = arr_settings(HeaderLine2, counter_col_nr) 'get column position
cc = cc + ListStartCol - 1
counter = 0
For rr = ListStartLine To LastRowColA
counter = counter + 1
Cells(rr, cc).Value = counter
Next rr
End If

Range("A1").Select

End Sub

Sub Layout1(sheetname As Worksheet, LastRowColA As Long, LastColRow1 As Long, quick


As Boolean)

Dim nr_of_rows As Long, nr_of_cols As Integer, Titel_row_nr As Integer


nr_of_rows = LastRowColA - ListStartLine + 1
nr_of_cols = LastColRow1 - ListStartCol + 1
Titel_row_nr = ListStartLine - 2
If Titel_row_nr < 2 Then Titel_row_nr = 1

'retrieve Projname from excel-filename (so, after "_" and without extension)
Dim projectname As String, UnderScorePosition As Integer, pos As Integer
projectname = ThisWorkbook.Name
UnderScorePosition = InStr(1, projectname, "_") 'get postion of "_"
If UnderScorePosition > 0 Then
pos = UnderScorePosition + 1 'begin after "_"
projectname = Mid(projectname, pos, Len(projectname) - (pos - 1) - 4)
End If

sheet_leftheader = arr_settings(HeaderLine8, 46)


sheet_centerheader = arr_settings(HeaderLine8, 47)
sheet_rightheader = arr_settings(HeaderLine8, 48)
sheet_leftfooter = arr_settings(HeaderLine8, 49)
sheet_centerfooter = arr_settings(HeaderLine8, 50)
sheet_rightfooter = arr_settings(HeaderLine8, 51)

' If sheet_leftheader = "" Then sheet_leftheader = "&B" & "NUPAS-CADMATIC


Piping" & Chr(10) & "MATERIAL REPORT"
' If sheet_centerheader = "" Then sheet_centerheader = "PROJECT: " &
projectname
' If sheet_leftfooter = "" Then sheet_leftfooter = "&F"
' If sheet_centerfooter = "" Then sheet_centerfooter = "Prepared on: &D"
' If sheet_rightfooter = "" Then sheet_rightfooter = "Page &P"

If quick = False Then


With ActiveSheet.PageSetup
.PrintTitleRows = ActiveSheet.Rows(Titel_row_nr).Address
.Orientation = xlLandscape
.PrintHeadings = False
.LeftHeader = sheet_leftheader
.CenterHeader = sheet_centerheader
.RightHeader = sheet_rightheader
.LeftFooter = sheet_leftfooter
.CenterFooter = sheet_centerfooter
.RightFooter = sheet_rightfooter
End With
End If
'thick outer border:
Range(Cells(ListStartLine, ListStartCol), Cells(LastRowColA,
LastColRow1)).Select
OuterBorderThick

End Sub
Sub Layout2(sheetname As Worksheet, LastRowColA As Long, LastColRow1 As Long, quick
As Boolean)

Dim layoutsheet As String, Titel_row_nr As Integer


Dim nr_of_rows As Long, nr_of_cols As Integer
nr_of_rows = LastRowColA - ListStartLine + 1
nr_of_cols = LastColRow1 - ListStartCol + 1

If quick = True Then Exit Sub

' Empty row: filling:


Titel_row_nr = SheetHeaderLines + 1
Range(Cells(Titel_row_nr + 1, 1), Cells(Titel_row_nr + 1, LastColRow1 +
1)).Select
With Selection.Interior
.ColorIndex = 15 'light-gray
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With

'
' BORDERS: Outer border is double line and inner cells normal line
'
Range(Cells(ListStartLine, ListStartCol), Cells(LastRowColA,
LastColRow1)).Select
Call InnerNormal_OuterDouble_Border(1)

'
'BORDERS: column 16 should be total empty only left and right line is double
line
'
Dim sel_col_nr As Integer
sel_col_nr = ListStartCol + 16 - 1
Range(Cells(ListStartLine, sel_col_nr), Cells(LastRowColA, sel_col_nr)).Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlDouble
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
Selection.Borders(xlEdgeTop).LineStyle = xlNone
Selection.Borders(xlEdgeBottom).LineStyle = xlNone
With Selection.Borders(xlEdgeRight)
.LineStyle = xlDouble
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
'
'BORDERS: column 17 should be total empty only left and right line is double
line
'
sel_col_nr = ListStartCol + 17 - 1
Range(Cells(ListStartLine, sel_col_nr), Cells(LastRowColA, sel_col_nr)).Select
With Selection.Borders(xlEdgeRight)
.LineStyle = xlDouble
.Weight = xlThick
.ColorIndex = xlAutomatic
End With

'printpreview
With ActiveSheet.PageSetup
.Orientation = xlLandscape
.Zoom = 43
.LeftMargin = Application.InchesToPoints(0.3)
.RightMargin = Application.InchesToPoints(0.3)
End With

'zoom
ActiveWindow.Zoom = 75

End Sub

Private Sub OuterBorderThick()


Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
End Sub

Sub NormalBorder(arg As Integer)


Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With

End Sub

Sub InnerNormal_OuterDouble_Border(arg As String)


Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlDouble
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlDouble
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlDouble
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlDouble
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
End Sub

Sub ImportSettings(ThisWorkbookName As String, Importfile As String)

' Open Importfile and read the semicolon seprated file,


'only the header (which are the first few lines containing the settings)
'
'There are 2 parts:
'- the query-lines, they should be all in the first column only (nr of lines is
unknown)
' these will be read just by opening the file
'- the headerlines, a fix number of lines will a lot of columns (seperated by
";")
'
ReDim query_lines_firstCol(1 To QueryLinesMax, 1 To 1) As Variant
Dim FileNum As Integer, tLine As String, line_nr As Integer, stop_reading As
Boolean
FileNum = FreeFile() ' next file number
Open Importfile For Input Access Read Shared As #FileNum ' open the file for
reading
stop_reading = False
line_nr = 0
Do While Not EOF(FileNum) And stop_reading = False
Line Input #FileNum, tLine ' read a line from the text file
If Left(tLine, 4) = "COL_" Then
stop_reading = True
Else
line_nr = line_nr + 1
query_lines_firstCol(line_nr, 1) = tLine
End If
Loop ' until the last line is read
QueryLines = line_nr
Close #FileNum ' close the file

Workbooks.OpenText Filename:=Importfile, Origin:=xlMSDOS, startrow:=QueryLines


+ 1 _
, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=True, Comma:=False _
, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 2), Array(2, 2), _
Array(3, 2), Array(4, 2), Array(5, 2), Array(6, 2), Array(7, 2), Array(8,
2), Array(9, 2), _
Array(10, 2), Array(11, 2), Array(12, 2), Array(13, 2), Array(14, 2),
Array(15, 2), _
Array(16, 2), Array(17, 2), Array(18, 2), Array(19, 2), Array(20, 2),
Array(21, 2), _
Array(22, 2), Array(23, 2), Array(24, 2), Array(25, 2), Array(26, 2),
Array(27, 2), _
Array(28, 2), Array(29, 2), Array(30, 2), Array(31, 2), Array(32, 2),
Array(33, 2), _
Array(34, 2), Array(35, 2), Array(36, 2), Array(37, 2), Array(38, 2),
Array(39, 2), _
Array(40, 2), Array(41, 2), Array(42, 2), Array(43, 2), Array(44, 2),
Array(45, 2), _
Array(46, 2), Array(47, 2), Array(48, 2), Array(49, 2), Array(50, 2),
Array(51, 2), _
Array(52, 2), Array(53, 2), Array(54, 2), Array(55, 2), Array(56, 2),
Array(57, 2), _
Array(58, 2), Array(59, 2), Array(60, 2), Array(61, 2), Array(62, 2),
Array(63, 2), _
Array(64, 2), Array(65, 2), Array(66, 2), Array(67, 2), Array(68, 2),
Array(69, 2), _
Array(70, 2), Array(71, 2), Array(72, 2), Array(73, 2), Array(74, 2),
Array(75, 2), _
Array(76, 2), Array(77, 2), Array(78, 2), Array(79, 2), Array(80, 2),
Array(81, 2), _
Array(82, 2), Array(83, 2), Array(84, 2), Array(85, 2), Array(86, 2),
Array(87, 2), _
Array(88, 2), Array(89, 2), Array(90, 2)), _
DecimalSeparator:=".", ThousandsSeparator:=" "

'
'Copy first lines of this imported excelWorkbook into curr sheet,& delete that
workbook
'
Dim Importfile_excel As String
Importfile_excel = ThisWorkbookName & ".sum"
Application.DisplayAlerts = False 'to avoid message about clipboard when
coping
Windows(Importfile_excel).Activate 'activate imported excel workbook
Rows("1:" & HeaderLines).Select 'select the header (which is the first
few lines)
Selection.Copy 'copy whole sheet to clipboard
Windows(ThisWorkbook.Name).Activate 'activate current workbook
If Not WorksheetExists("settings") Then
Sheets.Add 'Add new sheet
ActiveSheet.Name = "settings" 'Rename new sheet
End If
Sheets("settings").Select 'select the sheet with the name
"settings"
Rows(QueryLines + 1 & ":" & QueryLines + HeaderLines).Select
ActiveSheet.Paste 'paste content of clipboard to the sheet

'also write Querylines to the settings-sheet


Range(Cells(1, 1), Cells(QueryLines, 1)).Value = query_lines_firstCol

Windows(Importfile_excel).Activate 'activate imported excel workbook


Application.CutCopyMode = False 'Clear Clipboard. VERY GOOD LINE: it will
fasten up
' following SAVE/CLOSE vermy much (no
time instead of 2 sec)

ActiveWindow.Close savechanges:=0 'close imported excel workbook


Application.DisplayAlerts = True 'set original value back ("True")

Call ReadSettings(0)

End Sub

Sub ReadSettings(SwitchBackToSheet As String)

If Not WorksheetExists("settings") Then


Exit Sub
End If

If SwitchBackToSheet = "1" Then


Dim remembered_activesheetname As String, remembered_activecell As String
remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address
Application.ScreenUpdating = False
End If

Sheets("settings").Visible = True
Sheets("settings").Select

Call get_number_of_query_lines(1)

'read in whole settings-sheet into an array


'Dim arr_settings As Variant 'MUST be variant (is already declared as public)
ReDim arr_settings(1 To HeaderLines, 1 To Col_ArraySize) As Variant
arr_settings = Range(Cells(QueryLines + 1, 1), Cells(QueryLines + HeaderLines,
Col_ArraySize)).Value

Dim default_desc As String, cust_desc As String, counter_empty As Integer


counter_empty = 0
For iCounter = 1 To Col_ArraySize
cust_desc = arr_settings(HeaderLine10, iCounter)
default_desc = arr_settings(HeaderLine11, iCounter)
If Trim(cust_desc) = "" Then
cust_desc = default_desc
End If
'stil empty? then fill it with "empty__<number>"
If Trim(cust_desc) = "" Then
counter_empty = counter_empty + 1
cust_desc = " < empty__" & counter_empty & " >"
End If
' put back to array:
arr_settings(HeaderLine10, iCounter) = cust_desc
Next iCounter

'only for compat reason add new columns: (because they migh miss when
rrp-file is form old version)
If Trim(arr_settings(HeaderLine1, COL_CUST41)) = "" Then
arr_settings(HeaderLine1, COL_CUST41) = "COL_CUST41"
arr_settings(HeaderLine2, COL_CUST41) = first_free_pos()
arr_settings(HeaderLine3, COL_CUST41) = "HIDE"
arr_settings(HeaderLine4, COL_CUST41) = "string"
End If
If Trim(arr_settings(HeaderLine1, COL_CUST42)) = "" Then
arr_settings(HeaderLine1, COL_CUST42) = "COL_CUST42"
arr_settings(HeaderLine2, COL_CUST42) = first_free_pos()
arr_settings(HeaderLine3, COL_CUST42) = "HIDE"
arr_settings(HeaderLine4, COL_CUST42) = "string"
End If
If Trim(arr_settings(HeaderLine1, COL_OBIREF)) = "" Then
arr_settings(HeaderLine1, COL_OBIREF) = "COL_OBIREF"
arr_settings(HeaderLine2, COL_OBIREF) = first_free_pos()
arr_settings(HeaderLine3, COL_OBIREF) = "HIDE"
arr_settings(HeaderLine4, COL_OBIREF) = "string"
End If

'write desc back to settings sheet


Range(Cells(QueryLines + 1, 1), Cells(QueryLines + HeaderLines,
Col_ArraySize)).Value = arr_settings

'read layout settings


Dim read_nr As Integer
read_nr = arr_settings(HeaderLine8, 9)
If read_nr > 0 Then SheetHeaderLines = read_nr
read_nr = arr_settings(HeaderLine8, 10)
If read_nr > 0 Then SheetHeaderColumns = read_nr
ListStartLine = SheetHeaderLines + 3 ' begin-row of the list-area
ListStartCol = SheetHeaderColumns + 1 ' begin-column of the list-area

For iCounter = 1 To Col_ArraySize


Select Case Trim(arr_settings(HeaderLine1, iCounter))
Case "COL_CAT"
COL_CAT = iCounter
Case "COL_PLI"
COL_PLI = iCounter
Case "COL_SPN"
COL_SPN = iCounter
Case "COL_SYS"
COL_SYS = iCounter
Case "COL_DE"
COL_DE = iCounter
Case "COL_DD"
COL_DD = iCounter
Case "COL_FII"
COL_FII = iCounter
Case "COL_ART"
COL_ART = iCounter
Case "COL_VPO"
COL_VPO = iCounter
Case "COL_BPL"
COL_BPL = iCounter
Case "COL_LEN"
COL_LEN = iCounter
Case "COL_QTY"
COL_QTY = iCounter
Case "COL_GT"
COL_GT = iCounter
Case "COL_MAS"
COL_MAS = iCounter
Case "COL_CGX"
COL_CGX = iCounter
Case "COL_CGY"
COL_CGY = iCounter
Case "COL_CGZ"
COL_CGZ = iCounter
Case "COL_CONM"
COL_CONM = iCounter
Case "COL_CONX"
COL_CONX = iCounter
Case "COL_CONY"
COL_CONY = iCounter
Case "COL_CONZ"
COL_CONZ = iCounter
Case "COL_FLUID"
COL_FLUID = iCounter
Case "COL_CONV"
COL_CONV = iCounter
Case "COL_TOTM"
COL_TOTM = iCounter
Case "COL_TOTX"
COL_TOTX = iCounter
Case "COL_TOTY"
COL_TOTY = iCounter
Case "COL_TOTX"
COL_TOTX = iCounter
Case "COL_TOTY"
COL_TOTY = iCounter
Case "COL_TOTZ"
COL_TOTZ = iCounter
Case "COL_OBI"
COL_OBI = iCounter
Case "COL_PID"
COL_PID = iCounter
Case "COL_CORP"
COL_CORP = iCounter
Case "COL_DIMT"
COL_DIMT = iCounter
Case "COL_SLAVE"
COL_SLAVE = iCounter
Case "COL_MAT"
COL_MAT = iCounter
Case "COL_SPC"
COL_SPC = iCounter
Case "COL_CMD"
COL_CMD = iCounter
Case "COL_NAM"
COL_NAM = iCounter
Case "COL_LOX"
COL_LOX = iCounter
Case "COL_LOY"
COL_LOY = iCounter
Case "COL_LOZ"
COL_LOZ = iCounter
Case "COL_HUL"
COL_HUL = iCounter
Case "COL_MTH"
COL_MTH = iCounter
Case "COL_SCO"
COL_SCO = iCounter
Case "COL_UNIT"
COL_UNIT = iCounter
Case "COL_IDN"
COL_IDN = iCounter
Case "COL_MOT"
COL_MOT = iCounter
Case "COL_EMP1"
COL_EMP1 = iCounter
Case "COL_EMP2"
COL_EMP2 = iCounter
Case "COL_IPO"
COL_IPO = iCounter
Case "COL_CUST1"
COL_CUST1 = iCounter
Case "COL_CUST2"
COL_CUST2 = iCounter
Case "COL_CUST3"
COL_CUST3 = iCounter
Case "COL_CUST4"
COL_CUST4 = iCounter
Case "COL_CUST5"
COL_CUST5 = iCounter
Case "COL_CUST6"
COL_CUST6 = iCounter
Case "COL_CUST7"
COL_CUST7 = iCounter
Case "COL_CUST8"
COL_CUST8 = iCounter
Case "COL_CUST9"
COL_CUST9 = iCounter
Case "COL_CUST10"
COL_CUST10 = iCounter
Case "COL_CUST11"
COL_CUST11 = iCounter
Case "COL_CUST12"
COL_CUST12 = iCounter
Case "COL_CUST13"
COL_CUST13 = iCounter
Case "COL_CUST14"
COL_CUST14 = iCounter
Case "COL_CUST15"
COL_CUST15 = iCounter
Case "COL_CUST16"
COL_CUST16 = iCounter
Case "COL_CUST17"
COL_CUST17 = iCounter
Case "COL_CUST18"
COL_CUST18 = iCounter
Case "COL_CUST19"
COL_CUST19 = iCounter
Case "COL_CUST20"
COL_CUST20 = iCounter
Case "COL_CUST21"
COL_CUST21 = iCounter
Case "COL_CUST22"
COL_CUST22 = iCounter
Case "COL_CUST23"
COL_CUST23 = iCounter
Case "COL_CUST24"
COL_CUST24 = iCounter
Case "COL_CUST25"
COL_CUST25 = iCounter
Case "COL_CUST26"
COL_CUST26 = iCounter
Case "COL_CUST27"
COL_CUST27 = iCounter
Case "COL_CUST28"
COL_CUST28 = iCounter
Case "COL_CUST29"
COL_CUST29 = iCounter
Case "COL_CUST30"
COL_CUST30 = iCounter
Case "COL_CUST31"
COL_CUST31 = iCounter
Case "COL_CUST32"
COL_CUST32 = iCounter
Case "COL_CUST33"
COL_CUST33 = iCounter
Case "COL_CUST34"
COL_CUST34 = iCounter
Case "COL_CUST35"
COL_CUST35 = iCounter
Case "COL_CUST36"
COL_CUST36 = iCounter
Case "COL_CUST37"
COL_CUST37 = iCounter
Case "COL_CUST38"
COL_CUST38 = iCounter
Case "COL_CUST39"
COL_CUST39 = iCounter
Case "COL_CUST40"
COL_CUST40 = iCounter
Case "COL_CUST41"
COL_CUST41 = iCounter
Case "COL_CUST42"
COL_CUST42 = iCounter
Case "COL_OBIREF"
COL_OBIREF = iCounter
Case ""
Case "COL_EMP3" ' for compatibilly reason with older versions, June
2009
COL_IPO = iCounter
Case "COL_EMP2" ' for compatibilly reason with older versions, Jan
2010
COL_BLK = iCounter
Case "COL_EMP1" ' for compatibilly reason with older versions, Jan
2010
COL_SPO = iCounter
Case Else
MsgBox "unknown COLUMN found in header: <" &
arr_settings(HeaderLine1, iCounter) & "> col=" & iCounter
End Select
Next iCounter

' Read the FORMAT-setting of the columns and store it in a public array
Call GetColFormat(1)
Sheets("settings").Visible = False

If SwitchBackToSheet = "1" Then


Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select
Application.ScreenUpdating = True
End If

End Sub
Sub WriteSettings(SwitchBackToSheet As String)
If Not WorksheetExists("settings") Then
Exit Sub
End If

If SwitchBackToSheet = "1" Then


Dim remembered_activesheetname As String, remembered_activecell As String
remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address
Application.ScreenUpdating = False
End If

Sheets("settings").Visible = True
Sheets("settings").Select
'read in whole settings-sheet into an array
'Dim arr_settings As Variant 'MUST be variant (is already declared as public)

' Do not write the description: < empty_xx >


ReDim arr_headerlin10_tmp(1 To Col_ArraySize) As Variant
For nn = 1 To Col_ArraySize
arr_headerlin10_tmp(nn) = arr_settings(HeaderLine10, nn)
If Left(arr_settings(HeaderLine10, nn), 9) = " < empty_" Then
arr_settings(HeaderLine10, nn) = ""
End If
Next nn

'Write headerlines from array to the cells of the settings-sheet


Range(Cells(QueryLines + 1, 1), Cells(QueryLines + HeaderLines,
Col_ArraySize)).Value = arr_settings

Sheets("settings").Visible = False
If SwitchBackToSheet = "1" Then
Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select
Application.ScreenUpdating = True
End If

End Sub

Function WorksheetExists(wksName As String) As Boolean


On Error Resume Next
WorksheetExists = CBool(Len(Worksheets(wksName).Name) > 0)
On Error GoTo 0 ' set back to the default error handling in VB
End Function

Sub MacroSort(Celladdress As String)


Application.ScreenUpdating = False

'get last row and last column


Dim LastRowColA As Long, LastColRow1 As Long
LastRowColA = last_row_nr(ListStartLine, ListStartCol) 'call to function
last_row_nr()

'Sort according CurrentColumn


Rows(ListStartLine & ":" & LastRowColA).Select
Selection.Sort Key1:=Range(Celladdress), Order1:=xlAscending, Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom

'activate current cell


Range(Celladdress).Activate

Application.ScreenUpdating = True
End Sub
Sub PresentDecimals(SelColumn As Integer, LastRowColA As Long, NrOfDecimals As
Integer)
Range(Cells(ListStartLine, SelColumn), Cells(LastRowColA, SelColumn)).Select
If NrOfDecimals = 0 Then Selection.NumberFormat = "0"
If NrOfDecimals = 1 Then Selection.NumberFormat = "0.0"
If NrOfDecimals = 2 Then Selection.NumberFormat = "0.00"
If NrOfDecimals = 3 Then Selection.NumberFormat = "0.000"
End Sub
Function Column2Char(ColumnNumber As Integer) As String
If ColumnNumber > 26 Then

' 1st character: Subtract 1 to map the characters to 0-25,


' but you don't have to remap back to 1-26
' after the 'Int' operation since columns
' 1-26 have no prefix letter

' 2nd character: Subtract 1 to map the characters to 0-25,


' but then must remap back to 1-26 after
' the 'Mod' operation by adding 1 back in
' (included in the '65')

Column2Char = Chr(Int((ColumnNumber - 1) / 26) + 64) & _


Chr(((ColumnNumber - 1) Mod 26) + 65)
Else
' Columns A-Z
Column2Char = Chr(ColumnNumber + 64)
End If
End Function

Sub GetColFormat(arg As String)


'
' Read the FORMAT-setting of the columns and store it in a public array
'
For iCounter = 1 To Col_ArraySize
read_frm = arr_settings(HeaderLine4, iCounter)
read_frm = LCase(Left(read_frm, 4))
Select Case Trim(LCase(read_frm))
Case "stri", ""
frm(iCounter) = 2 'means text (string)
Case "floa" 'float
frm(iCounter) = 1 'means general
Case "date" 'date
frm(iCounter) = 5 'means YMD date
Case "form" 'formula
frm(iCounter) = 1 'means general
Case Else
MsgBox "unknown Format found in header: <" &
arr_settings(HeaderLine4, iCounter) & " > col = " & iCounter
frm(iCounter) = 2 'means text
End Select
Next iCounter

End Sub

Sub SetColFormat(arg As String)


'
' Set the FORMAT of the columns, these Format-settings are read from a public
array
'
Dim col_nr As Integer
For iCounter = 1 To Col_ArraySize
col_nr = arr_settings(HeaderLine2, iCounter) 'get column position
col_nr = col_nr + ListStartCol - 1
Select Case frm(iCounter)
Case 1 'means Format 'general'
Columns(col_nr).NumberFormat = "General"
Case 2 'means text (string)
Columns(col_nr).NumberFormat = "@"
Case 5 'means YMD date
Columns(col_nr).NumberFormat = "yyyy/mm/dd"
Case Else
Columns(col_nr).NumberFormat = "General"
End Select
Next iCounter

End Sub

Sub Rounding(LastRowColA As Long)

'
'DECIMALS presenting ( and also call to assign formula)
'
Dim col_nr As Integer, declaration As String, decimals As String, col_nr_unit
As Integer
Dim celformat As String, row As Long, unit As String, pcs As String, TheFormula
As String

For iCounter = 1 To Col_ArraySize


declaration = arr_settings(HeaderLine4, iCounter)
If Left(declaration, 5) = "float" Then
decimals = Mid$(declaration, 6, 1)
col_nr = arr_settings(HeaderLine2, iCounter) 'get column position
col_nr = col_nr + ListStartCol - 1
If decimals = "0" Then Call PresentDecimals(col_nr, LastRowColA, 0)
If decimals = "1" Then Call PresentDecimals(col_nr, LastRowColA, 1)
If decimals = "2" Then Call PresentDecimals(col_nr, LastRowColA, 2)
If decimals = "3" Then Call PresentDecimals(col_nr, LastRowColA, 3)

pcs = UCase(Mid$(declaration, 7, 3))


If pcs = "PCS" Then
col_nr_unit = arr_settings(HeaderLine2, COL_UNIT) 'get column
position of COL_UNIT
col_nr_unit = col_nr_unit + ListStartCol - 1
For row = ListStartLine To LastRowColA
unit = UCase(Cells(row, col_nr_unit).Value)
If unit = "PCS" Then
Cells(row, col_nr).NumberFormat = "0"
End If
Next row
End If

End If
If declaration = "formula" Then
col_nr = arr_settings(HeaderLine2, iCounter) 'get column position
col_nr = col_nr + ListStartCol - 1
TheFormula = "=" & arr_settings(HeaderLine5, iCounter)
TheFormula = Replace(TheFormula, "[R]", ListStartLine)
If TheFormula <> "" Then Call AssignFormula(col_nr, LastRowColA,
TheFormula)
End If
Next iCounter

End Sub
Sub AssignFormula(SelColumn As Integer, LastRowColA As Long, TheFormula As String)
On Error GoTo ErrorHandlingLabel
Range(Cells(ListStartLine, SelColumn), Cells(LastRowColA, SelColumn)).Select
Range(Cells(ListStartLine, SelColumn), Cells(LastRowColA, SelColumn)).Formula =
TheFormula
On Error GoTo 0 ' set back to the default error handling in VB
Exit Sub

ErrorHandlingLabel:
MsgBox "Warning the following formula has a problem (so check via report
control the formula) : " & TheFormula
On Error GoTo 0 ' set back to the default error handling in VB
End Sub

Sub Columns_HideShow(LastRowColA As Long, LastColRow1 As Long)


'
' Hide or Show all columns
'
For iCounter = 1 To Col_ArraySize
col_nr = arr_settings(HeaderLine2, iCounter) 'get column position
col_nr = col_nr + ListStartCol - 1
If arr_settings(HeaderLine3, iCounter) = "SHOW" Then
'un-hide (Show) the columns
Columns(col_nr).EntireColumn.Hidden = False
Else
'hide the columns
Columns(col_nr).EntireColumn.Hidden = True
End If
Next iCounter
End Sub

Sub Columns_Width(Titel_row_nr As Integer, LastRowColA As Long, LastColRow1 As


Long)
'
' Column width
'
'autofit column width
Rows(Titel_row_nr & ":" & LastRowColA + 7).Select '+7 to include the total-
fields
Selection.Columns.AutoFit

Dim Format_sett As String, width_str As String, MinMax As String


For iCounter = 1 To Col_ArraySize
col_nr = arr_settings(HeaderLine2, iCounter) 'get column position
col_nr = col_nr + ListStartCol - 1
Format_sett = Trim(UCase(arr_settings(HeaderLine6, iCounter)))

If Format_sett <> "AUTOFIT" And Format_sett <> "" Then


'
' Value could a number only or added with MIN or MAX, examples:
' 12MIN
' 15
' 30MAX
'
Pos_of_M = InStr(Format_sett, "M")
If Pos_of_M > 0 Then
width_str = Left(Format_sett, Pos_of_M - 1)
MinMax = Mid$(Format_sett, Pos_of_M, 3)
Else
width_str = Format_sett
MinMax = ""
End If

'col width
If MinMax = "" Then
Columns(col_nr).ColumnWidth = width_str
End If

'MIN col width


If MinMax = "MIN" Then
If Columns(col_nr).ColumnWidth < width_str Then
Columns(col_nr).ColumnWidth = width_str
End If
End If

'MAX col width


If MinMax = "MAX" Then
If Columns(col_nr).ColumnWidth > width_str Then
Columns(col_nr).ColumnWidth = width_str
End If
End If

End If
Next iCounter
End Sub

Function get_obi_from_pipefile(guid As String) As String

get_obi_from_pipefile = ""
If InStr(guid, "-") <= 0 Then
Exit Function
End If

Dim SplitString() As String


SplitString = Split(guid, "-")
get_obi_from_pipefile = SplitString(0)

End Function

Function get_obi(obi As String) As String

Dim str_len As Integer


str_len = Len(obi)
Do While str_len < 8
obi = "0" + obi
str_len = Len(obi)
Loop

get_obi = obi

End Function

Function isspool(IsoMfileName As String) As Boolean


isspool = True
If InStr(IsoMfileName, ".") > 0 Then

Dim SplitString() As String, nr As Integer


SplitString = Split(IsoMfileName, ".")
nr = SplitString(1)
If nr = 0 Then isspool = False

End If
End Function

'Select sheet
Sub sheet_sel(sh_name As String)
If sh_name <> ActiveSheet.Name Then
If WorksheetExists(sh_name) Then
If Sheets(sh_name).Visible = True Then Sheets(sh_name).Select
End If
End If
End Sub

Sub get_number_of_query_lines(arg As Integer)


ReDim FirstColumn(1 To QueryLinesMax) As Variant
Dim iCounter As Integer, found As Boolean
QueryLines = 0
iCounter = 0
found = False
FirstColumn = Range(Cells(1, 1), Cells(QueryLinesMax, 1)).Value
Do While found = False And iCounter <= QueryLinesMax
iCounter = iCounter + 1
If Left(Trim(FirstColumn(iCounter, 1)), 4) = "COL_" Then
found = True
QueryLines = iCounter - 1
End If
Loop ' until

End Sub

Sub set_named_cell(sheetname As Worksheet)


Dim named_cell As String, rest As String, namedcell_Address As String,
namedcell_Name As String
Dim CommaPosition As Integer, reference_to_namedcell_Address As String,
condition As String
named_cell = arr_settings(HeaderLine8, 89)
If named_cell = "" Then Exit Sub
CommaPosition = InStr(1, named_cell, ",") 'get postion of ","
If CommaPosition > 0 Then
namedcell_Address = Left(named_cell, CommaPosition - 1)
rest = Mid(named_cell, CommaPosition + 1)
CommaPosition = InStr(1, rest, ",") 'get postion of ","
If CommaPosition > 0 Then
namedcell_Name = Left(rest, CommaPosition - 1)
Else
namedcell_Name = rest
End If
End If
If (namedcell_Address = "") Or (namedcell_Name = "") Then Exit Sub

Dim first_sheetNO As Integer


first_sheetNO = SheetNo_of_firstdatasheet()
If first_sheetNO = sheetname.index Then
Range(namedcell_Address).Name = namedcell_Name
If CustomPropertyDoesExist(namedcell_Name) = False Then
ActiveWorkbook.CustomDocumentProperties.Add Name:=namedcell_Name,
LinkToContent:=False, Value:="", Type:=msoPropertyTypeString
End If
Else
reference_to_namedcell_Address = "'" & Sheets(first_sheetNO).Name & "'!" &
Range(namedcell_Address).Address
condition = reference_to_namedcell_Address & "<>" & Chr(34) & Chr(34)
Range(namedcell_Address).Value = "=IF(" & condition & "," &
reference_to_namedcell_Address & "," & Chr(34) & Chr(34) & ")"
End If
End Sub

Function CustomPropertyDoesExist(CustomPropertyName As String) As Boolean


' Checks if custom property of this workbook already exists
Dim propCustom As DocumentProperty
For Each propCustom In ActiveWorkbook.CustomDocumentProperties
If propCustom.Name = CustomPropertyName Then
CustomPropertyDoesExist = True
Exit Function
End If
Next
CustomPropertyDoesExist = False
End Function

Function CheckServicePack(RequiredServicePack As String) As Boolean


Dim GetServicePack_str As String, ServicePack_num As Integer
CheckServicePack = False ' default value
GetServicePack_str = arr_settings(HeaderLine8, 82) 'Service Pack
If GetServicePack_str = "" Then GetServicePack_str = "0"
ServicePack_num = CInt(GetServicePack_str) ' convert string to integer
If ServicePack_num >= RequiredServicePack Then
CheckServicePack = True
Else
CheckServicePack = False
End If
End Function

Function first_free_pos() As String


ReDim ColPos_used(1 To Col_ArraySize) As Integer
Dim col_nr As Integer
For aCounter = 1 To Col_ArraySize
If Trim(arr_settings(HeaderLine2, aCounter)) <> "" Then
col_nr = arr_settings(HeaderLine2, aCounter) 'get column position
ColPos_used(col_nr) = aCounter
End If
Next aCounter
For aCounter = 1 To Col_ArraySize
If ColPos_used(aCounter) = 0 Then
first_free_pos = aCounter
Exit For
End If
Next aCounter
End Function

Function SheetNo_of_firstdatasheet() As Integer


For Each WorkSh In ActiveWorkbook.Worksheets
If (filtersheets(WorkSh.Name) = False) Then
SheetNo_of_firstdatasheet = WorkSh.index
Exit Function
End If
Next
SheetNo_of_firstdatasheet = -1
End Function

=================================================================================
Rem Attribute VBA_ModuleType=VBAModule
Option VBASupport 1
Option Explicit

Sub CreateMenu(arg As String)


'(added an optional Fake Argument to this subroutine,
' because then it will not be presented in the available macro-list when user
tries to start a macro

'
' creates a new menu.
'
Dim cbMenu As CommandBarControl, cbSubMenu As CommandBarControl

RemoveMenu ' delete the menu if it's already exists


' create a new menu on an existing commandbar (the next 6 lines)
Set cbMenu = Application.CommandBars(1).Controls.Add(msoControlPopup, , , ,
True)
With cbMenu
.Caption = "&N-C Menu"
.tag = "MyTag_N-C_Menu"
.BeginGroup = False
End With

' add menuitem to menu


With cbMenu.Controls.Add(msoControlButton, 1, , , True)
.Caption = "&Report Control"
.OnAction = ThisWorkbook.Name & "!Macro_ListControl"
.FaceId = 548
End With

' add menuitem to menu


With cbMenu.Controls.Add(msoControlButton, 1, , , True)
.Caption = "&Columns Hide / Show"
.OnAction = ThisWorkbook.Name & "!Macro_Form_ShowColumns"
.FaceId = 3836
End With

' add a submenu


Set cbSubMenu = cbMenu.Controls.Add(msoControlPopup, 1, , , True)
With cbSubMenu
.Caption = "&Sheet selection"
.tag = "SubMenu1"
.BeginGroup = True

End With

' add all existing sheets as menuitem to submenu


Dim sheetIndexVar As Long
For sheetIndexVar = 1 To Sheets.Count
'If Sheets(sheetIndexVar).Visible = True Then
If (filtersheets(Sheets(sheetIndexVar).Name) = False) Then
' add menuitem to submenu
With cbSubMenu.Controls.Add(msoControlButton, 1, , , True)
.Caption = Sheets(sheetIndexVar).Name
.OnAction = "'MacroSelectSheet """ & .Caption & """'"
.Style = msoButtonIconAndCaption
If .Caption = ActiveSheet.Name Then
.FaceId = 1 '1= selected
Else
.FaceId = 0 '0=empty
End If
.State = msoButtonDown ' or msoButtonUp
.Enabled = True ' or False
End With
End If
Next sheetIndexVar

' add menuitem to menu


With cbMenu.Controls.Add(msoControlButton, 1, , , True)
.Caption = "&Write settings to a file ( a Report Profile)"
.OnAction = ThisWorkbook.Name & "!Macro_WriteSettingsFile"
.Style = msoButtonIconAndCaption
.FaceId = 3
.BeginGroup = True
End With

If (CheckServicePack(2)) Then
' add menuitem to menu
With cbMenu.Controls.Add(msoControlButton, 1, , , True)
.Caption = "&eBrowser link"
.OnAction = ThisWorkbook.Name & "!setup_eBrowser_link"
.Style = msoButtonIconAndCaption
.FaceId = 1577
.BeginGroup = True
End With
End If

'tip:
'instead of .FaceId = 463 you can also use your own facID's by replacing it with:
'Sheet1.Shapes("Pic1").Copy
'.PasteFace

' add menuitem to menu


With cbMenu.Controls.Add(msoControlButton, 1, , , True)
.Caption = "&Clean up"
.OnAction = ThisWorkbook.Name & "!CleanUp_A"
.Style = msoButtonIconAndCaption
.FaceId = 463
.BeginGroup = True
End With

' add menuitem to menu


With cbMenu.Controls.Add(msoControlButton, 1, , , True)
.Caption = "&Export to a textfile (*.csv)"
.OnAction = ThisWorkbook.Name & "!Macro_ExportToCSV"
.Style = msoButtonIconAndCaption
.FaceId = 0
.BeginGroup = True
End With

Set cbSubMenu = Nothing


Set cbMenu = Nothing
End Sub

Private Sub setup_eBrowser_link()


Call init(1)
If NotAllowedToStartMacroFromHere(True) Then Exit Sub
If Not WorksheetExists("settings") Or Not WorksheetExists(eBrowserSheet) Then
MsgBox "ReportGenerator. It is not possible to Setup an eBrowser-link after
a CleanUp has been done."
Exit Sub
End If
Dim eb_file As String, incl_setup_ref As Boolean
Call ReadSettings(1) 'Readsettings
eb_file = get_ebfile 'ask for location of eBrowserfile
If eb_file = "" Or Dir(eb_file) = "" Then Exit Sub
Call WriteSettings(1)
incl_setup_ref = True
Call EbrowserInitialize(True, incl_setup_ref) 'initialize the connection
to the eBrowserfile, and load it
If EbrowserInitialized = False Then
Sheets(eBrowserSheet).Visible = False
MsgBox "Failed to setup an eBrowser link."
Exit Sub
End If
Call switch_to_eBrowsersheet(False) 'swich to the eBrowser sheet ( and show no
go-back-button on sheet)
End Sub

Private Sub CleanUp_A()


Call CleanUp_B(True)
End Sub

Sub CleanUp_B(with_message As Boolean)


Call init(1)
If NotAllowedToStartMacroFromHere(with_message) Then Exit Sub

If with_message = True Then


If MsgBox("The Clean-Up will remove this N-C Menu, " & Chr(10) & _
"and deletes the internal " & "database of this excel file." & Chr(10) & _
"" & Chr(10) & _
"Do you want to Clean-Up ?", vbQuestion + vbYesNo, "Clean up.") = vbNo Then
Exit Sub
End If
End If

Dim remembered_activesheetname As String, remembered_activecell As String


remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address

Application.ScreenUpdating = False
Call ReadSettings(0)

Dim WorkSh As Worksheet, LastColRow1 As Long, iCounter As Long


For Each WorkSh In ActiveWorkbook.Worksheets
If (filtersheets(WorkSh.Name) = True) Then
'
' Delete the hidden sheets
'
Application.DisplayAlerts = False
'skip sheet "TOTAL". Also skip sheet "eBrowser" because that sheet will
be deleted at the end.
If WorkSh.Name <> "eBrowser" And UCase(WorkSh.Name) <> "TOTAL" Then
WorkSh.Delete
Application.DisplayAlerts = True
Else
'
' Delete the hidden columns
'
WorkSh.Select
LastColRow1 = last_col_nr(ListStartCol) 'call to function
last_col_nr()

For iCounter = LastColRow1 To 1 Step -1


If Columns(iCounter).EntireColumn.Hidden = True Then
Columns(iCounter).EntireColumn.Delete
End If
Next iCounter

'activate cell A1, to avoid that previous selection is still active


Range("A1").Select
'set active window to left upper corner
ActiveWindow.ScrollRow = 1
ActiveWindow.ScrollColumn = 1

End If
Next

Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select

Call RemoveMenu
Call EbrowserInitialize(False, False) 'check if eBrowser is initialized
Call CleanUp_C(1) ' Removes all macros, etc.
Application.ScreenUpdating = True

' Special treatment for ebrowsersheet while earlier it was crashing during
deletion in previous block ( probably somehow related to the activeX object)
' And also below lines should be done at the end because after this some
function somehow do not work anymore like: Application.ActiveWorkbook.Name
If WorksheetExists("eBrowser") Then
If EbrowserInitialized = False Then ' skip deleting when its active
because otherwise excel crashes
Application.DisplayAlerts = False
' Sheets("eBrowser").Delete ' does not yet work, it crashes because
eBrowser object is still somehow active. Lic even remains active till complete
excel is closed
Application.DisplayAlerts = True
End If
End If
End Sub

Sub Macro_ExportToCSV()
Call ExportToCSV(True)
End Sub

Sub ExportToCSV(with_message As Boolean)


Call init(1)
If NotAllowedToStartMacroFromHere(with_message) Then Exit Sub

Dim remembered_activesheetname As String, remembered_activecell As String


remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address

Application.ScreenUpdating = False
Call ReadSettings(0)
Call ExportToCSV_core(with_message)

Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select
Application.ScreenUpdating = True
End Sub

Sub ExportToCSV_core(with_message As Boolean)


Dim vFileNum As Integer, csv_file As Variant, csv_file_path As String
Dim LastRowColA As Long, LastColRow1 As Long, nr_of_rows As Long, RowIn As Long
Dim nr_of_cols As Integer, c As Integer, col_pos As Integer, iCounter As
Integer, pos As Integer
Dim CSV_columns As String, one_line As String, ColName As String, seperator As
String
Dim csv_file_n As String, next_char As String
Dim WorkSh As Worksheet, export_col As Boolean

csv_file_path = arr_settings(HeaderLine8, 84)


If csv_file_path = "" Then csv_file_path = ThisWorkbook.Path & "\"
If Right(csv_file_path, 1) <> "\" Then csv_file_path = csv_file_path & "\"

If Dir(csv_file_path) = "" Then


MsgBox "RepGen. Info: Could not export to CSV-file because path is not
found: " & csv_file_path
If with_message = True Then
'ask user the directory:
Exit Sub
Else
Exit Sub
End If
End If
csv_file_n = arr_settings(HeaderLine8, 85)
If csv_file_n = "" Then csv_file = Left(ThisWorkbook.Name,
Len(ThisWorkbook.Name) - 4) & ".csv" 'cut off the extension ".xls" and add ".csv"
csv_file = csv_file_path & csv_file_n

Dim ThisWorkbookPath As String, ThisWorkbookName As String, Importfile As


String
ThisWorkbookPath = ThisWorkbook.Path
ThisWorkbookName = ThisWorkbook.Name
ThisWorkbookName = Left(ThisWorkbookName, Len(ThisWorkbookName) - 4) 'cut off
the extension ".xls"

seperator = arr_settings(HeaderLine8, 86)


If seperator = "" Then seperator = ";"
CSV_columns = arr_settings(HeaderLine8, 87)
'Open file for writing
vFileNum = FreeFile()
On Error Resume Next
Open csv_file For Output As #vFileNum
On Error GoTo 0

For Each WorkSh In ActiveWorkbook.Worksheets


If (filtersheets(WorkSh.Name) = False) Then
Sheets(WorkSh.Name).Select 'make the sheet the active sheet
'get last row and column:
LastRowColA = last_row_nr(ListStartLine, ListStartCol) 'call to
function last_row_nr()
LastColRow1 = last_col_nr(ListStartCol) 'call to function
last_col_nr()
nr_of_rows = LastRowColA - ListStartLine + 1
nr_of_cols = LastColRow1 - ListStartCol + 1

'read in whole sheet into an array


Dim arr_in As Variant 'MUST be variant
arr_in = Range(Cells(ListStartLine, ListStartCol), Cells(LastRowColA,
LastColRow1)).Value
For RowIn = 1 To nr_of_rows
one_line = ""
For c = 0 To nr_of_cols
export_col = False
For iCounter = 1 To nr_of_cols
col_pos = arr_settings(HeaderLine2, iCounter) 'get column
position
If col_pos = c Then
ColName = arr_settings(HeaderLine1, iCounter)
If CSV_columns <> "" Then
pos = InStr(1, CSV_columns, ColName)
If pos > 0 Then ' search if this col is in list of
to be exported columns
pos = pos + Len(ColName)
next_char = Mid(CSV_columns, pos, 1)
' check the next_char to avoid finding
'COL_CUST1' in string COL_NAM,COL_CUST13,COL_QTY
If (next_char = ",") Or (next_char = "") Then
export_col = True
End If
Else
export_col = True
End If
End If
Next iCounter
If export_col = True Then
one_line = one_line & Chr(34) & arr_in(RowIn, c) & Chr(34)
& seperator
End If
Next c
one_line = Left(one_line, Len(one_line) - 1) 'skip last seperator-
char at the end of the line (requested by DamenSchelde)
Print #vFileNum, one_line
Next RowIn
End If
Next
Close #vFileNum
If with_message = True Then
MsgBox "created csv-file ready at: " & csv_file
End If
End Sub
Function define_CSV_columns() As String

define_CSV_columns = ""
End Function

Private Sub RemoveMenu()


DeleteCustomCommandBarControl "MyTag_N-C_Menu" ' deletes the new menu
End Sub

Private Sub DeleteCustomCommandBarControl(CustomControlTag As String)


' deletes ALL occurences of commandbar controls with a tag = CustomControlTag
On Error Resume Next
Do
Application.CommandBars.FindControl(, , CustomControlTag, False).Delete
Loop Until Application.CommandBars.FindControl(, , CustomControlTag, False) Is
Nothing
On Error GoTo 0
End Sub

Sub MacroSelectSheet(SelectedSheet As String)


'macro used by the menuitems in order to select a sheet
Call init(1)
If NotAllowedToStartMacroFromHere(True) Then Exit Sub
With Worksheets(SelectedSheet)
.Activate
.Range("A1").Select
End With

'Readsettings ( just voor one headerline8 setting used in subroutine:


CreateMenu
If Not WorksheetExists("settings") Then Exit Sub
Call ReadSettings(1)
Call CreateMenu(1)
End Sub

Sub Macro_ListControl()
Call init(1)
If NotAllowedToStartMacroFromHere(True) Then Exit Sub
Form_ListControl.Show
End Sub

Sub Macro_Form_ShowColumns()
Call init(1)
If NotAllowedToStartMacroFromHere(True) Then Exit Sub
If (filtersheets(ActiveSheet.Name) = True) Then
MsgBox "Not possible to start this function from sheet '" &
ActiveSheet.Name & "'" & _
Chr(10) & " ( please first select another sheet to start this
function )"
Exit Sub
End If
Form_ShowColumns.Show
End Sub

Function NotAllowedToStartMacroFromHere(with_message As Boolean) As Boolean


'Abort when this subroutine is started from some other workbook
' (by checking existence of sheet "import"
'this is just for safety because one of these functions will delete sheets
If Not WorksheetExists("import") Then
If with_message = True Then
MsgBox "ReportGenerator. Not possible to run this macro from this
workbook" & _
Chr(10) & " ( checked by looking for internal import-sheet )"
NotAllowedToStartMacroFromHere = True
End If
Else
NotAllowedToStartMacroFromHere = False
End If

End Function

Sub Macro_WriteSettingsFile()
Call init(1)
If NotAllowedToStartMacroFromHere(True) Then Exit Sub
If Not WorksheetExists("settings") Then Exit Sub

Dim item As String, remembered_activesheetname As String, remembered_activecell


As String
Dim vFileNum As Integer, tempStr As String, i As Long, j As Integer, _
default_rpp_file As String, rpp_file As Variant, default_rpp_path As String, _
RememberCurDir As String, DriveLetter As String, default_rpp As String

remembered_activesheetname = ActiveSheet.Name
remembered_activecell = ActiveCell.Address

Call ReadSettings(1)

' Change dir to directory of rpp-file


default_rpp = arr_settings(HeaderLine8, 76)
default_rpp = Replace(default_rpp, "/", "\")
default_rpp_file = StripFileOrPath(default_rpp, "GetFile")
default_rpp_path = StripFileOrPath(default_rpp, "GetPath")
RememberCurDir = CurDir$()

If Dir(default_rpp_path & default_rpp_file) <> "" Then


DriveLetter = Left$(default_rpp_path, 1)
If DriveLetter <> "/" And DriveLetter <> "\" Then ChDrive DriveLetter
ChDir default_rpp_path
Else
MsgBox "Info: file-Location of rpp-file may be: " & default_rpp_path
End If

'ask user the filename and location:


rpp_file = Application.GetSaveAsFilename(InitialFileName:= _
default_rpp_file, filefilter:= _
"Report Profile (*.rpp), *.rpp", Title:="Please enter filename to export the
settings")

' Change dir to original current directory


DriveLetter = Left$(RememberCurDir, 1)
If DriveLetter <> "/" And DriveLetter <> "\" Then ChDrive DriveLetter
ChDir RememberCurDir

If (rpp_file = False Or rpp_file = "") Then Exit Sub


If Dir(rpp_file) <> "" Then
If MsgBox("File Already exists!" & Chr(10) & Chr(10) & _
"Are you really sure to overwrite existing file:" & Chr(10) & _
" < " & default_rpp_file & " > ?", _
vbQuestion + vbYesNo, "Writing current settings to a report profile file")
= vbNo Then
MsgBox "Writing file aborted."
Exit Sub
End If
End If

'Open file for writing


vFileNum = FreeFile()
On Error Resume Next
Open rpp_file For Output As #vFileNum
If Err <> 0 Then MsgBox "Cannot save to filename " & rpp_file: End
On Error GoTo 0

Application.ScreenUpdating = False
Sheets("settings").Visible = True
Sheets("settings").Select

If QueryLines > 0 Then


ReDim arr_dummy_q(1 To 1, 1 To QueryLines) As Variant
arr_dummy_q = Range(Cells(1, 1), Cells(QueryLines, 1)).Value
For i = 1 To QueryLines
Print #vFileNum, arr_dummy_q(i, 1)
Next i
End If

ReDim arr_dummy_h(1 To HeaderLines, 1 To Col_ArraySize) As Variant


arr_dummy_h = Range(Cells(QueryLines + 1, 1), Cells(QueryLines + HeaderLines,
Col_ArraySize)).Value
For i = 1 To HeaderLines - 1
tempStr = ""
For j = 1 To Col_ArraySize
tempStr = tempStr & arr_dummy_h(i, j) & ";"
Next j
Print #vFileNum, tempStr
Next i

Close #vFileNum

Call sheet_sel(remembered_activesheetname)
Range(remembered_activecell).Select
Sheets("settings").Visible = False
Application.ScreenUpdating = True
End Sub

Public Function StripFileOrPath(FullPath As String, ReturnType As String) As String


' =====================================================================
' Returns either the FileName or the Path from a given Full FileName
' 1st Arg = Pass a files full name (C:\Example\MyFile.xls)
' 2nd Arg = What to return (either the filename [0] or the path [1]

' Example: MsgBox StripFileOrPath(ThisWorkbook.FullName, GetPath)


' =====================================================================
Dim szPathSep As String, szCut As String, i As Long, szPath As String, szFile
As String
szPathSep = Application.PathSeparator
szCut = CStr(Empty)
i = Len(FullPath)

If i > 0 Then
Do While ((szCut <> szPathSep) And (i > 0))
szCut = Mid$(FullPath, i, 1)
If szCut = szPathSep Then
szPath = Left$(FullPath, i)
szFile = Right$(FullPath, Len(FullPath) - i)
End If
i = i - 1
Loop

Select Case ReturnType


Case "GetPath"
StripFileOrPath = szPath
Case "GetFile"
StripFileOrPath = szFile
Case Else
MsgBox "script warning: unknown case " & ReturnType & " (should be
GetPath or GetFile)"
End Select
Else
StripFileOrPath = CStr(Empty)
End If

End Function

===================================================================================

You might also like