Posts Tagged Object

Email Excel Spreadsheet as Email Body Issues

Hello all. I had a production manager wanting an excel spreadsheet mailed as the body of the email. As some of you know the code generated by excel to produce the email is pretty crazy. But as a result, it showed up fine in Outlook and Android but it did not show the gridlines on the spreadsheet. So this code is based on the excellent work by Ron DeBruin over at http://www.rondebruin.nl/win/s1/outlook/bmail3.htm . I did a replacement for the HTML Range in this manner and the grid lines did appear. And the manager was happy.

Sub Mail_Selection_Range_Outlook_Body()
‘For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
‘Don’t forget to copy the function RangetoHTML in the module.
‘Working in Excel 2000-2016
    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object
‘MsgBox Cells(5, 9).Value
    Set rng = Nothing
    On Error Resume Next
    ‘Only the visible cells in the selection
    Set rng = Selection.SpecialCells(xlCellTypeVisible)
    ‘You can also use a fixed range if you want
    ‘Set rng = Sheets(“YourSheet”).Range(“D4:D12”).SpecialCells(xlCellTypeVisible)
    On Error GoTo 0

    If rng Is Nothing Then
        MsgBox “The selection is not a range or the sheet is protected” & _
               vbNewLine & “please correct and try again.”, vbOKOnly
        Exit Sub
    End If

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set OutApp = CreateObject(“Outlook.Application”)
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .BodyFormat = olFormatHTML
        .To = “you@you.com”       
           
               
       
         .CC = “”
        .BCC = “”
        .Subject = “Testing Purchase Order Email To Steve”
        .HTMLBody = RangetoHTML(rng)
        Replace .HTMLBody, “border-left:none”, “border-left:solid;border-width: 1px;border-color:black”
        Replace .HTMLBody, “border-right:none”, “border-right:solid;border-width: 1px;border-color:black”
        Replace .HTMLBody, “border-bottom:none”, “border-bottom:solid;border-width: 1px;border-color:black”
        Replace .HTMLBody, “border-top:none”, “border-bottom:solid;border-width: 1px;border-color:black”
        .Send
         ‘or use .Display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a comment

Write DataTable to an MS Word Table Efficiently with C# using a Dynamic Type

This is a C# adaptation of the code I wrote to write a datatable to a Microsoft Word document table for vb.net . But that doesn’t really begin to tell the story here. In vb.net we have been accustomed to being allowed to leave parameters empty when automating the creation of a table in Microsoft Word. C# has not permitted me that luxury which to be honest is probably a better code practice. So prepare to meet the Type.Missing object! In addition the default item that we learned to love/hate in Visual Basic for Applications (VBA) code years ago also is not used in C#. Finally in declaring the range object for the table it became an opportunity to use the new dynamic reference type keyword, which was designed for such situations. Check out this video on the subject which is quite excellent.

http://channel9.msdn.com/Shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/player?w=512&h=288

For these reasons you will see key differences between the two sets of code. Don’t forget to import Microsoft Word as a COM reference and do your import statements. As always feel free to comment or email. Have a great day!

using Office = Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;

public void CreateWordTableWithDataTable(DataTable dt)
        {
            int RowCount = dt.Rows.Count; int ColumnCount = dt.Columns.Count;
            Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];
            //int RowCount = 0; int ColumnCount = 0;
            int r = 0;
            for (int c = 0; c <= ColumnCount – 1; c++)
            {
                DataArray[r, c] = dt.Columns[c].ColumnName;
                for (r = 0; r <= RowCount – 1; r++)
                {
                    DataArray[r, c] = dt.Rows[r][c];
                } //end row loop
            } //end column loop

            Word.Document oDoc = new Word.Document();
            oDoc.Application.Visible = true;
            oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
           
            dynamic oRange = oDoc.Content.Application.Selection.Range;
            String oTemp = “”;
            for (r = 0; r <= RowCount – 1; r++)
            {
                for (int c = 0; c <= ColumnCount – 1; c++)
                {
                    oTemp = oTemp + DataArray[r, c] + “\t”;
                  
                }
            }

oRange.Text = oTemp;
           
object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs;
object Format = Word.WdTableFormat.wdTableFormatWeb1;
object ApplyBorders = true;
object AutoFit = true;

object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;
            oRange.ConvertToTable(ref Separator,
        ref RowCount, ref ColumnCount, Type.Missing, ref Format,
        ref ApplyBorders, Type.Missing, Type.Missing, Type.Missing,
         Type.Missing, Type.Missing, Type.Missing,
         Type.Missing, ref AutoFit, ref AutoFitBehavior,
         Type.Missing);
           
            oRange.Select();
            oDoc.Application.Selection.Tables[1].Select();
            oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
            oDoc.Application.Selection.Tables[1].Rows.Alignment = 0;
            oDoc.Application.Selection.Tables[1].Rows[1].Select();
            oDoc.Application.Selection.InsertRowsAbove(1);
            oDoc.Application.Selection.Tables[1].Rows[1].Select();

            //gotta do the header row manually
            for (int c = 0; c <= ColumnCount – 1; c++)
            {
               oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = dt.Columns[c].ColumnName;
            }

            oDoc.Application.Selection.Tables[1].Rows[1].Select();
            oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                      
                    }

Facebook

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a comment

Create a Share on Remote Machine using WMI with vb.net

This code was used to create a share on a remote machine a while back for the purpose of automating a function that had previously required a network guy at the company to actually touch the machine which of course they didn’t like to do (it required work on their part). But it was ok. I didn’t mind as it wasn’t that hard. WMI makes it easy to do.

I have been involved with a series of technical discussions with some folks at various companies lately. My most embarrassing moment yesterday was when I stumbled on my words when asked about polymorphism. I actually used the words “parallel universe” in conjunction with this! Can you imagine? I got to think better on my feet. But its all good. Have a great day!

Public Sub CreateShare(ByVal strShareName As String, ByVal strPath As String, ByVal computername As String, ByVal shareinfo As String)
        Try
            Dim objSWbemServices As Object
            Dim objSWbemObject As Object
            Dim colSWbemObject As Object
            Dim intRet As Integer
            Dim blnExists As Boolean
            Dim objSWbem As Object

            objSWbemServices = GetObject(“winmgmts://” + computername + “/root/cimv2”)

            colSWbemObject = objSWbemServices.InstancesOf(“Win32_Share”)

            For Each objSWbem In colSWbemObject
                If (objSWbem.name = strShareName) Then
                    blnExists = True
                    Exit For
                Else
                    blnExists = False
                End If
            Next

            If (blnExists = False) Then
                objSWbemObject = objSWbemServices.Get(“Win32_Share”)
                intRet = objSWbemObject.Create(strPath, strShareName, 0, 25, shareinfo)
                System.Console.WriteLine(“Share has been created on : ” + computername)
                System.Console.WriteLine(“ShareName : ” + ShareName + ”   SharePath : ” + SharePath + ”   ShareInfo : ” + shareinfo)
            Else
                System.Console.WriteLine(“Share is already present on computer : ” + computername)
                System.Console.WriteLine(“ShareName : ” + ShareName + ”   SharePath : ” + SharePath + ”   ShareInfo : ” + shareinfo)
            End If
        Catch ex As Exception
            System.Console.Write(“Error occured while trying to create shares on remote pc : ” + computername + vbCrLf + “Check if you have the necessary rights and/or that the pc is turned on.” + vbCrLf + ex.ToString)
            System.Console.WriteLine(“ShareName : ” + ShareName + ”   SharePath : ” + SharePath + ”   ShareInfo : ” + shareinfo)
        End Try

    End Sub

My Facebook Page

, , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a comment