Wednesday, 5 June 2013

Code related to Excel Macros

Code related to Excel Macros

Code related to Excel Macros:
In this article I am trying to explore some important code related to VB macros which can help you to write robust VB macro based excel project.
For all code I am using the “Test.xls” excel file which have two work sheets:
<!--[if !supportLists]-->1. Inventory<!--[endif]-->
<!--[if !supportLists]-->2. Payroll<!--[endif]-->
Add the following reference to project:
<!--[if !supportLists]-->1. Microsoft Excel 12.0 Object Library<!--[endif]-->
<!--[if !supportLists]-->2. MicrosoftOffice 12.0 Object Library<!--[endif]-->
<!--[if !supportLists]-->3. Microsoft Forms 2.0 Object Library<!--[endif]-->
<!--[if !supportLists]-->4. Microsoft Scripting Runtime<!--[endif]-->
<!--[if !supportLists]-->i. If you want to find total numbers of used rows and columns in the work sheet Payroll:<!--[endif]-->
Dim wsheet_Payroll As Excel.Worksheet
Dim USEDROW_Payroll As Long
Dim USEDCOL_Payroll As Long
‘Create connection to Payroll worksheet
Set wsheet_Payroll = Worksheets("Payroll")
‘Activate the Payroll shett
wsheet_Payroll.Activate
‘Find total number of Used Row in the Payroll sheet
USEDROW_Payroll = wsheet_Payroll.UsedRange.Rows.Count
‘Find total number of Used Row in the Payroll sheet
USEDCOL_Payroll = wsheet_Payroll.UsedRange.Columns.Count
<!--[if !supportLists]-->ii. If you want to find first occurrence some text(for example: Deducted) and want to delete that column in which text found in the work sheet Payroll:<!--[endif]-->
Dim wsheet_Payroll As Excel.Worksheet
Dim USEDROW_Payroll As Long
Dim USEDCOL_Payroll As Long
Dim Driverrange_Payroll As Range
Dim oTemp As Range
Dim ROWSTART_Payroll As Long
Dim COLSTART_Payroll As Long
‘Create connection to Payroll worksheet
Set wsheet_Payroll = Worksheets("Payroll")
‘Activate the Payroll shett
wsheet_Payroll.Activate
‘Find total number of Used Row in the Payroll sheet
USEDROW_Payroll = wsheet_Payroll.UsedRange.Rows.Count
‘Find total number of Used Row in the Payroll sheet
USEDCOL_Payroll = wsheet_Payroll.UsedRange.Columns.Count
‘Define the range in which you need to search the text
Set Driverrange_Payroll = wsheet_Payroll.Range("a1:HV" & USEDROW_Payroll)
'---------Find Deducted in Payroll Sheet------------
Set oTemp = Driverrange_Payroll.Find("Deducted")
If Not oTemp Is Nothing Then
‘If Deducted exist in the Payroll sheet
‘----Store row number------
ROWSTART_Payroll = oTemp.Row
‘----Store column number------
COLSTART_Payroll = oTemp.Column
'----Delete column --------
wsheet_Payroll.Columns(COLSTART_Payroll).Delete
'------------------------------------
Set oTemp = Nothing
End If
<!--[if !supportLists]-->iii. If you want to find first occurrence some text(for example: EmplidSearch) and want to insert new column with value after that column in which text found in the work sheet Payroll:<!--[endif]-->
Dim wsheet_Payroll As Excel.Worksheet
Dim USEDROW_Payroll As Long
Dim USEDCOL_Payroll As Long
Dim Driverrange_Payroll As Range
Dim oTemp As Range
Dim ROWSTART_Payroll As Long
Dim COLSTART_Payroll As Long
‘Create connection to Payroll worksheet
Set wsheet_Payroll = Worksheets("Payroll")
‘Activate the Payroll shett
wsheet_Payroll.Activate
‘Find total number of Used Row in the Payroll sheet
USEDROW_Payroll = wsheet_Payroll.UsedRange.Rows.Count
‘Find total number of Used Row in the Payroll sheet
USEDCOL_Payroll = wsheet_Payroll.UsedRange.Columns.Count
‘Define the range in which you need to search the text
Set Driverrange_Payroll = wsheet_Payroll.Range("a1:HV" & USEDROW_Payroll)
'---------Find Deducted in Payroll Sheet------------
Set oTemp = Driverrange_Payroll.Find("EmplidSearch")
If Not oTemp Is Nothing Then
‘If Deducted exist in the Payroll sheet
‘----Store row number------
ROWSTART_Payroll = oTemp.Row
‘----Store column number------
COLSTART_Payroll = oTemp.Column
'----Insert column after empid--------
wsheet_Payroll.Columns(COLSTART_Payroll).Offset(, 1).Insert
'------------------------------------
'----------Enter value =Deducted in all columns---------
wsheet_Payroll.UsedRange.Columns(COLSTART_Payroll + 1).Value = "Deducted"
'------------------------------------
Set oTemp = Nothing
End If

