VERSION 5.00
Begin {C62A69F0-16DC-11CE-9E98-00AA00574A4F} FORMULAEDIT 
   Caption         =   "Формула"
   ClientHeight    =   4980
   ClientLeft      =   45
   ClientTop       =   330
   ClientWidth     =   9495
   OleObjectBlob   =   "FORMULAEDIT.frx":0000
   StartUpPosition =   1  'CenterOwner
End
Attribute VB_Name = "FORMULAEDIT"
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False







Option Explicit

Public pbMode As Boolean ' Режим загрузки
Public pnTypeFormula As Integer ' Тип формулы
Public pcCodeStr As String ' код строки
Public pnLinkStr As Integer ' Link строки
Public pnNumGraf As Integer ' номер графы
'Public pnSaveGraf As Integer ' номер графы
Public pcTypeFormula As String ' Наименование типа формулы
Public pnNumFormula As Integer ' Номер формулы
Public pnRowForm  As Integer ' Номер записи в TABLE_FORM
Public pnCodeItog As Integer ' Код итога

' Процедура создания текста формулы
Public Sub Create_Formula()

On Error GoTo doError
 
Dim lcTextFormula As String, lcLetter As String, lcNewKey As String
Dim nCnt As Integer, lnRowStr As Integer, lcKey As String
Dim LookRange As Range
Dim lnColumn As Long, lnColumnCount As Long, lnRow As Long
Dim lSheetsAlg As Object, lSheetsService As Object, lSheetsReport As Object, lSheetsForm As Object
Dim i As Integer
Dim s As String
Dim pageName As String

lcTextFormula = ""

Set lSheetsService = Sheets("Service")
Set lSheetsReport = Sheets(Sheets("Service").Range("B19").Text)
Set lSheetsForm = Sheets("Form")
Set lSheetsAlg = Sheets("ALG")

With lSheetsService
    lnColumn = .Range("KRIT_GRAF").Column
    lnColumnCount = .Range("KRIT_GRAF").Columns.count
    lnRow = .Range("KRIT_GRAF").row
End With

' Просмотрим все составляющие
With Me.ListView1
    For nCnt = 1 To .ListItems.count
        ' Определим букву колонки
        ' Заполнение критерия
        lSheetsService.Cells(lnRow + 1, lnColumn) = VBA.Val(.ListItems(nCnt).TooltipText)
        lSheetsService.Cells(lnRow + 1, lnColumn + 1) = ""
        If pnTypeFormula = 1 Then 'для всех граф
            lcLetter = "@"
        Else
            lcLetter = lSheetsService.Cells(lnRow + 3, lnColumn) ' Буква колонки
        End If
        ' Сброс критерия
        lSheetsService.Range(lSheetsService.Cells(lnRow + 1, lnColumn), lSheetsService.Cells(lnRow + 1, lnColumn + lnColumnCount - 2)) = ""

        ' Определим номер записи Excel
        If .ListItems(nCnt).Tag = "-1" Then
            lnRowStr = 1
            lcTextFormula = lcTextFormula + " " + VBA.Trim(.ListItems(nCnt).Text) + " $" + lcLetter + VBA.Trim(VBA.str(lnRowStr))
        Else
            If VBA.InStr(.ListItems(nCnt).Text, "СУММ") <> 0 Then
                s = .ListItems(nCnt).Tag
                Set LookRange = lSheetsReport.Range("LINK").Find(getNextSubstr(s, ":"), LookIn:=xlFormulas, lookat:=xlWhole)
                lnRowStr = LookRange.row ' номер записи
                lcTextFormula = lcTextFormula + " " + VBA.Trim(.ListItems(nCnt).Text) + "(" + lcLetter + "$" + VBA.Trim(VBA.str(lnRowStr))
                Set LookRange = lSheetsReport.Range("LINK").Find(s, LookIn:=xlFormulas, lookat:=xlWhole)
                lnRowStr = LookRange.row ' номер записи
                lcTextFormula = lcTextFormula + ":" + lcLetter + "$" + VBA.Trim(VBA.str(lnRowStr)) + ")"
            Else
                ' проверим лист
                pageName = IIf(VBA.InStr(.ListItems(nCnt).ListSubItems(1), "!") <> 0, VBA.Left(.ListItems(nCnt).ListSubItems(1), VBA.InStr(.ListItems(nCnt).ListSubItems(1), "!")), "")
                Set LookRange = lSheetsReport.Range("LINK").Find(.ListItems(nCnt).Tag, LookIn:=xlFormulas, lookat:=xlWhole)
                lnRowStr = LookRange.row ' номер записи
                lcTextFormula = lcTextFormula + " " + VBA.Trim(.ListItems(nCnt).Text) + " " + pageName + lcLetter + "$" + VBA.Trim(VBA.str(lnRowStr))
            End If
        End If
        
    Next
    lcTextFormula = lcTextFormula + " "
