Quantcast
Channel: Visual Studio Tools for Office (VSTO) forum
Viewing all 5157 articles
Browse latest View live

VSTO COM Exception 0x800A03EC

$
0
0

Hi,

i´m writing a VSTO Plug-In and i get this exception.

System.Runtime.InteropServices.COMException(0x800A03EC); 

SpecialCells method of Range class failed

 at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target,Int32[] aWrapperTypes, MessageData& msgData)

at Microsoft.Office.Interop.Excel.Range.SpecialCells(xLCellType Type,Object Value)

The Exception is coming after a while using Excel. You can also see that the Exception is comming from the SpecialCells Method.

I call this Function to get the last written Cell Row and Collum of the Sheet to read the data on the Sheet export it into a TXT-File. The problem is that the Export-Function is running without Problems but if you use the Excel-Applikation for a time and press export Sheet(my Addin Function) this exception will thrown.

Does anyone have a solution for this.

Best regards


Assistance with reading a drop down in excel using c#

$
0
0

I am writing a program in C# that reads and randomly populates an excel spreadsheet with various types of cells including drop-downs (the workbooks are all different and I never know where they are going to put the drop down. I don't really care what data is in the drop-down I just need to select an item from the list and populate the cell). I am using Microsoft.Office.Interop.Excel and have functionality working for the most part but am struggling on how to locate the drop downs and then populate with the default or any value in the drop-down list.  My code is as follows. (be kind I am still new to c# :-))

Thank you in advance for any assistance you can provide.

private void button1_Click(object sender, EventArgs e)
        {
            
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            Excel.Range range;
            Excel.DropDowns xlDropDowns;
            Excel.DropDown xlDropDown;

            string path = @"folder path foes here"; //will need to use path once folders are set up permanently
            string outputPath = @"folder path goes here"
            string fn = "";
            string str;

            Random random = new Random(100);
            int rand = random.Next(100, 5000);

            DirectoryInfo dI = new DirectoryInfo(@"path goes here");//will need to use path once folders are set up permanently
            FileInfo[] fileName = dI.GetFiles("*.xls*");

            foreach (FileInfo file in fileName)
            {
                fn = file.Name;
                //Console.WriteLine("GetFilename = " + fn);
            }

            xlApp = new Excel.Application();
            completedLabel.Text = "working";
            xlWorkBook = xlApp.Workbooks.Open(@"path goes here" + fn, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); // this is getting 1 - how to get more?

            int rCnt;
            int cCnt;
            int wsCount = xlWorkBook.Worksheets.Count;
            Console.WriteLine("# ws: " + wsCount);

            range = xlWorkBook.ActiveSheet.UsedRange; // this is to find the 'range' of used cells in the worksheet
            xlDropDowns = ((Excel.DropDowns)(xlWorkBook.ActiveSheet.DropDowns(Type.Missing)));

             <g class="gr_ gr_736 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="736" id="736">foreach</g> (Excel<g class="gr_ gr_738 gr-alert gr_gramm gr_inline_cards gr_run_anim Style replaceWithoutSep" data-gr-id="738" id="738">.Worksheet</g> <g class="gr_ gr_737 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" data-gr-id="737" id="737">xlworksheet</g> in xlWorkBook.Worksheets)
            {

            int cellCnt = 0;
            int rw = 0;
            int cl = 0;
            rw = range.Rows.Count;
            cl = range.Columns.Count; 

            for (rCnt = 1; rCnt <= rw; rCnt++) // loop through row
            {
                for (cCnt = 1; cCnt <= cl; cCnt++) //loop though column
                {
                    // **** TODO **********************************
                    //if (is a dropdownlist cell) //if (default exists) // use default //else //use list<1>
                    //***********************************************

                    str = Convert.ToString((range.Cells[rCnt, cCnt] as Excel.Range).Value2);
                    
                    if (range.Cells[rCnt, cCnt].Locked == false && string.IsNullOrEmpty(str) && !range.Cells[rCnt, cCnt].HasFormula)
                    //True if the object is locked; False if the object can be modified when the sheet is protected. Returns Null if the specified range contains both locked and unlocked cells.
                    {
                        range.Cells[rCnt, cCnt] = rand.ToString();
                        rand++;
                        cellCnt++;
                    }
                }
                rowCountLabel.Text = "Row Count is : " + rCnt;
                colCountLabel.Text = "Column Count is : " + cCnt;
                cellCountLabel.Text = "Unlocked Cell Count is : " + cellCnt;  // add in a cell count
            }
            completedLabel.Text = "completed";
            xlWorkBook.SaveAs(outputPath + fn); // Save workbook to output file
            xlWorkBook.Close(true, null, null);
            xlApp.Quit();

            Marshal.ReleaseComObject(xlWorkSheet);
            Marshal.ReleaseComObject(xlWorkBook);
            Marshal.ReleaseComObject(xlApp);
        }
        private void closeButton_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Application.Exit();
        }
    }

