關於在Excel中使用搜尋的操作(Find)

有關Delphi 的語法, 程式, 等
回覆文章
頭像
tim
文章: 1380
註冊時間: 2008年 11月 26日, 00:49

關於在Excel中使用搜尋的操作(Find)

文章 tim »

http://delphi.ktop.com.tw/topic.asp?TOPIC_ID=41639

可以使用 VarIsEmpty 來檢驗 Find 傳回的 Cell 是否為找到的 cell !!



關於是否找到的問題, 可以使用 VarIsEmpty 來測試, 即可很容易明白是否有找到, 唯在 excel 中, findnext 是會一直重覆重頭再來找, 所以要找完整個文件, 必須自行記錄第一個找到的 cell 並記錄下來, 藉以比對, 是否 excel 又重頭開始找了, 程式如下:

代碼: 選擇全部

     
    procedure Tform1.Button1Click(Sender: TObject); 
    var 
      FExcel : variant; 
      FWorkBook : variant; 
      FWorkSheet : variant; 
      FCell: variant; 
      FindRow, FindColumn: integer; 
    begin 
     
     
      try 
        FExcel := CreateOLEObject( 'Excel.Application' ); 
        FWorkBook := FExcel.WorkBooks.Open('c:1.xls'); 
        FWorkSheet := FWorkBook.WorkSheets[1]; 
      except 
        raise Exception.Create('無法啟動excel'); 
        exit; 
      end; 
     
      FExcel.visible := True; 
     
     
      FCell := FWorkSheet.cells.Find('test'); 
      if not VarIsEmpty(FCell) then    // if the data is find, VarIsEmpty is very useful to exam the result 
      begin 
        // find first cell and record the row and column 
        FindRow := FCell.Row; 
        FindColumn := FCell.Column; 
      end 
      else 
      begin 
        ShowMessage('not found'); 
        exit; 
      end; 
      repeat 
        FCell := FWorkSheet.cells.FindNext(FCell); 
        ShowMessage(FCell); 
      until (FindRow = FCell.Row) and (FindColumn = FCell.Column); // compare if the found cell is the first found cell 
     
    end; 
多多留言, 整理文章, 把經驗累積下來.....
回覆文章