End With
    
    ' Адресс первой колонки TABLE_FORM
    lnColumn = lSheetsForm.Range("TABLE_FORM").Column
    
    If Me.pbMode Then ' Update формула
        ' Пропишем заголовок формулы
        'FORMULAEDIT.pnLinkStr ' Link строки
        'FORMULAEDIT.pnNumFormula ' Номер формулы
        'FORMULAEDIT.pnTypeFormula ' Тип Формулы
        'FORMULAEDIT.pnNumGraf 'Номер графы
        'FORMULAEDIT.pnRowForm ' Номер записи Excel
        ' Запись в DB "TABLE_FORM"
        With lSheetsForm
            .Cells(pnRowForm, lnColumn) = IIf(FORMULAEDIT.pnTypeFormula = 4, -1, FORMULAEDIT.pnLinkStr) 'FORMULAEDIT.pnLinkStr
            .Cells(pnRowForm, lnColumn + 1) = IIf(FORMULAEDIT.pnTypeFormula = 1, 0, FORMULAEDIT.pnNumGraf) 'FORMULAEDIT.pnNumGraf
            .Cells(pnRowForm, lnColumn + 2) = FORMULAEDIT.pnNumFormula
            .Cells(pnRowForm, lnColumn + 3) = lcTextFormula
            .Cells(pnRowForm, lnColumn + 4) = FORMULAEDIT.CmbZnak.ListIndex + 1
            .Cells(pnRowForm, lnColumn + 6) = FORMULAEDIT.pnTypeFormula
            .Cells(pnRowForm, lnColumn + 7) = Sheets("Service").Range("B20")
        End With
        LIST_FORMULA.LstFormula.SelectedItem.SubItems(1) = FORMULAEDIT.pcCodeStr
        LIST_FORMULA.LstFormula.SelectedItem.Tag = FORMULAEDIT.pnLinkStr
        LIST_FORMULA.LstFormula.SelectedItem.TooltipText = FORMULAEDIT.pnNumGraf
    Else ' добавление новой формулы в таблицу
        ' Необходимо вычислить новую запись в TABLE_FORM
        Set LookRange = lSheetsForm.Columns(lnColumn).Find("", LookIn:=xlFormulas, lookat:=xlWhole, SearchOrder:=xlByRows)
        pnRowForm = LookRange.row
        With LIST_FORMULA.LstFormula
            ' Определим последний Item в ListView
            If .ListItems.count = 0 Then
                lcNewKey = "_1"
            Else
                lcKey = .ListItems(.ListItems.count).Key
                lcNewKey = "_" + VBA.Trim(VBA.str(VBA.Val(VBA.Right(lcKey, VBA.Len(lcKey) - 1)) + 1)) ' Новый свободный ключ
            End If
            .ListItems.Add , lcNewKey, FORMULAEDIT.pnNumFormula, 0, 5
            .ListItems(lcNewKey).SubItems(1) = IIf(FORMULAEDIT.pnTypeFormula = 4, "Все строки", FORMULAEDIT.pcCodeStr)
            .ListItems(lcNewKey).SubItems(2) = VBA.Trim(FORMULAEDIT.TxtTypeFormula.value)
            .ListItems(lcNewKey).Tag = FORMULAEDIT.pnLinkStr
            .ListItems(lcNewKey).TooltipText = FORMULAEDIT.pnNumGraf
        End With
        With lSheetsForm
            .Cells(pnRowForm, lnColumn) = IIf(FORMULAEDIT.pnTypeFormula = 4, -1, FORMULAEDIT.pnLinkStr)
            .Cells(pnRowForm, lnColumn + 1) = IIf(FORMULAEDIT.pnTypeFormula = 1, 0, FORMULAEDIT.pnNumGraf) 'IIf(FORMULAEDIT.pnTypeFormula = 2, , FORMULAEDIT.pnNumGraf)
            .Cells(pnRowForm, lnColumn + 2) = FORMULAEDIT.pnNumFormula
            .Cells(pnRowForm, lnColumn + 3) = lcTextFormula
            .Cells(pnRowForm, lnColumn + 4) = FORMULAEDIT.CmbZnak.ListIndex + 1
            .Cells(pnRowForm, lnColumn + 5).FormulaLocal = "=СТРОКА()"
            .Cells(pnRowForm, lnColumn + 6) = FORMULAEDIT.pnTypeFormula
            .Cells(pnRowForm, lnColumn + 7) = Sheets("Service").Range("B20")
        End With

    End If

Exit Sub
doError:
    Call ERROR_EVENT("Create_Formula")
End Sub

' Процедура добавления нового Item
Public Sub New_Formula_Item()
Dim lcKey As String
Dim lcNewKey As String
Dim i As Integer

