C# set opened workbook - c#

I started creating an Excel-Add-IN with C#.
what I need to do is simple, I need to set a workbook to a variable, the workbook is already running, I tried this but did not work
Excel.Application excel = new Excel.Application();
Excel.Workbook wb = excel.ActiveWorkbook as Excel.Workbook;
wb.SaveAs("C:\\Users\\ro_sg\\Desktop\\Pasta1.xlsx");
Excel.Worksheet ws = wb.Worksheets["Plan1"];
Excel.Range range = ws.Range["A1"];
range.Value = "Success";
wb.Save();
The wb variable cannot find the workbook (gets null), and I can't see why.
Please, if any of you spot the mistake let me know.
Thanks!

I believe your issue is it may not be finding the active Excel application upstream from when you set your workbook variable. It appears that your code is trying to create a new excel application (without a workbook) rather than get the existing one that is open.
Give this a try:
Excel.Application excel = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
Excel.Workbook wb = (Excel.Workbook)excel.ActiveWorkbook;
wb.SaveAs("D:\\WeeeDueceDuece.xlsx");

I don't know if you need to get a specific Sheet but if you try this: Excel.Worksheet ws = wb.Worksheets[1]; It will get the first Sheet of your Workbook

If your actual code doesn't have more in-between steps, it will always fail. I'm surprised this line didn't error:
Excel.Workbook wb = excel.ActiveWorkbook as Excel.Workbook;
It's because a new instance of Excel does not necessarily create a new workbook. You can check this with the following lines:
Excel.Application application = new Excel.Application();
Excel.Workbooks workbooks = application.Workbooks;
Console.WriteLine(workbooks.Count); // "0"
The new workbook, however, should create the default number of worksheets (usually 3, but editable).

Related

Excel Interop set View style of worksheet to a normal view