How to avoid the Windows Defender SmartScreen prevented an unrecognized app from starting warning

$
0
0

Hi there,

I have code signed my outlook application setup .exe using the GoDaddy code signing certificate. But when the application is downloaded from the internet, I get this message.

 

Windows protected your PC

Windows Defender SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk.

What could be the problem?

Thanks


Error while installing extension (specflow) in Visual studio 2017: Element not found. (Exception from HRESULT: 0x80070490)

$
0
0

Below is the log details for error.

8/17/2018 9:50:15 AM - System.Runtime.InteropServices.COMException (0x80070490): Element not found. (Exception from HRESULT: 0x80070490)
   at Microsoft.VisualStudio.Setup.Configuration.ISetupConfiguration2.GetInstanceForPath(String path)
   at VSIXInstaller.LocationBasedSKU..ctor(String appidInstallPath, String appidName, Version vsVersion, String edition, String rootSuffix)
   at VSIXInstaller.LocationBasedSKU..ctor(String appidInstallPath, String appidName, Version vsVersion, String edition, String rootSuffix, IntPtr alternateUserToken)
   at VSIXInstaller.ExtensionService.GetInstallableData(String vsixPath, String extensionPackParentName, Boolean isRepairSupported, IStateData stateData, IEnumerable`1& skuData)
   at VSIXInstaller.App.Initialize(Boolean isRepairSupported)
   at VSIXInstaller.App.Initialize()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()

Can you please help in resolving the issue?

Powerpoint 2016 Automation when logged into Office 365 VSTO OneDrive

$
0
0

I'm having trouble generating thumbnails in PowerPoint 2016 with VSTO. I'm using the following code to loop through a folder of pptx files and export the first slide to jpg:

Public Function FolderExists(strFolder As String) As Boolean
    FolderExists = IO.Directory.Exists(strFolder)
End Function

Public Sub CreateDirectoryIfNotExists(ByVal NewDirectory As String)
    Try
        ' Checking the existence of directory
        If Not FolderExists(NewDirectory) Then
            'If No any such directory then creates the new one
            IO.Directory.CreateDirectory(NewDirectory)
        Else
        End If
    Catch ex As IOException
    End Try
End Sub

Public Function FolderDeleteIfExists(strPath As String) As Boolean
    Try
        If FolderExists(strPath) Then
            System.IO.Directory.Delete(strPath, True)
        End If
        Return True
    Catch ex As Exception
        Return False
    End Try
End Function

Sub ClearFolder(strDirectory As String)
    If Not FolderExists(strDirectory) Then
        Exit Sub
    End If
    Dim s As String
    For Each s In System.IO.Directory.GetFiles(strDirectory)
        System.IO.File.Delete(s)
    Next s
End Sub

Sub ThumbnailGenTest()

    Try
        Dim strPath As String = InputBox("Provide repository folder")
        If strPath = "" Then Return
        Dim dir As New IO.DirectoryInfo(strPath)
        Dim strPath_thumbnails As String = IO.Path.Combine(strPath, "Thumbnails")
        Dim diar1 As IO.FileInfo() = dir.GetFiles("*.pptx")

        ClearFolder(strPath_thumbnails)
        CreateDirectoryIfNotExists(strPath_thumbnails)
        Dim pres As PowerPoint.Presentation = Nothing
        Dim sld As PowerPoint.Slide = Nothing
        'list the names of all files in the specified directory
        For Each dra As IO.FileInfo In diar1
            pres = Globals.ThisAddIn.Application.Presentations.Open(dra.FullName, True, False, False)
            Dim strFileName As String = strPath_thumbnails & "\" & dra.Name.Replace(".pptx", ".jpg")
            sld = pres.Slides(1)
            sld.Export(strFileName, "jpg")

            If sld IsNot Nothing Then sld = Nothing

            If pres IsNot Nothing Then
                pres.Close()
                pres = Nothing
            End If
        Next

        MsgBox("Thumbnails rebuilt", vbInformation, "Test")
    Catch ex As Exception
        MsgBox("There was an error - " & ex.Message, vbInformation, "Error")
    End Try
End Sub

After processing anywhere from 100 to 1000 slides the code hangs on pres.Close() - no error, just hangs permanently.

I've discovered it only happens in 2013 or 2016 when I'm logged into Office 365 in PowerPoint - possibly it's connected to OneDrive.

I've tried several fixes:

  • System.Threading.Thread.Sleep
  • System.Windows.Forms.Application.DoEvents
  • WaitForPendingFinalizers
  • ReleaseComObject

I've tried disabling OneDrive using the registry or group policy. Nothing seems to help except logging off the account in PowerPoint or disconnecting the internet.

Has anyone got any ideas what might be causing it, potential fixes or ways of disabling temporarily Office 365/OneDrive.

Any ideas appreciated.

VSTO - Excel - How to call range.Validation.Delete() without raising an error?

$
0
0

When I press Alt + Down keys before calling range.Validation.Delete(), the Excel shows the following error:

An exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll but was not handled in user code

Additional information: Exception from HRESULT: 0x800AC472

If there is a handler for this exception, the program may be safely continued.

How can I prevent this error in an asynchronous method?

Any help would be appreciated.

Multiple Action Panes on different Worksheets

$
0
0

Hi,

I like to create a projekt where on everey Worksheet a different Action Pane shows up. (e.g. for Navigation in a Workbook or task like printing etc.)

How can I do that?

I tried to hide the actionpanes in the sheet active Call but it didn't work. I only can show both actionpanes or none.

Or is there an other way to handle such problems ?

thanks a lot

How to install the Office Developer tools in VS 2015?

$
0
0

I'm trying to install the Office Developer Tools, but I'm constantly getting this issue:

I have access only to Visual Studio 2015 not 2017. Thanks for your support.


Federico Navarrete


VSTO Outlook 2016 addin gets disappeared from the add-ins tab

$
0
0

My addin is developed in VS 2015, and I have created the installer with installshield.

I create a registry key in "HKLM\Software (64 bit)\Microsoft\Office\ClickToRun\Registry\Machine\Software\Wow6432node\Microsoft\Office\Outlook\Addins\my_vsto_addin\" with below keys:

Description, FriendlyName, LoadBehavior, Manifest.

I have also signed the addin with a code signing certificate issued by "DigiCert SHA2 Assured ID Code Signing CA".

The problem is, whenever office 2016 gets updated, the addin no longer appears in the Outlook Options\Add-ins tab. But, the binary files are still available in the installation folder. Until the office update, the addin works fine.

Any ideas how to prevent this?

The ad-ins tab also does not show the Publisher name of the addin though I have set this up in the publish\Options tab of the addin project. Note: I don't publish the addin from this tab. Instead I create the setup file using installshield. I looked at the vsto file, and it contains a different publisher name (looks like its my product name) in the <description> node.

Any help will be highly appreciated.



VSTO | Word | Range compare

$
0
0

Hi,

I'm trying to work out if two ranges in Word intersect. I'm just interested in whether they intersect or not, I don't need to know how they intersect. I originally thought this would be easy, all I need to do is compare the start and end values and in a simple text document his is sufficient. The problem I have is with text boxes. If I start with a new document and add "Hello, World" on the first line, then add a text box containing "Hello, World", then compare the range start / end values for both "Hello, World",s you end up with the same numbers.

Is it possible to differentiate the two ranges? How does the range in the text box know it's within a text box?

Many thanks for any pointers that can be provided.

Martin

.Net Console App Getting an error running

$
0
0
An unhandled win32 exception occurred in ConsoleApp.exe 

AccessViolationException exception while setting status bar in vsto excel add-in

$
0
0

Hi,

We have a vsto add-in which utilizes status bar to show progress message to user. Following is the code which sets the value for status bar

public void SetStatusBarMessage(string message, bool isComplete)
{
    try
    {
        if (isComplete)
        {
            Globals.ThisAddIn.Application.StatusBar = false;
        }
        else
        {
            Globals.ThisAddIn.Application.StatusBar = message;
        }
    }
    catch (Exception ex)
    {
        LogDebugInfo("Updating status bar failed."+ex.Message);
    }
}

Using the above method, We are setting the value of status bar right before start of an action and once the action is completed, we use the same method to reset the StatusBar.

One of the users reported that his excel crashed while using our add-in and when we checked for event viewer logs, we saw System.AccessViolationExceptionthrown at Microsoft.Office.Interop.Excel._Application.set_StatusBar(System.Object)followed by stack trace leading to above given method. Also, LogDebugInfo is a method which we use to log to a file, but this log file did not contain any details on error even though it is handled in the code!

Exact Message:

Application: EXCEL.EXE Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.AccessViolationException at Microsoft.Office.Interop.Excel._Application.set_StatusBar(System.Object).

Same thing works fine when we try it in our local environment.

Has anyone faced this issue? 

Any help would be greatly appreciated.


Creating a Map Chart in PowerPoint

$
0
0

I'm trying to add a map chart in PowerPoint.

As of now I can't see the option to do so in XlChartType, but if I insert one manually I can then examine the inserted chart and see, that its XlChartType evaluates to 140.

If I try to insert a chart with this type I get a map as expected. However, if I try to access its workbook it throws an exception. These two lines of code should explain what I'm doing:

var chart = _slide.Shapes.AddChart((XlChartType)140).Chart;
var workbook = (Workbook)chart.ChartData.Workbook;

I assume this is related to the fact that it's not officially supported. Is there any way to work around this problem and edit the data of the chart?

VSTO AddIn is not a valid add in

$
0
0

I implemented a VSTO Word Add In in Visual Studio 2015 for Office 2016, which contains 1 ThisAddIn.vb class and about 15 VB classes (1 Ribbon, Forms and Standard classes).

If I build and start (debug) my AddIn from Visual Studio, Word 2016 opens up and the AddIn is installed properly, everything words fine.

Now, I implemented a Setup Project, which installs Registry Key, Launch Conditions, etc.

I am able to install the corresponding msi file (on the same machine) and the registry key (HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\Word\Addins\<company>.<addinname>) is visible afterwards.

Now:

1) When I start up Word, the Add in does not load.
2) When I try to add the dll file in manually via File -> Options -> Add Ins -> COM Add In -> Add, it says that the dll file is not a valid add in. (Same is with the vsto manifest file)

(the Manifest value in the registry key points to the vsto file)

My question is now why. And I know this is a very general question, maybe someone can tell what further information is needed to answer it. (I am quite new to visual studio and add ins.)

Thanks in advance.

How to copy an Excel Worksheet from one workbook to another workbook with the associated C# code intact

$
0
0

I am trying to use a Worksheet template from a master Workbook by copying the Worksheet template into a new Workbook. I have provided code for several document level events within the Worksheet template (sheet1.cs) that need to follow the Worksheet when it is copied into the new Workbook. The code to copy the template Worksheet into the new Workbook is fully functional, but when the Worksheet is opened in the new Workbook, the events do not work (they are fully functional in the master Workbook).

I am using Visual Studio 2017 Professional and Excel 2016.

Is there a way to get the C# code (sheet1.cs code) to follow the Worksheet to the new Workbook?


Webbrowser control inside custom taskpane not showing loaded webpage

$
0
0

Hi,

I have created Outlook Add-in which, used custom pane to log in user into Salesforce.

In custom taskpane,User control was added which has webbrowser control.

Now from last few days,the custom taks pane is loaded but no login webpage is shown.I have also tried with other URLs.

Was there any update which has happened recently,which may be causing the issue.

Here is the link to the addin video:https://www.facebook.com/Point5Nyble/videos/2080581445493387/

private void MailTangy_Load(object sender, RibbonUIEventArgs e)
        {
            myCredentials=myCredentials.deserializeCredentials();
            //check if credentials have not expired.
            if (HasLoginExpired().Result==true)
            {
                Globals.ThisAddIn.myCredentials = null;
                if (loginPane == null)
                {
                    loginPane = new LoginCustomPane();
                    taskPaneValue = Globals.ThisAddIn.CustomTaskPanes.Add(
                        loginPane, "Login | Salesforce");
                    taskPaneValue.DockPosition = MsoCTPDockPosition.msoCTPDockPositionFloating;
                    taskPaneValue.DockPositionRestrict = MsoCTPDockPositionRestrict.msoCTPDockPositionRestrictNoChange;
                    //Move Login Window to Center

                    //End
                    taskPaneValue.Height = 575;
                    taskPaneValue.Width = 540;
                    taskPaneValue.Visible = true;
                    taskPaneValue.VisibleChanged += TaskPaneValue_VisibleChanged;
                }
            }
UserControl which was added:
 public partial class LoginCustomPane : UserControl
    {
        Credentials myCredentials = new Credentials();
        string redirectURL = Properties.Settings.Default.RedirectURL;
        public LoginCustomPane()
        {
            InitializeComponent();
            string url = "https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=" +"3MVG9d8..jksdakdaHadaDoPDosVQgzlKdbddzLx48u68paKUn8o_UK2ZcZBFu9aQ7_DFPz&redirect_uri=" + redirectURL;
            //string url = "http://www.google.com";
            webBrowserLogin.Navigate(url);           
            webBrowserLogin.TabIndex = 0;
            webBrowserLogin.TabStop = true;
            webBrowserLogin.NewWindow += new CancelEventHandler(wb_newWindow);
            webBrowserLogin.Visible = true;         
        }


Point5Nyble

Send a byte array from VBA to a WCFService

$
0
0

Hey guys,

I need some help with a problem.

So, I have a very basic WCF Service application which has method that gets a byte array as input and returns a bool. The byte array consists in the content of a document and is generated in VBA. What I try to do is to conect myself from VBA to the WCFService and pass the byte array and get the result back in the vba project. Problem is that I'm not sure how to do that. Here is what I tried:

Public Function GetServiceData() As XMLHTTP Dim httpData As New XMLHTTP Dim webServiceURL As String webServiceURL = ipAddress & port & "/TestService/SaveAndAttach" httpData.Open "POST", webServiceURL, False httpData.setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8" httpData.send Example Set GetServiceData = httpData End Function End Function

Public Function GetFileBytes(ByVal path As String) As Byte()
    Dim lngFileNum As Long
    Dim bytRtnVal() As Byte
    lngFileNum = FreeFile
    If LenB(Dir(path)) Then ''// Does file exist?
        Open path For Binary Access Read As lngFileNum
        ReDim bytRtnVal(LOF(lngFileNum) - 1&) As Byte
        Get lngFileNum, , bytRtnVal
        Close lngFileNum
    Else
        Err.Raise 53
    End If
    GetFileBytes = bytRtnVal
    Erase bytRtnVal
End Function

Public Function Example() As Byte()
    Dim byteFile() As Byte
    byteFile = GetFileBytes("C:\Desktop\FilesForTesting\TestDocument13_2.docx")
    Example = byteFile
End Function

I added a break point in the service and from what I know when you send data to it should trigger.

Is there any extra settings I should do in the WCF Service project? 

Is the VBA code wrong? (I haven't worked too much in VBA so might be a stupid mistake I did).

Thank you very much for the time.


Extract entity strings from an Outlook item using VSTO (Outlook client not O365 based Office Add-ins)

$
0
0

Hello,

With web based Office add-ins, outlook provides APIs to extract entity strings (Address, contacts, email address etc.) from an Outlook item subject, body fields.

Please refer below articles. https://docs.microsoft.com/en-us/outlook/add-ins/extract-entity-strings-from-an-item

https://docs.microsoft.com/en-us/outlook/add-ins/match-strings-in-an-item-as-well-known-entities

Is there any similar thing available for COM based outlook plugins (VSTO) ? If not in built with Outlook API then any Microsoft service which we can use to pass text and get such results can also help.

Thanks,

Manoj


ManojPatel

Problem with Word Addin not starting/loading

$
0
0

Hi

We have a package of Office Addins for Word, Excel, Powerpoint and Outlook, all for Microsoft Office 2010.
A couple of clients out of +500 has been getting problems starting/loading the AddIn for Word.
The AddIns for Excel, Powerpoint and Outlook all works.

In our investigation we have tried reinstall Office and also our package, but without success.
The Addins are all registered in the Local_Machine-part of the registry.
When we look in the registry HKLM we can see that the Addin has Loadbehavior 3 as it should.
All files from the package are in place and nothing seems to be missing.

When we start Word we can se that an attempt is made to start the AddIn, but when the UI is shown, our menu is missing.
We look in the Word configuration - Addins, and our AddIn is amongs the inactivated ones.

We open the dialog for COM-Addins and when we try to fill in the checkbox, information is shown in the dialog that the AddIn is not lodaed and the reason is a runtime error.
We can see that no code in our Addin is executed because no entries in our logfile is found.

What we also has discovered is that when we try to activate the AddIn in Word UI, a new registry key is created in the Current_User-part of the registry with a singel value for Loadbehavior set to 2.

I'm beginning to feel there is some lost registry-value set the interferes with the Addin or that some files are missing.

Where should I begin to look for the cause of all this?

Thanks


Best Regards Peter Karlström Midrange AB, Sweden

outlook/word/excel/powerpoint addin fails to load at startup of app due to the loadbehavior getting changed from 3 to 0

$
0
0

Opening the Com Addins setup you wills see that the addin is inactive. If you make the addin active, it will fuction until you close and reopen the application. Once the app is reopened, the addin will be inactive again.

What we find "fixes" it for a short time normally, is to search the regsitry for the name of the addin and you will find another location in the registry with a Key called LoadBehavior that is set to a value of 0. This value means to no load at startup of the application. The key will also exist in the normal location with a value of 3. It can be seen up to three different locations in the registry that have loadbehavior keys for the same addin.

This is not a key that is getting created by my application nor can we keep MS from creating the other keys. This seems due to some office updates which i am not sure. 

Can someone figure out what is happening? 

Thanks in advance


Viewing all 5157 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>