On Error GoTo doError
 
    Load PART_FORMULAEDIT
    PART_FORMULAEDIT.pbMode = False
    PART_FORMULAEDIT.pcCodeStr = ""
    PART_FORMULAEDIT.pcNameGraf = ""
    PART_FORMULAEDIT.pcZnak = ""
    PART_FORMULAEDIT.pnTypeFormula = Me.pnTypeFormula
    PART_FORMULAEDIT.pnLinkStr = 0
    PART_FORMULAEDIT.Form_init
    PART_FORMULAEDIT.Show
    If pbFormCancel Then ' Добавим новое слагаемое в формулу
        PART_FORMULAEDIT.pcNameGraf = VBA.Trim(PART_FORMULAEDIT.TxtGraf.value)
        If VBA.InStr(PART_FORMULAEDIT.pcZnak, "СУММ") <> 0 Then
            If PART_FORMULAEDIT.pnCount <> 2 Then
                Call MsgBox("Число параметров функции ""СУММ"" должно быть 2 (начало и конец диапазона)!!!", 16, "Внимание !!!")
            Else
                    PART_FORMULAEDIT.pcNameGraf = VBA.Trim(PART_FORMULAEDIT.TxtGraf.value)
                    ' Определим последний Item в ListView
                    If FORMULAEDIT.ListView1.ListItems.count = 0 Then
                        lcNewKey = "_1"
                    Else
                        lcKey = FORMULAEDIT.ListView1.ListItems(FORMULAEDIT.ListView1.ListItems.count).Key
                        lcNewKey = "_" + VBA.Trim(VBA.str(VBA.Val(VBA.Right(lcKey, VBA.Len(lcKey) - 1)) + 1)) ' Новый свободный ключ
                    End If
                    With Me.ListView1
                        .ListItems.Add , lcNewKey, PART_FORMULAEDIT.pcZnak
                        .ListItems(lcNewKey).SubItems(1) = PART_FORMULAEDIT.pnRetArrayValue(0) + ":" + PART_FORMULAEDIT.pnRetArrayValue(1)
                        .ListItems(lcNewKey).Tag = PART_FORMULAEDIT.pnRetArrayLink(0) + ":" + PART_FORMULAEDIT.pnRetArrayLink(1)
                        .ListItems(lcNewKey).SubItems(2) = PART_FORMULAEDIT.pcNameGraf
                        .ListItems(lcNewKey).TooltipText = PART_FORMULAEDIT.pnNumGraf
                        .ListItems(lcNewKey).Selected = True
                    End With
                    Me.CmdOK.Enabled = True
                    Me.TlbFormula.Buttons("B2").Enabled = True
                    Me.TlbFormula.Buttons("B3").Enabled = True
            End If
        Else
            If PART_FORMULAEDIT.pnCount <= 1 Then
                ' Определим последний Item в ListView
                If FORMULAEDIT.ListView1.ListItems.count = 0 Then
                    lcNewKey = "_1"
                Else
                    lcKey = FORMULAEDIT.ListView1.ListItems(FORMULAEDIT.ListView1.ListItems.count).Key
                    lcNewKey = "_" + VBA.Trim(VBA.str(VBA.Val(VBA.Right(lcKey, VBA.Len(lcKey) - 1)) + 1)) ' Новый свободный ключ
                End If
                With Me.ListView1
                    .ListItems.Add , lcNewKey, PART_FORMULAEDIT.pcZnak
                    If Me.pnTypeFormula <> 4 Then
                        .ListItems(lcNewKey).SubItems(1) = IIf(PART_FORMULAEDIT.TextBox1.Text = "", "", PART_FORMULAEDIT.TextBox1.Text + "!") + PART_FORMULAEDIT.pcCodeStr
                        .ListItems(lcNewKey).Tag = PART_FORMULAEDIT.pnLinkStr
                    Else
                        .ListItems(lcNewKey).SubItems(1) = "Все строки"
                        .ListItems(lcNewKey).Tag = "-1"
                    End If
                    .ListItems(lcNewKey).SubItems(2) = PART_FORMULAEDIT.pcNameGraf
                    .ListItems(lcNewKey).TooltipText = PART_FORMULAEDIT.pnNumGraf
                    .ListItems(lcNewKey).Selected = True
                End With
                
                Me.CmdOK.Enabled = (Me.pnTypeFormula = 4 And Me.TxtGraf <> "") Or (Me.pnTypeFormula <> 4 And Me.TxtBar <> "")
                Me.TlbFormula.Buttons("B2").Enabled = True
                Me.TlbFormula.Buttons("B3").Enabled = True
            Else
                For i = 0 To PART_FORMULAEDIT.pnCount - 1
                    PART_FORMULAEDIT.pcNameGraf = VBA.Trim(PART_FORMULAEDIT.TxtGraf.value)
                    ' Определим последний Item в ListView
                    If FORMULAEDIT.ListView1.ListItems.count = 0 Then
                        lcNewKey = "_1"
                    Else
                        lcKey = FORMULAEDIT.ListView1.ListItems(FORMULAEDIT.ListView1.ListItems.count).Key
                        lcNewKey = "_" + VBA.Trim(VBA.str(VBA.Val(VBA.Right(lcKey, VBA.Len(lcKey) - 1)) + 1)) ' Новый свободный ключ
                    End If
                    With Me.ListView1
                        .ListItems.Add , lcNewKey, PART_FORMULAEDIT.pcZnak
                        If Me.pnTypeFormula <> 4 Then
                            .ListItems(lcNewKey).SubItems(1) = IIf(PART_FORMULAEDIT.TextBox1.Text = "", "", PART_FORMULAEDIT.TextBox1.Text + "!") + PART_FORMULAEDIT.pnRetArrayValue(i)
                            .ListItems(lcNewKey).Tag = PART_FORMULAEDIT.pnRetArrayLink(i)
                        Else
                            .ListItems(lcNewKey).SubItems(1) = "Все строки"
                            .ListItems(lcNewKey).Tag = "-1"
                        End If
                        .ListItems(lcNewKey).SubItems(2) = PART_FORMULAEDIT.pcNameGraf
                        .ListItems(lcNewKey).TooltipText = PART_FORMULAEDIT.pnNumGraf
                        .ListItems(lcNewKey).Selected = True
                    End With
                    Me.CmdOK.Enabled = True
                    Me.TlbFormula.Buttons("B2").Enabled = True
                    Me.TlbFormula.Buttons("B3").Enabled = True
                Next
            End If
        End If
        Unload PART_FORMULAEDIT
    End If
    Me.ListView1.SetFocus

