Solved

Excel automation

Posted on 2004-04-23
3
684 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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
ADO Memory leak with DELPHI 2007 37 153
if loop in java 3 114
only14 challenge 19 63
FizzBuzz challenge 9 71
In this article, I'll describe -- and show pictures of -- some of the significant additions that have been made available to programmers in the MFC Feature Pack for Visual C++ 2008.  These same feature are in the MFC libraries that come with Visual …
Introduction: Database storage, where is the exe actually on the disc? Playing a game selected randomly (how to generate random numbers).  Error trapping with try..catch to help the code run even if something goes wrong. Continuing from the seve…
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.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.

763 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now