How do I change the view style of Excel Worksheet In Excel interop to a Normal style?
Like this:
Just have no idea :(
Does someone know?
i see just one solution, you have to use ActiveWindow.View: a sample to use it
using Excel = Microsoft.Office.Interop.Excel;
object missing = System.Reflection.Missing.Value;
Excel.Application excel = new Excel.Application();
Excel.Workbooks wbs = excel.Workbooks;
Excel.Workbook wb = wbs.Open(#"d:\test.xlsm");
Excel.Worksheet sheet = wb.ActiveSheet;
// set the view style
excel.ActiveWindow.View = XlWindowView.xlNormalView;
object filename = #"d:\test1.xlsm";
wb.SaveAs(filename);
wbs.Close();
excel.Quit();
if you have more Worksheets, you have to do that on each Worksheet...

visible and hide specific excel sheet in C#

this is my variables and my input and result excel file are in different workbooks and I want to show the output workbook only. I want to show Targetworkboo1 in output but with this code, sourceworkbook and Targetworkbook1 will be shown in output. how should I do it?
Excel.Application xlApp = new Excel.Application();
Excel.Workbook SourceWorkbook;
xlApp.Visible = true;
Excel.Workbook TargetWorkbook1;
Excel.Worksheet SourceWorksheet;
Excel.Worksheet TargetWorksheet1;
SourceWorksheet = SourceWorkbook.Worksheets[1];
TargetWorkbook1 = xlApp.Workbooks.Add();
TargetWorksheet1 = TargetWorkbook1.Worksheets[1];
Hide any sheets in excel workbook using this code:
SourceWorksheet.Visible=Excel.XlSheetVisibility.xlSheetHidden;
Hide the window of the workbook:
SourceWorkbook.Windows[1].Visible = false;

c#: Excel obj count is 0 while accessing through GetActiveObject("Excel.Application")

excel object returns count zero Please refer the screenshot.
I need to access objects of file type PPT, Excel, Word which are opened through an application similar to sharepoint.
While I try getting count of opened excel files I always get the count as 0. I already searched if I can get help, got to see this Accessing an open Excel Workbook in C# but though implementing the solution it returns 0.
Microsoft.Office.Interop.Excel.Application xlObj =
(Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
while (xlObj.Windows.Count == 0) // This line returns the count as 0
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"C:\Users\nagendra.k.kumar\Desktop\Talent Review - Nagendra Kumar.xlsx");
Microsoft.Office.Interop.Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Microsoft.Office.Interop.Excel.Range xlRange = lWorksheet.UsedRange;
MessageBox.Show(xlRange.Rows.Count.ToString());

Change ActiveWorkbook When Multiple Instances Open

I am opening an Excel file, and if it does not meet certain conditions, I am then creating a new workbook. Problem I am having is that when the new workbook is created it is not by default set to the activeworkbookso when I try to use activeworkbook.saveas()it saves the 1st workbook, with inaccurate data.
This is what I am using to create the new workbook:
Excel.Workbook newWorkbook = this.Application.Workbooks.Add();
Can someone show me how to change activeworkbook in Excel when multiple workbooks are opened?
BTW this is Excel 2007 I am working with.
Copy worksheet to new workbook
ws = wb.Sheets["Mitchell"];
((Excel.Worksheet)ws).Copy();
Configuration Details:
Code is written in vb.net using Visual Studio 2010 Professional
All example code is placed in the ThisAddIn_Startup event handler of the
Application-Level Add-In for Excel 2010
In project references (right click project > properties >
references) make sure there is a check beside Excel = Microsoft.Office.Interop.Excel
When multiple worksheets are open, I use For Each to loop through the collection and see the names...
For Each wrkbk As Excel.Workbook In Me.Application.Workbooks
MsgBox(wrkbk.Name)
Next
Combine this with a Select Case and this allows you get at any workbook that is open.
For Each wrkbk As Excel.Workbook In Me.Application.Workbooks
Select Case wrkbk.Name
Case "Book1"
wrkbk.Activate()
Case "Book2"
Case Else
End Select
Next
Now, tying it all together, you can do this:
Create a new workbook named CustomWorkbook.xlsx
Activate Book1, copy Sheet1, and paste it into CustomWorkbook.xlsx (rename sheet to CopiedWorksheet)
Activate CustomWorkbook.xlxs
//Hide alerts so no prompts display when using SaveAs to rename new workbook
Me.Application.DisplayAlerts = False
//Programatically create a new workbook
Dim myWrkbk As Excel.Workbook
myWrkbk = Me.Application.Workbooks.Add()
//Name new workbook
myWrkbk.SaveAs("CustomWorkbook")
//Set Book1 as the active workbook (so can copy sheet)
Application.Workbooks("Book1").Activate()
//Create a new worksheet variable
Dim sourceWrksht As Excel.Worksheet
sourceWrksht = Application.Worksheets("Sheet1")
sourceWrksht.Range("A1").Value = "Text in a Cell"
//Select Sheet1 and copy into CustomWorkbook and paste as first sheet
sourceWrksht.Select()
sourceWrksht.Copy(Before:=Application.Workbooks("CustomWorkbook.xlsx").Sheets(1))
//Rename copied worksheet
Dim destinationWrksht As Excel.Worksheet
destinationWrksht = Application.Workbooks("CustomWorkbook.xlsx").Sheets(1)
destinationWrksht.Name = "CopiedWorksheet"
//Loop through all open workbooks in Excel Application
For Each wrkbk As Excel.Workbook In Me.Application.Workbooks
Select Case wrkbk.Name
Case "CustomWorkbook.xlsx"
wrkbk.Activate()
Case "Book1"
Case Else
End Select
Next
//Set Excel to show alerts again
Me.Application.DisplayAlerts = True
Simply call the Activate() method on the workbook you want to show.
When you create a new workbook you could use this:
Excel.Wokrbook oldWorkbook = this.Application.ActiveWorkbook;
Excel.Workbook newWorkbook = this.Application.Workbooks.Add();
oldWorkbook.Activate();
And after a while:
newWorkbook.Activate();
See the docs at MSDN.
Except:
The Activate method of the Workbooks collection activates a Microsoft Office Excel workbook and selects the first sheet in the workbook.
EDIT:
This works for me:
Excel.Workbook oldWorkbook = this.Application.ActiveWorkbook;
this.Application.ActiveWorkbook.Sheets["name"].Copy();
Excel.Workbook newWorkbook = this.Application.ActiveWorkbook;
old = Book1
new = Book2

Error While using Excel Interop's set_Value(XLRangeValueDataType.XLRangeValueMSPersistXML,object)

I am getting error while using the Excel Interops set_Value on a range.
Any help/suggestion will be valuable.
This is the code which is failing.
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp = new Excel.ApplicationClass();
Excel.WorkBook WB = xlApp.Workbooks.Add(Type.Missing);
Excel.WorkSheet WS = WB.Sheets[1] as Excel.WorkSheet;
object obj = (WS.get_Range("A1:D10") as Excel.Range).get_Value(Excel.XLRangeValueDataType.XLRangeValueMSPersistXML);
(WS.get_Range("A1:D10") as Excel.Range).set_Value(Excel.XLRangeValueDataType.XLRangeValueMSPersistXML,obj);
The code fails here.
I am setting the same object value which i am getting from excel range.
The exception shown is System.NotImplementedException.
I am clueless at this point if it is the office interop doesn't support XLRangeValueMSPersistXML while setting the value back to the excel range.
When setting the value, it appears that you should leave off the RangeValueDataType setting. The following code does not cause the NotImplementedException to be thrown. (It also corrects some case problems that prevent your original sample from compiling, as well as tidying it up a bit.)
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp = new Excel.ApplicationClass();
Excel.Workbook WB = xlApp.Workbooks.Add(Type.Missing);
Excel.Worksheet WS = WB.Sheets[1] as Excel.Worksheet;
Excel.Range r = WS.Range["A1:D10"];
var obj = r.Value[Excel.XlRangeValueDataType.xlRangeValueMSPersistXML];
r.Value = obj;

Categories

Resources