Exit Sub
doError:
    Call ERROR_EVENT("New_Formula_Item")
End Sub
' Процедура редактирования существующего Item
Public Sub Edit_Formula_Item(ByVal lcKey As String)
Dim pageName As String
On Error GoTo doError
' строчки с СУММ пока не редактируются :-(
If VBA.InStr(Me.ListView1.SelectedItem.Tag, ":") = 0 Then
    pageName = IIf(VBA.InStr(Me.ListView1.SelectedItem.SubItems(1), "!") = 0, "", VBA.Left(Me.ListView1.SelectedItem.SubItems(1), VBA.InStr(Me.ListView1.SelectedItem.SubItems(1), "!") - 1))
    Load PART_FORMULAEDIT
    PART_FORMULAEDIT.pbMode = True
    PART_FORMULAEDIT.pcNamePage = pageName
    PART_FORMULAEDIT.pcCodeStr = VBA.Mid(VBA.Trim(Me.ListView1.SelectedItem.SubItems(1)), VBA.InStr(VBA.Trim(Me.ListView1.SelectedItem.SubItems(1)), "!") + 1, VBA.Len(VBA.Trim(Me.ListView1.SelectedItem.SubItems(1))))
    PART_FORMULAEDIT.pcNameGraf = VBA.Trim(Me.ListView1.SelectedItem.SubItems(2))
    PART_FORMULAEDIT.pcZnak = VBA.Trim(Me.ListView1.SelectedItem.Text)
    PART_FORMULAEDIT.pnNumGraf = VBA.Val(VBA.Trim(Me.ListView1.SelectedItem.TooltipText))
    PART_FORMULAEDIT.pnTypeFormula = Me.pnTypeFormula
    PART_FORMULAEDIT.pnLinkStr = VBA.Val(VBA.Trim(Me.ListView1.SelectedItem.Tag)) ' Link строки
    PART_FORMULAEDIT.Form_init
    PART_FORMULAEDIT.Show
    If pbFormCancel Then ' Сделаем изменения
        With Me.ListView1.ListItems(lcKey)
            .Text = PART_FORMULAEDIT.pcZnak
            .SubItems(1) = IIf(PART_FORMULAEDIT.pcNamePage = "", "", PART_FORMULAEDIT.pcNamePage + "!") + PART_FORMULAEDIT.pcCodeStr
            .SubItems(2) = PART_FORMULAEDIT.pcNameGraf
            .TooltipText = PART_FORMULAEDIT.pnNumGraf
            .Tag = PART_FORMULAEDIT.pnLinkStr
            .Selected = True
        End With
        Me.CmdOK.Enabled = True
        Unload PART_FORMULAEDIT
    Else
        Me.ListView1.ListItems(lcKey).Selected = True
    End If
    Me.ListView1.SetFocus
End If
Exit Sub
doError:
    Call ERROR_EVENT("Edit_Formula_Item")
End Sub
' Процедура удаления существующего Item
Public Sub Del_Formula_Item(ByVal lcKey As String)
 
On Error GoTo doError
    
    With Me.ListView1
        .ListItems.Remove (lcKey)
        If .ListItems.count = 0 Then
            Me.CmdOK.Enabled = False
            Me.TlbFormula.Buttons("B2").Enabled = False
            Me.TlbFormula.Buttons("B3").Enabled = False
        Else
            .ListItems(1).Selected = True
            .SetFocus
        End If
    End With

Exit Sub
doError:
    Call ERROR_EVENT("Del_Formula_Item")
