Solved

Excel automation

Posted on 2004-04-23
3
703 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Enroll in June's Course of the Month

June's Course of the Month is now available! Every 10 seconds, a consumer gets hit with ransomware. Refresh your knowledge of ransomware best practices by enrolling in this month's complimentary course for Premium Members, Team Accounts, and Qualified Experts.

Question has a verified solution.

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

Introduction: Displaying information on the statusbar.   Continuing from the third article about sudoku.   Open the project in visual studio. Status bar – let’s display the timestamp there.  We need to get the timestamp from the document s…
Introduction: Hints for the grid button.  Nested classes, templated collections.  Squash that darned bug! Continuing from the sixth article about sudoku.   Open the project in visual studio. First we will finish with the SUD_SETVALUE messa…
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.
If you're a developer or IT admin, you’re probably tasked with managing multiple websites, servers, applications, and levels of security on a daily basis. While this can be extremely time consuming, it can also be frustrating when systems aren't wor…

695 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