Add/Update/Delete operations on the Sharepoint List Item using C#(C-Sharp)

Add/Update/Delete operations on the Sharepoint List Item using C#(C-Sharp)

Add/Update/Delete operations on the Sharepoint List Item using C#(C-Sharp):
The list present in the SharePoint serves as a table which we used in the relational database. Its means in SharePoint we used list for storing user data instead of table used in RDB. These lists contain data which are required by the user for doing some computational operation or for other functionality. Here I am taking the scenario of the User List for storing user details. This list contain the details of user i.e. first name , last name and email id. With the help of this list I will explain you, how you can add/update/delete items in the list with the help of C#(C-Sharp).
First add the reference to Microsoft.SharePoint. After that create the object of SPSite:

SPSite oSiteCollection = new SPSite();
<!--[if !supportLists]-->
  • siteName should be the url of your sharepoint site.
<!--[endif]-->
Now create the object of SPWeb with the help of SPSite object:
SPWeb oWebsiteRoot = oSiteCollection.OpenWeb();
oWebsiteRoot.AllowUnsafeUpdates = true;
After that create the connection to the User List and create object of SPListItemCollection :
SPList oList = oWebsiteRoot.Lists["User"];
SPListItemCollection listItemCOll;
<!--[if !supportLists]-->
  • If you want to add the item in the User List then use following steps:
<!--[endif]-->
SPListItem oListItem = oList.Items.Add();
oListItem["FIRST_NAME"] = “Amit”;
oListItem["LAST_NAME"] = “Kumar”;
oListItem["EMAIL_ADDR"] = “mcapassion@gmail.com”;
oListItem.Update();
After that new item(row) would be added in the User List.
<!--[if !supportLists]-->
  • If you want to update the item in the User List whose EMPLID is “101” then use following steps:
<!--[endif]-->
Create the object of SPQuery:
SPQuery query = new SPQuery();
//Create query for fetching record which are having EMPLID=101
//Fetch item from the User List by passing query to the User List
listItemCOll = oList.GetItems(query);
if (listItemCOll.Count > 0)
{
//If record found in the list

{
//Take the reference of that item
SPListItem listItem = listItemCOll[icount];
listItem["FIRST_NAME"] = “A”;
listItem["LAST_NAME"] = “Kumar”;
listItem["EMAIL_ADDR"] = “mcapassion@gmail.com”;
//Update the Item
listItem.Update();
}
}
<!--[if !supportLists]-->
  • If you want to delete the item in the User List whose EMPLID is “101” then use following steps:
<!--[endif]-->
Create the object of SPQuery:
SPQuery query = new SPQuery();
//Create query for fetching record which are having EMPLID=101


//Check items exist in the User List or not
if (oList.Items.Count > 0)
{
//Fetch item from the User List by passing query to the User List
listItemCOll = oList.GetItems(query);
if (listItemCOll.Count > 0)
{
//If record found in the list
listItemCOll [0].Delete();
}
}
The above mentioned steps help you to create Custom Web parts/User controls in SharePoint for

Get UserProfile Object of Logged-in User

Get UserProfile Object of Logged-in User