End Sub
' Процедура заполнения содержимого формулы при редактировании
Public Sub FILL_FORMULA_CONTENTS(ByVal lcFormText As String)
Dim lcFormTextWork As String, nCnt As Long, lcLetter As String, lcText3 As String
Dim lnStartAddress As Integer, lnStartEmpty As Integer, lnNumRow As Integer, lnNumRow1 As Integer, lnNumGraf As Integer
Dim lcPart As String, lcZnak As String, lnOccur As Integer
Dim LookRange As Range, lSheetsReport As Object, lSheetsService As Object
Dim lnColumn As Long, lnRow As Long, lnColumnCount As Long, sumFlag As Boolean
Dim pageName As String
Dim i As Integer

Set lSheetsReport = Sheets(Sheets("Service").Range("B19").Text)
Set lSheetsService = Sheets("Service")
 
On Error GoTo doError
    
lcFormTextWork = lcFormText
' Определим колличество вхождений - Количество участников (строк или граф)
lnOccur = Occur(lcFormText, "$") - Occur(lcFormText, ":")
With Me.ListView1
    .ColumnHeaders.Add 1, "_1", "Знак", 50, 0
    .ColumnHeaders.Add 2, "_2", "Код строки", 70, 0
    .ColumnHeaders.Add 3, "_3", "Графы", 300, 0
    For nCnt = 1 To lnOccur
        If Me.pnTypeFormula <> 4 Then
            lnStartAddress = VBA.InStr(1, lcFormTextWork, "$", vbTextCompare)
            lnStartEmpty = VBA.InStr(lnStartAddress, lcFormTextWork, " ", vbTextCompare)
            lcPart = VBA.Mid(lcFormTextWork, 2, lnStartEmpty - 1)
            lcFormTextWork = VBA.Right(lcFormTextWork, VBA.Len(lcFormTextWork) - VBA.Len(lcPart))
            If VBA.InStr(lcPart, "!") <> 0 Then
                pageName = VBA.Mid(lcPart, 3, VBA.InStr(lcPart, "!") - 3)
                lcPart = VBA.Left(lcPart, 2) + VBA.Mid(lcPart, VBA.InStr(lcPart, "!") + 1, VBA.Len(lcPart) - VBA.InStr(lcPart, "!"))
            Else
                pageName = ""
            End If
            lcZnak = VBA.Left(lcPart, 1)
            lnNumRow = VBA.Val(VBA.Right(lcPart, VBA.Len(lcPart) - VBA.InStr(1, lcPart, "$", vbTextCompare)))
            lcLetter = VBA.Mid(lcPart, 2, VBA.InStr(1, lcPart, "$", vbTextCompare) - 2)
        Else
            lnStartAddress = VBA.InStr(1, lcFormTextWork, "$", vbTextCompare)
            lnStartEmpty = VBA.InStr(lnStartAddress, lcFormTextWork, " ", vbTextCompare)
            lcPart = VBA.Mid(lcFormTextWork, 2, lnStartEmpty - 1)
            lcZnak = VBA.Left(lcPart, 1)
            'lnNumRow = vba.Right(lcPart, 1)
            lcLetter = VBA.Mid(lcPart, 4, VBA.Len(lcPart) - 5)
            lcFormTextWork = VBA.Right(lcFormTextWork, VBA.Len(lcFormTextWork) - VBA.Len(lcPart))
        End If
        ' Заполнение ListView
        sumFlag = IIf(VBA.InStr(lcPart, ":") <> 0, True, False)
        .ListItems.Add nCnt, "_" + VBA.Trim(VBA.str(nCnt)), IIf(Not sumFlag, lcZnak, lcZnak + " СУММ"), 0
        If pnTypeFormula <> 4 Then
            'VBA.Trim(lSheetsReport.Cells(lnNumRow, pnAddress_Col - lSheetsService.Range(lSheetsService.Range("E1"))))
            If Not sumFlag Then
                .ListItems("_" + VBA.Trim(VBA.str(nCnt))).SubItems(1) = pageName + IIf(pageName = "", "", "!") + getCode(lnNumRow, "", pageName)
                .ListItems("_" + VBA.Trim(VBA.str(nCnt))).Tag = VBA.Trim(lSheetsReport.Cells(lnNumRow, pnAddress_Col - lSheetsService.Range("E2")))
            Else
                lnNumRow = VBA.Val(VBA.Mid(lcPart, VBA.InStr(VBA.InStr(lcPart, ":"), lcPart, "$") + 1, VBA.InStr(lcPart, ")") - VBA.InStr(VBA.InStr(lcPart, ":"), lcPart, "$") - 1))
                lnNumRow1 = VBA.Val(VBA.Mid(lcPart, VBA.InStr(lcPart, "$") + 1, VBA.InStr(lcPart, ":") - VBA.InStr(lcPart, "$") - 1))
                
                .ListItems("_" + VBA.Trim(VBA.str(nCnt))).SubItems(1) = getCode(lnNumRow1) + ":" + getCode(lnNumRow)
                .ListItems("_" + VBA.Trim(VBA.str(nCnt))).Tag = VBA.Trim(lSheetsReport.Cells(lnNumRow1, pnAddress_Col - lSheetsService.Range("E2"))) + ":" + VBA.Trim(lSheetsReport.Cells(lnNumRow, pnAddress_Col - lSheetsService.Range("E2")))
            End If
        Else
            .ListItems("_" + VBA.Trim(VBA.str(nCnt))).SubItems(1) = "Все строки"
            .ListItems("_" + VBA.Trim(VBA.str(nCnt))).Tag = VBA.Trim(VBA.str(-1))
        End If
        If sumFlag Then
            lcLetter = VBA.Trim(Replace_in_Str(lcLetter, "СУММ(", ""))
        End If
        ' Посмотрим какая графа
        With lSheetsService
            lnColumn = .Range("KRIT_GRAF").Column
            lnColumnCount = .Range("KRIT_GRAF").Columns.count
            lnRow = .Range("KRIT_GRAF").row
            'Заполним критерий
            If VBA.InStr(1, lcLetter, "!") <> 0 Then lcLetter = VBA.Mid(lcLetter, VBA.InStr(1, lcLetter, "!") + 2, VBA.Len(lcLetter) - VBA.InStr(1, lcLetter, "!") - 1)
            
            .Cells(lnRow + 1, lnColumn + 1) = VBA.Trim(lcLetter)
            If pageName <> "" Then
                'определим номер листа
                i = .Cells(lnRow + 1, lnColumn + 2)
                .Range(.Cells(KRIT_RAZDEL_ROW + 1, KRIT_RAZDEL_COLUMN), .Cells(KRIT_RAZDEL_ROW + 1, KRIT_RAZDEL_COLUMN + KRIT_RAZDEL_COLUMNCOUNT - 1)) = ""
                .Cells(KRIT_RAZDEL_ROW + 1, KRIT_RAZDEL_COLUMN + 1) = pageName
                .Cells(lnRow + 1, lnColumn + 2) = .Cells(KRIT_RAZDEL_ROW + 2, KRIT_RAZDEL_COLUMN)
                .Cells(KRIT_RAZDEL_ROW + 1, KRIT_RAZDEL_COLUMN + 1) = ""
            End If
            
            lcText3 = .Cells(lnRow + 2, lnColumn)
            lnNumGraf = .Cells(lnRow + 2, lnColumn + 1)
            ' Сброс критерия
            If pageName <> "" Then
                .Cells(lnRow + 1, lnColumn + 2) = i
            End If
            .Range(.Cells(lnRow + 1, lnColumn), .Cells(lnRow + 1, lnColumn + lnColumnCount - 2)) = ""
        End With
        .ListItems("_" + VBA.Trim(VBA.str(nCnt))).SubItems(2) = lcText3
        .ListItems("_" + VBA.Trim(VBA.str(nCnt))).TooltipText = VBA.Trim(VBA.str(lnNumGraf))
    Next
