Solved

Excel automation

Posted on 2004-04-23
3
692 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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How to calculate times for developing software? 8 67
Prevent this page from creating additional dialogs. 3 534
Change to event 1 113
Increment column based of a FK 8 23
Introduction: Load and Save to file, Document-View interaction inside the SDI. Continuing from the second article about sudoku.   Open the project in visual studio. From the class view select CSudokuDoc and double click to open the header …
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
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.
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

803 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