Solved

Excel automation

Posted on 2004-04-23
3
696 Views
Last Modified: 2013-11-20
How to copy a cell or group of cells and paste in same sheet and in different sheets, how to copy a excel sheet
0
Comment
Question by:krush_ice
  • 2
3 Comments
 
LVL 1

Accepted Solution

by:
kevinnguyen earned 150 total points
ID: 10905790
I used Excel XP on Win2K. There should be some minor changes with Excel 97, 2000, or 2003. Below is my code snippet:

#include <comdef.h>
#import "C:\Program Files\Common Files\Microsoft Shared\Office10\mso.dll"
#import "C:\Program Files\Common Files\Microsoft Shared\VBA\VBA6\vbe6ext.olb"
#import "C:\Program Files\Microsoft Office\Office10\excel.exe" \
         rename("DialogBox", "ExcelDialogBox") \
         rename("RGB", "ExcelRGB") \
         exclude("IFont", "IPicture") \
         named_guids

using namespace Excel;

int main(int argc, char *argv[])
{
    unsigned short  i;
    _variant_t      v1, v2, v3, v4;
    _ApplicationPtr app;
    _WorkbookPtr    book;
    _WorksheetPtr   wsh1, wsh2, wsh3;
    RangePtr        r;    

    CoInitialize(0);
    app.CreateInstance(__uuidof(Application));
    book = app->GetWorkbooks()->Add();
    wsh1 = book->Worksheets->Item[_variant_t((short)1)];
    r    = wsh1->Cells;
    v1.SetString("Hello, world !");
    for(i = 1; i <= 10; ++i)
        r->Item[_variant_t((short)i)][_variant_t((short)1)] = v1;    
     
    // Copy contents of worksheet 1 entirely and paste into worksheet 2
    wsh2 = book->Worksheets->Item[_variant_t((short)2)];        
    r->Copy();
    wsh2->Paste();
   
    // Copy a range from A1 to A10 on worksheet 1 and paste into worksheet 3
    v2.SetString("A1");
    v3.SetString("A10");
    wsh1->GetRange(v2, v3)->Copy();
    wsh3 = book->Worksheets->Item[_variant_t((short)3)];
    wsh3->GetRange(v2, v3)->PasteSpecial(xlPasteValues, xlPasteSpecialOperationNone);

    // Copy value of cell A1 on worksheet 1 and paste into cell B11 of worksheet 3
    v1.SetString("A1");
    v2.SetString("A1");
    v3.SetString("B11");
    v4.SetString("B11");
    wsh1->GetRange(v1, v2)->Copy();
    wsh3->GetRange(v3, v4)->PasteSpecial(xlPasteValues, xlPasteSpecialOperationNone);
       
    app->PutVisible(0, VARIANT_TRUE);
    Sleep(4000);    
    CoUninitialize();
    return 0;
}

Good Luck

kevinnguyen
0
 

Expert Comment

by:aerowang
ID: 10937671
First you can create a new file with at "C:\\Book1.xls",and you can input a string at cell(a1),then you can establish a MFC project(dialog based),finally you can insert a button in the "about" dialog,
the code is as follows:
void CExcelDialog::OnButton1()
{              _Application2000 app;  // app is the Excel _Application object
      Workbooks2000 books;
      _Workbook2000 book;

      Worksheets2000 sheets;
      _Worksheet2000 sheet;
      Range2000 range;
      Font2000 font;
      Range2000 rows;
      Range2000 cols;
      Range2000 row;
      Range2000 col;
      Range2000 cells;
      Range2000 cell;

      VARIANT vtValue;
      VariantInit(&vtValue);
      COleVariant VOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
      
      // Start Excel and get Application object...
      // Instantiate Excel and open an existing workbook.
      if(!app.CreateDispatch("Excel.Application"))
      {
            AfxMessageBox("Couldn't CreateDispatch() for Excel");
            return;
      }

      books = app.GetWorkbooks();
      book = books.Open("C:\\Book1.xls",
            VOptional, VOptional, VOptional, VOptional,
            VOptional, VOptional, VOptional, VOptional,
            VOptional, VOptional, VOptional, VOptional);
      sheets =book.GetSheets();
      sheet = sheets.GetItem(COleVariant((short)1));

      range = sheet.GetRange(COleVariant("a1"),COleVariant("a1"));

      int nCount = range.GetCount();
      vtValue = range.GetValue();
      

      COleSafeArray sa;
      if( nCount > 1 )
            sa.Attach(vtValue);
      else{
            sa.CreateOneDim(VT_VARIANT, 1, &vtValue);
      }

      
      sheet = sheets.GetItem(COleVariant((short)2));
      range = sheet.GetRange(COleVariant("a1"),COleVariant("a1"));
                range.SetValue(COleVariant(sa));

      //Make the application visible and give the user control of Microsoft Excel
      app.SetVisible(TRUE);
      app.SetUserControl(TRUE);
      app.ReleaseDispatch();
}
Wish you good luck!
This program copy the string in cell(A1) of sheet1 to cell(A1) of sheet2,you can modify it to get more effects!
I'm using excel Automation with MFC these days.If you have some experience,shall we exchange?
0
 
LVL 1

Expert Comment

by:kevinnguyen
ID: 10940283
I used to use MFC wrapper classes a lot for Excel automation. It simplies automation coding but adds a lot of overheads to executable file (you compare the size of exectable file created with MFC with that of executable file created with COM smart pointers).

If you know OLE automation is built on top of COM and you understand how COM works, you will find that you are better off using smart pointers (#import statement) rather than MFC wrapper classes.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Process filename extension 3 194
Define unique primary key 9 95
fizzArray2 challenge 1 90
Excel file not created as expected 7 79
Introduction: Finishing the grid – keyboard support for arrow keys to manoeuvre, entering the numbers.  The PreTranslateMessage function is to be used to intercept and respond to keyboard events. Continuing from the fourth article about sudoku. …
Introduction: Ownerdraw of the grid button.  A singleton class implentation and usage. Continuing from the fifth article about sudoku.   Open the project in visual studio. Go to the class view – CGridButton should be visible as a class.  R…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question