End With

Exit Sub
doError:
    Call ERROR_EVENT("FILL_FORMULA_CONTENTS")
End Sub

Private Sub CommandButton5_Click()
    Call SEEK_POP_GET_DATA(2, False)
End Sub

Public Sub CmdBar_Click()
    Call SEEK_POP_GET_DATA(1, False)
    If pbFormCancel Then
        Me.TxtBar.value = SEEK_POP.pcRetValue
        Me.TxtNameStr.value = SEEK_POP.pcRetText
        Me.pcCodeStr = SEEK_POP.pcRetValue
        Me.pnLinkStr = VBA.Val(SEEK_POP.pcRetLink)
        Unload SEEK_POP
        Me.CmdOK.Enabled = (Me.pnTypeFormula = 4 And Me.TxtGraf <> "") Or (Me.pnTypeFormula <> 4 And Me.TxtBar <> "")
    End If
End Sub

Private Sub CmdExit_Click()
    Unload Me
End Sub

Public Sub CmdGraf_Click()
    Call SEEK_POP_GET_DATA(2, False)
    If pbFormCancel Then
        Me.TxtGraf.value = SEEK_POP.pcRetText
        Me.pnNumGraf = SEEK_POP.pcRetLink
        Unload SEEK_POP
    End If
End Sub

Private Sub CommandButton4_Click()
    'Debug.Print Me.ListView1.ListItems("_1").SubItems(1)
End Sub

Private Sub CmdOk_Click()
Dim lSheetsForm As Object
Dim lnRow As Long, lnColumn As Long
 
