powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Delphi [игнор отключен] [закрыт для гостей] / delphi ole excel findformat mergecells
19 сообщений из 19, страница 1 из 1
delphi ole excel findformat mergecells
    #39665545
andreymx
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Надо вызвать в delphi через ole excel и настроить findformat на mergecells

в экселе это выглядит вот так
Код: vbnet
1.
 Application.FindFormat.MergeCells = True



в делфи по-простому не взлетело
Код: pascal
1.
ExcelApp.FindFormat.MergeCells := True; -- не компилится; да и не должно, там целая структура для FindFormat

Код: pascal
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
// *********************************************************************//
// DispIntf:  CellFormat
// Flags:     (4096) Dispatchable
// GUID:      {00024450-0000-0000-C000-000000000046}
// *********************************************************************//
  CellFormat = dispinterface
    ['{00024450-0000-0000-C000-000000000046}']
    property Application: ExcelApplication readonly dispid 148;
    property Creator: XlCreator readonly dispid 149;
    property Parent: IDispatch readonly dispid 150;
    property Borders: Borders dispid 435;
    property Font: Font dispid 146;
    property Interior: Interior dispid 129;
    property NumberFormat: OleVariant dispid 193;
    property NumberFormatLocal: OleVariant dispid 1097;
    property AddIndent: OleVariant dispid 1063;
    property IndentLevel: OleVariant dispid 201;
    property HorizontalAlignment: OleVariant dispid 136;
    property VerticalAlignment: OleVariant dispid 137;
    property Orientation: OleVariant dispid 134;
    property ShrinkToFit: OleVariant dispid 209;
    property WrapText: OleVariant dispid 276;
    property Locked: OleVariant dispid 269;
    property FormulaHidden: OleVariant dispid 262;
    property MergeCells: OleVariant dispid 208;
    procedure Clear; dispid 111;
  end;



Цель всего этого:
надо найти, есть ли в выбранном диапазоне объединенные ячейки. Если есть - то может глючить загрузка ячеек в массив через Ole
Код: pascal
1.
ExcelObject.Range[sh.Cells[FirstRow, FirstCol], sh.Cells[FirstRow + RowCount-1, FirstCol+ColCount-1]].select;



перебором по каждой ячейке искать медленно
хотел побыстрее, поиском



В общем, если идеи есть, прошу помощи
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39665546
andreymx
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
версия - д7
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39665619
Фотография _Vasilisk_
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
andreymx
Код: pascal
1.
не компилится; да и не должно,

Вообще-то должно. Не компилится с какой ошибкой? Какие типы у ExcelApp и FindFormat?
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39665682
andreymx
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Код: pascal
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
    property FindFormat: CellFormat read Get_FindFormat write _Set_FindFormat;


    procedure _Set_FindFormat(const RHS: CellFormat);

// *********************************************************************//
// DispIntf:  CellFormat
// Flags:     (4096) Dispatchable
// GUID:      {00024450-0000-0000-C000-000000000046}
// *********************************************************************//
  CellFormat = dispinterface
    ['{00024450-0000-0000-C000-000000000046}']
    property Application: ExcelApplication readonly dispid 148;
    property Creator: XlCreator readonly dispid 149;
    property Parent: IDispatch readonly dispid 150;
    property Borders: Borders dispid 435;
    property Font: Font dispid 146;
    property Interior: Interior dispid 129;
    property NumberFormat: OleVariant dispid 193;
    property NumberFormatLocal: OleVariant dispid 1097;
    property AddIndent: OleVariant dispid 1063;
    property IndentLevel: OleVariant dispid 201;
    property HorizontalAlignment: OleVariant dispid 136;
    property VerticalAlignment: OleVariant dispid 137;
    property Orientation: OleVariant dispid 134;
    property ShrinkToFit: OleVariant dispid 209;
    property WrapText: OleVariant dispid 276;
    property Locked: OleVariant dispid 269;
    property FormulaHidden: OleVariant dispid 262;
    property MergeCells: OleVariant dispid 208;
    procedure Clear; dispid 111;
  end;
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39665683
andreymx
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
хм... вроде скомпилировался
Код: pascal
1.
  ExcelApp.FindFormat.MergeCells := true;
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39665772
Фотография _Vasilisk_
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
andreymxхм... вроде скомпилировалсяВот и я удивился, что возникли какие-то проблемы
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39665801
andreymx
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
как понять, что найдена ячейка (ячейки)? она может быть найдена, но без текста

Код: pascal
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
var
  ExcelApp        : TExcelApplication
  ExcelObject     : Variant;
  FileName : string;
  Range1 : variant;
begin  ExcelApp := nil;
  ExcelApp := TExcelApplication.create(nil);
  ExcelApp.FindFormat.MergeCells := true;

  ExcelApp.Connect;


  ExcelObject := GetActiveOleObject('Excel.Application');

  filename := 'C:\qq\bad.xlsx';
  ExcelObject.Workbooks.open(FileName);
  ExcelObject.Range['a1:b14'].select;
  Range1 := ExcelObject.selection.Find(
      What := '',
      LookIn := xlValues,
      SearchOrder := xlByColumns,
      SearchDirection := xlNext,
      MatchCase:= False,
      SearchFormat:=True);
  showmessage(VarToStr(Range1) + '/' + VarTypeAsText(VarType(Range1)));
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39665939
Фотография _Vasilisk_
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-find-method-excel Return Value
A Range object that represents the first cell where that information is found.