In this article, I will explain how to get UserProfile object for Logged-in User (current user).
  1. //Function Call   
  2. UserProfile objUserProfile= GetProfileOfCurrentUser(SPContext.Current.Web.CurrentUser.LoginName)   
  3. public UserProfile GetProfileOfCurrentUser(string accountName)   
  •         {   
  •             UserProfile profile = null;   
  •             try  
  •             {   
  •                 if (string.IsNullOrEmpty(accountName))   
  •                 {   
  •                     return null;   
  •                 }   
  •                 SPSecurity.RunWithElevatedPrivileges(delegate()   
  •                 {   
  •                     SPSite site = SPContext.Current.Site;   
  •                     ServerContext context = ServerContext.GetContext(site);   
  •   
  •                     UserProfileManager profileManager = new UserProfileManager(context);   
  •                     if (!profileManager.UserExists(accountName))   
  •                     {   
  •                         profile = null;   
  •                     }   
  •   
  •                     profile = profileManager.GetUserProfile(accountName);   
  •                 });   
  •             }   
  •             catch (Exception ex)   
  •             {   
  •                 profile = null;   
  •             }   
  •             return profile;   
  •         }  
  • Upload (Import) data from excel (spreadsheet) file to SharePoint list using c#

    Upload (Import) data from excel (spreadsheet) file to SharePoint list using c#

    Upload (Import) data from excel (spreadsheet) file to SharePoint list using c#:

    When we have data in excel format and want to import that data to a SharePoint list, then how to do. By default SharePoint will provide us an option to edit in spreadsheet or download list items in spread sheet. But, it doesn't have an option to import the excel data to SharePoint list. To resolve this problem, I have created web part.
    In this web part, I am using SharePoint list called “Employee”. The name of columns are Tile and LastName.
    With the help of this web part, user will enter the data in the excel and then give the path of the file in the input box present in the page. Now instead of uploading the whole excel file into a document library the code will read the file and update the list with the data present in the excel file.

    The web part code is:

    1. using System;  
    2. using System.Collections.Generic;  
  • using System.Text;  
  • using System.Web;  
  • using System.Data;  
  • using System.Xml;  
  • using System.Xml.Serialization;  
  • using System.ComponentModel;  
  • using System.Data.OleDb;  
  • using System.Web.UI.WebControls;  
  • using Microsoft.SharePoint;  
  • using Microsoft.SharePoint.WebPartPages;  
  • using Microsoft.SharePoint.WebControls;  
  •   
  •   
  •   
  •   
  • namespace Example1  
  • {  
  •     public class wp_ImportXLSFile : WebPart  
  •     {  
  •         #region Member Variables  
  •         System.Web.UI.WebControls.Button btnUpload;  
  •         FileUpload fleDoc;  
  •         #endregion  
  •  
  •         #region Properties  
  •         private const string _defaultList = "Employee";  
  •         private string _listName = "Employee";  
  •         [DefaultValue(_defaultList)]  
  •         [WebPartStorage(Storage.Personal)]  
  •         [XmlElement(ElementName = "List Name", IsNullable = false)]  
  •         public string InternalList  
  •         {  
  •             get { return this._listName; }  
  •             set { this._listName = value; }  
  •         }  
  •  
  •  
  •          #endregion  
  •  
  •         #region Render Controls and Handle Controls Event  
  •  
  •         #region Create Child Controls  
  •         protected override void CreateChildControls()  
  •         {  
  •   
  •             try  
  •             {  
  •                 Table tbl = new Table();  
  •                 TableRow tr = new TableRow();  
  •                 TableCell tc = new TableCell();  
  •   
  •                 tc.Text = "Select file:";  
  •                 tr.Cells.Add(tc);  
  •                 tc = new TableCell();  
  •                 //Create browse object  
  •                 fleDoc = new FileUpload();  
  •                 tc.Controls.Add(fleDoc);  
  •                 tr.Cells.Add(tc);  
  •                 tbl.Rows.Add(tr);  
  •   
  •   
  •                 tr = new TableRow();  
  •                 tc = new TableCell();  
  •                 tc.RowSpan = 2;  
  •                 tc.HorizontalAlign = HorizontalAlign.Center;  
  •                 //Create button  
  •                 btnUpload = new System.Web.UI.WebControls.Button();  
  •                 btnUpload.Text = "Upload File";  
  •                 btnUpload.Click += new EventHandler(btnUpload_Click);  
  •                 tc.Controls.Add(btnUpload);  
  •                 tr.Cells.Add(tc);  
  •                 tbl.Rows.Add(tr);  
  •                 this.Controls.Add(tbl);  
  •   
  •             }  
  •             catch (Exception ex)  
  •             {  
  •                 this.Page.Response.Write(ex.Message);  
  •             }  
  •         }  
  •  
  •         #endregion  
  •  
  •         #region Handle button click event  
  •         void btnUpload_Click(object sender, EventArgs e)  
  •         {  
  •             try  
  •             {  
  •                 if (fleDoc != null && fleDoc.PostedFile != null)  
  •                 {  
  •                     #region If File exist  
  •   
  •                     if (fleDoc.PostedFile.ContentLength > 0)  
  •                     {  
  •                         #region File size is greater than 0  
  •                           
  •                         string fileExt = System.IO.Path.GetExtension(fleDoc.FileName);  
  •                         if (string.Equals(fileExt, ".xls", StringComparison.InvariantCultureIgnoreCase) )  
  •                         {  
  •                             #region If not xls file  
  •                             string Path = fleDoc.PostedFile.FileName;  
  •                             string listname = "Sheet1";  
  •   
  •                             OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path + ";Extended Properties=Excel 8.0");  
  •                             //OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Path + ";Extended Properties=Excel 12.0 Xml;HDR=YES");  
  •                             //Provider=Microsoft.ACE.OLEDB.12.0;Data Source=;Extended Properties="Excel 12.0;HDR=YES";  
  •                             //Provider=Microsoft.ACE.OLEDB.12.0;Data Source=;Extended Properties="Excel 12.0 Xml;HDR=YES";  
  •                             con.Open();  
  •   
  •   
  •                             //Create Dataset and fill with imformation from the Excel Spreadsheet for easier reference  
  •                             DataSet myDataSet = new DataSet();  
  •                             OleDbCommand myCommand = new OleDbCommand(" SELECT * FROM [" + listname + "$]", con);  
  •                             System.Data.OleDb.OleDbDataAdapter da = new OleDbDataAdapter(myCommand);  
  •   
  •                             da.Fill(myDataSet);  
  •                             con.Close();  
  •   
  •                             if (myDataSet != null && myDataSet.Tables.Count > 0 && myDataSet.Tables[0].Rows.Count > 0 && !string.IsNullOrEmpty(this.InternalList))  
  •                             {  
  •                                 #region If record found  
  •   
  •                                 SPWeb web = SPContext.Current.Web;  
  •   
  •                                 SPSecurity.RunWithElevatedPrivileges(delegate  
  •                                                     {  
  •                                                         using (SPSite fullSite = new SPSite(web.Site.ID))  
  •                                                         {  
  •                                                             using (SPWeb fullWeb = fullSite.OpenWeb())  
  •                                                             {  
  •  
  •                                                                 #region Find list exist or not  
  •                                                                 if (chkListExist(fullWeb))  
  •                                                                 {  
  •                                                                     fullWeb.AllowUnsafeUpdates = true;  
  •                                                                     SPList oList = fullWeb.Lists[this.InternalList];  
  •  
  •                                                                     #region Travers through each row in the dataset  
  •                                                                     foreach (DataRow myDataRow in myDataSet.Tables[0].Rows)  
  •                                                                     {  
  •                                                                         #region Datarow Loop  
  •                                                                         Object[] cells = myDataRow.ItemArray;  
  •                                                                         string strFirstName = string.Empty;  
  •                                                                         string strLastName = string.Empty;  
  •                                                                         int cellCount = 1;  
  •                                                                         foreach (object cellContent in cells)  
  •                                                                         {  
  •                                                                             #region Cell Loop  
  •   
  •                                                                             string cellText = cellContent.ToString();  
  •                                                                             cellText = cellText.Replace("\n", "|");  
  •                                                                             //Read the string and put into Array of characters chars  
  •                                                                             if (cellCount == 1)  
  •                                                                             {  
  •                                                                                 strFirstName = cellText;  
  •                                                                                 cellCount++;  
  •                                                                             }  
  •                                                                             else if (cellCount == 2)  
  •                                                                             {  
  •                                                                                 strLastName = cellText;  
  •                                                                                 cellCount = 1;  
  •                                                                             }  
  •                                                                             this.Page.Response.Write("\n" + cellText);  
  •                                                                             #endregion  
  •                                                                         }  
  •                                                                         insertRecordInList(oList, strFirstName, strLastName);  
  •                                                                         #endregion  
  •                                                                     }  
  •                                                                     #endregion  
  •   
  •                                                                     fullWeb.AllowUnsafeUpdates = false;  
  •   
  •                                                                 }  
  •                                                                  
  •                                                                 #endregion  
  •   
  •                                                             }  
  •                                                         }  
  •                                                     });  
  •  
  •                                 #endregion  
  •                             }  
  •                             else  
  •                             {  
  •                                 #region If record not found  
  •                                 this.Page.Response.Write("No record found.");  
  •                                 #endregion  
  •                             }  
  •                             #endregion  
  •   
  •                         }  
  •                         else  
  •                         {  
  •                             #region If not xls file  
  •                             this.Page.Response.Write("Only .xls files allowed!");  
  •                             #endregion  
  •                         }  
  •  
  •  
  •  
  •                         #endregion  
  •                     }  
  •                     else  
  •                     {  
  •                         #region File size is 0  
  •                         this.Page.Response.Write("Uploaded file size is 0.");  
  •                         #endregion  
  •                     }  
  •  
  •  
  •                     #endregion  
  •                 }  
  •                 else  
  •                 {  
  •                     #region If File not exist  
  •                     this.Page.Response.Write("Uploaded file does not exist.");  
  •                     #endregion  
  •                 }  
  •             }  
  •             catch (Exception ex)  
  •             {  
  •                 throw ex;  
  •             }  
  •         }  
  •  
  •         #endregion  
  •  
  •         #endregion  
  •  
  •         #region Helper  
  •  
  •  
  •         #region Check list exist or not  
  •         private Boolean chkListExist(SPWeb web)  
  •         {  
  •             Boolean blnExist = false;  
  •             try  
  •             {  
  •                 #region Try  
  •                 if (!String.IsNullOrEmpty(this.InternalList) && this.InternalList.ToString().Trim().Length != 0)  
  •                 {  
  •                     try  
  •                     {  
  •                         if (web.Lists[this.InternalList] != null)  
  •                         {  
  •                             blnExist =  true;  
  •                         }  
  •                     }  
  •                     catch  
  •                     {  
  •                         #region If internal news list name is not valid  
  •                         blnExist = false;  
  •                         #endregion  
  •   
  •                     }  
  •   
  •                 }  
  •                 else  
  •                 {  
  •                     #region If internal news list name is empty  
  •                     blnExist = false;  
  •                     #endregion  
  •                 }  
  •  
  •                 #endregion  
  •   
  •             }  
  •             catch (Exception ex)  
  •             {  
  •                 #region Catch  
  •                 blnExist = false;  
  •                 #endregion  
  •             }  
  •             return blnExist;  
  •         }  
  •         #endregion  
  •  
  •  
  •         #region Insert record in list  
  •         private void insertRecordInList(SPList oList,string strFirstName,string strLastName)  
  •         {  
  •             try  
  •             {  
  •                 #region Try  
  •                 SPListItem oListItem = oList.Items.Add();  
  •                 oListItem["Title"] = strFirstName;  
  •                 oListItem["LastName"] = strLastName;  
  •                 oListItem.Update();  
  •                 #endregion  
  •   
  •             }  
  •             catch (Exception ex)  
  •             {  
  •                 #region Catch  
  •                 throw ex;  
  •                 #endregion  
  •             }  
  •         }  
  •         #endregion  
  •  
  •         #endregion  
  •   
  •     }  
  • }