On Error GoTo doError
    
    pbFormCancel = True
    Set lSheetsForm = Sheets("Form")
        
    'Проверим, нет ли уже такой формулы
    'With lSheetsForm
    '    lnColumn = .Range("KRIT_FORM").Column
    '    lnRow = .Range("KRIT_FORM").row
    '    'Заполним критерий
    '    If FORMULAEDIT.pnTypeFormula <> 4 Then .Cells(lnRow + 1, lnColumn) = FORMULAEDIT.pnLinkStr
    '    .Cells(lnRow + 1, lnColumn + 4) = FORMULAEDIT.pnTypeFormula
    '    If (FORMULAEDIT.pnTypeFormula = 1) Then .Cells(lnRow + 1, lnColumn + 1) = 0
    '    If (FORMULAEDIT.pnTypeFormula <> 1) Then .Cells(lnRow + 1, lnColumn + 1) = FORMULAEDIT.pnNumGraf
    '    'If  Then .Cells(lnRow + 1, lnColumn + 1) = FORMULAEDIT.pnNumGraf
    'End With
   '
    'If pbMode = True Then
    '    lSheetsForm.Cells(lnRow + 1, lnColumn + 2) = "<>" + VBA.str(FORMULAEDIT.pnNumFormula)
    'End If
   
    'If lSheetsForm.Cells(lnRow + 2, lnColumn + 2) <> 1 Then
    '    Call MsgBox("Формула данного типа для этой строки (графы, ячейки) уже существует!", vbOKOnly, "Внимание!")
    'Else
    '    Call Create_Formula
    '    Me.Hide
    'End If
    
    Call Create_Formula
    Me.Hide
Exit Sub
doError:
    Call ERROR_EVENT("FORMULAEDIT.CmdOk_Click")
End Sub

Private Sub ListView1_BeforeLabelEdit(Cancel As Integer)
    Cancel = True
End Sub

Private Sub ListView1_DblClick()
    If Me.ListView1.ListItems.count <> 0 Then
        Edit_Formula_Item (Me.ListView1.SelectedItem.Key)
    End If
End Sub


Private Sub ListView1_KeyDown(KeyCode As Integer, ByVal Shift As Integer)
If KeyCode = 13 Then
    If Me.ListView1.ListItems.count <> 0 Then
        Edit_Formula_Item (Me.ListView1.SelectedItem.Key)
    End If
End If

End Sub

Private Sub ListView1_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then
    If Me.ListView1.ListItems.count <> 0 Then
        Edit_Formula_Item (Me.ListView1.SelectedItem.Key)
    End If
End If

End Sub


Private Sub TlbFormula_ButtonClick(ByVal Button As MSComctlLib.Button)
Select Case Button.Key
    Case "B1"
        Call New_Formula_Item
    Case "B2"
        Call Edit_Formula_Item(Me.ListView1.SelectedItem.Key)
    Case "B3"
        Call Del_Formula_Item(Me.ListView1.SelectedItem.Key)
    Case "B5"
        Unload Me
End Select

End Sub

' Процедура инициализации формы
Public Sub Form_init()
Dim lcTextFormula As String
Dim lnCodeItog As Integer
Dim lnColumn As Long, lnColumnCount As Long, lnRow As Long
Dim lnColumng As Long, lnColumnCountg As Long, lnRowg As Long
Dim lSheetsService As Object, lSheetsReport As Object, lSheetsForm As Object, LookRange As Range
 
On Error GoTo doError
    
Set lSheetsService = Sheets("Service")
Set lSheetsReport = Sheets(Sheets("Service").Range("B19").Text)
Set lSheetsForm = Sheets("Form")

With lSheetsForm.Range("KRIT_FORM")
    lnColumn = .Column
    lnColumnCount = .Columns.count
    lnRow = .row
End With
    
With lSheetsService.Range("KRIT_GRAF")
    lnColumng = .Column
    lnColumnCountg = .Columns.count
    lnRowg = .row
End With

If FORMULAEDIT.pbMode Then ' режим редактирования
    ' Заполним код строки
    Me.TxtBar.value = FORMULAEDIT.pcCodeStr ' Код строки
    If pnLinkStr > 0 Then
        Set LookRange = lSheetsReport.Range("LINK").Find(pnLinkStr, LookIn:=xlFormulas, lookat:=xlWhole)
        ' Заполним наименование строки
        Me.TxtNameStr.value = lSheetsReport.Cells(LookRange.row, pnAddress_Col - lSheetsService.Range("E5"))
    Else
        Me.TxtNameStr.value = "Все строки"
    End If
    ' Заполним наименование графы
    lSheetsService.Cells(lnRowg + 1, lnColumng) = FORMULAEDIT.pnNumGraf
    lSheetsService.Cells(lnRowg + 1, lnColumng + 1) = ""
    Me.TxtGraf.value = lSheetsService.Cells(lnRowg + 2, lnColumng)
    lSheetsService.Cells(lnRowg + 1, lnColumng) = ""
    ' Заполним номер формулы
    Me.TxtNumForm.value = VBA.Trim(VBA.str(pnNumFormula))
    ' Заполним Текст типа формулы
    Me.TxtTypeFormula.value = pcTypeFormula
    
    ' Заполнение формулы слагаемыми
    With lSheetsForm
        .Range(.Cells(lnRow + 1, lnColumn), .Cells(lnRow + 1, lnColumn + lnColumnCount - 2)) = ""
        .Cells(lnRow + 1, lnColumn) = IIf(Me.pnTypeFormula = 4, -1, pnLinkStr)
        .Cells(lnRow + 1, lnColumn + 1) = IIf(Me.pnTypeFormula = 1, 0, pnNumGraf)
        .Cells(lnRow + 1, lnColumn + 2) = pnNumFormula
        lcTextFormula = .Cells(lnRow + 2, lnColumn)
        FORMULAEDIT.pnCodeItog = .Cells(lnRow + 3, lnColumn)
        pnRowForm = .Cells(lnRow + 4, lnColumn) ' Номер записи Excel
        .Range(.Cells(lnRow + 1, lnColumn), .Cells(lnRow + 1, lnColumn + lnColumnCount - 2)) = ""
    End With
    'Установка знака
    Me.CmbZnak.ListIndex = FORMULAEDIT.pnCodeItog - 1
    Call FILL_FORMULA_CONTENTS(lcTextFormula)