Remarks
This method returns Nothing if no match is found. The Find method does not affect the selection or the active cell.Что такое Nothing - сказать сложно. Посмотри какой будет VarType у возвращаемого результата?
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39665944
Фотография makhaon
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
andreymx,

Может если не найдено, то Range1 какой-то особенный станет? null, например?
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39665952
Фотография _Vasilisk_
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Вот люди извращаются
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39669755
andreymx
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
andreymxнадо найти, есть ли в выбранном диапазоне объединенные ячейки. Если есть - то может глючить загрузка ячеек в массив через Oleнаконец-то допёр, в чём дело

всё очень просто, но я тупил долго :)

когда выделяешь диапазон, а в этом диапазоне есть объединенные ячейки, выходящие за пределы выделяемого диапазона, то диапазон-то автоматически расширяется
я это тыщи раз наблюдал в самом экселе, но связать это со своей проблемой удалось далеко не сразу
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39673311
andreymx
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
сделал контроль
Код: pascal
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
    RequestedAddress := 'R' + IntToStr(FirstRow)            + 'C' + IntToStr(FirstCol) + ':' +
                        'R' + IntToStr(RowCount+FirstRow-1) + 'C' + IntToStr(ColCount+FirstCol-1);
    SelectionAddress := ExcelObject.selection.address[True, True, xlR1C1, EmptyParam, EmptyParam];
    if SelectionAddress <> RequestedAddress then
    begin
      msg := 'При загрузке данных выявлено наличие объединенных ячеек:'#13 +
             'запрошен диапазон ' + RequestedAddress + #13 +
             'получен  диапазон  ' + SelectionAddress + #13 +
             'Корректность данных не гарантирована!';

      iAlert := AlertStandard(msg, ['Продолжить', 'Прервать загрузку'], mtWarning);
      if iAlert = 2 then
      begin
        raise exception.Create(msg);
      end;
    end;
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39673314
Соколинский Борис
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Жуть какая-то...
Код: pascal
1.
if Cells[FirstRow,FirstCol].Resize[RowCount, ColCount].MergeCells<>null then...
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39673318
andreymx
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Соколинский БорисЖуть какая-то...
Код: pascal
1.
if Cells[FirstRow,FirstCol].Resize[RowCount, ColCount].MergeCells<>null then...

OK, завтра попробую
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39673348
andreymx
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Соколинский БорисЖуть какая-то...
Код: pascal
1.
if Cells[FirstRow,FirstCol].Resize[RowCount, ColCount].MergeCells<>null then...

вспомнил, проверил
Код: vbnet
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
    Range("c3:c4").Select
    If Selection.MergeCells Then
       MsgBox "mergedCells"
    Else
       MsgBox "no mergedCells"
    End If
    Range("c4:c4").Select
    If Selection.MergeCells Then
       MsgBox "mergedCells"
    Else
       MsgBox "no mergedCells"
    End If

это работает, только если в выделении все ячейки являются объединенными
в моем же примере в первом случае выдается no mergedCells
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39673352
Соколинский Борис
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
andreymx,
Это очень странно. Проверь макросом

Код: vbnet
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
Sub checkmerge()
  Dim V As Variant
  V = Selection.MergeCells

  If (V = Null) Or (V = False) Then
    MsgBox "No merged cells"
  Else
    MsgBox "Range contains merged cells"
  End If
End Sub
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39673517
andreymx
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Код: vbnet
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
Sub checkmerge()
  Dim V As Variant
  
  Range("a1:a1").Select
  V = Selection.MergeCells
    
  If (V = Null) Then
    MsgBox "merged=null"
  ElseIf (V = False) Then
    MsgBox "merged=false"
  ElseIf (V = True) Then
    MsgBox "merged=true"
  Else
    MsgBox "merged=[" + merged + "]"
  End If

  Range("c3:c4").Select
  V = Selection.MergeCells
    
  If (V = Null) Then
    MsgBox "merged=null"
  ElseIf (V = False) Then
    MsgBox "merged=false"
  ElseIf (V = True) Then
    MsgBox "merged=true"
  Else
    MsgBox "merged=[" + merged + "]"
  End If

  Range("c4:c4").Select
  V = Selection.MergeCells
    
  If (V = Null) Then
    MsgBox "merged=null"
  ElseIf (V = False) Then
    MsgBox "merged=false"
  ElseIf (V = True) Then
    MsgBox "merged=true"
  Else
    MsgBox "merged=[" + merged + "]"
  End If

End Sub



Range("a1:a1").Select
merged=false

Range("c3:c4").Select
merged=[]

Range("c4:c4").Select
merged=true
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39673520
andreymx
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Код: vbnet
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
Range("a1:a1").Select
merged=false
Selection.Address=R1C1

Range("c3:c4").Select
merged=[]
Selection.Address=R3C3:R5C4

Range("c4:c4").Select
merged=true 
Selection.Address=R4C3:R5C4
...
Рейтинг: 0 / 0
delphi ole excel findformat mergecells
    #39673523
andreymx
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
...
Рейтинг: 0 / 0
19 сообщений из 19, страница 1 из 1
Форумы / Delphi [игнор отключен] [закрыт для гостей] / delphi ole excel findformat mergecells
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]