Else ' Режим новая
    ' Заголовок ListView
    With Me.ListView1
        .ColumnHeaders.Add 1, "_1", "Знак", 50, 0
        .ColumnHeaders.Add 2, "_2", "Код строки", 70, 0
        .ColumnHeaders.Add 3, "_3", "Графы", 300, 0
    End With
    
    lSheetsForm.Range(lSheetsForm.Cells(lnRow + 1, lnColumn), lSheetsForm.Cells(lnRow + 1, lnColumn + lnColumnCount - 2)) = ""
    
    Me.TxtNumForm.value = VBA.Trim(VBA.str(Sheets("FORM").Range("I6") + 1))
    Me.pnNumFormula = VBA.Val(Me.TxtNumForm.value)
    Me.TxtTypeFormula.value = pcTypeFormula

    If (Me.pnTypeFormula <> 4) And (ActiveCell.row >= pnAddress_Row And ActiveCell.row < Application.ActiveWorkbook.Sheets("Service").Range("A9") + pnAddress_Row) Then
        'Установим данные с текущей строки
        Me.pnLinkStr = lSheetsReport.Cells(Application.ActiveCell.row, Application.Names("LINK").RefersToRange.Column)  ' Link строки
        Me.pcCodeStr = getCode(Application.ActiveCell.row) ' код строки
        Me.TxtNameStr.Text = lSheetsReport.Cells(Application.ActiveCell.row, lSheetsService.Range("C6") - lSheetsService.Range("E5"))
        Me.TxtBar.Text = Me.pcCodeStr
        Me.pnNumGraf = Application.ActiveCell.Column - lSheetsService.Range("C6") + 1 ' номер графы
        
        ' Заполним наименование графы
        lSheetsService.Cells(lnRowg + 1, lnColumng) = Me.pnNumGraf
        lSheetsService.Cells(lnRowg + 1, lnColumng + 1) = ""
        Me.TxtGraf.value = lSheetsService.Cells(lnRowg + 2, lnColumng)
        lSheetsService.Cells(lnRowg + 1, lnColumng) = ""
    End If
    
    ' Запрещаем кнопку "Сохранить"
    Me.CmdOK.Enabled = False
End If
' Определим параметры формы от типа формулы
Select Case Me.pnTypeFormula
    Case 1 ' Вертикальный контроль
            Me.CmdGraf.Enabled = False
            Me.TxtGraf = "Все графы"
    Case 4 ' Горизонтальный контроль
            Me.CmdBar.Enabled = False
            Me.TxtNameStr.value = "Все строки"
    Case 2 '
            Me.CmdGraf.Enabled = False
End Select

Exit Sub
doError:
    Call ERROR_EVENT("FORMULAEDIT.Form_init")
End Sub

Private Sub TxtBar_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then
    Call Me.CmdBar_Click
End If
End Sub

Private Sub TxtBar_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii = 13 Then
    Call Me.CmdBar_Click
End If
End Sub

Private Sub TxtGraf_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii = 13 Then
    Call Me.CmdGraf_Click
End If
End Sub

Private Sub UserForm_Initialize()
Dim lnRowZnak As Integer, lnColumnZnak As Integer, nCnt As Long
' Заполнение знаков формул
 
On Error GoTo doError
    
With Sheets("Service").Range("S_ZNAK")
    lnRowZnak = .row
    lnColumnZnak = .Column
    For nCnt = 1 To .Rows.count - 1
        Me.CmbZnak.AddItem Sheets("Service").Cells(lnRowZnak + nCnt, lnColumnZnak + 1)
    Next
    Me.CmbZnak.ListIndex = 0
End With
' Set Toolbar
    With Me.TlbFormula
        .ImageList = Me.ImageList1
        .Buttons("B1").Image = 1
        .Buttons("B2").Image = 2
        .Buttons("B3").Image = 3
        .Buttons("B5").Image = 4
    End With
Me.Caption = pcNameApp + Me.Caption

Exit Sub
doError:
    Call ERROR_EVENT("FORMULAEDIT.UserForm_Initialize")
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = 1 Or CloseMode = 0 Then
    pbFormCancel = False
End If
End Sub
