{dfp-include}
Access denied.
{sidebar-top} {sidebar-middle} {link-v-xlrg-1} {sidebar-bottom}

privacy policy

{ezoic-ad-1}

{ez_footer_ads} Software Solutions Online http://software-solutions-online.com VBA and VB.Net Tutorials, Learning and Programming Services Sat, 17 Feb 2018 18:07:07 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.4 VBA List – A Powerful Tool for Processing Tables in Excel http://software-solutions-online.com/vba-list-powerful-tool-processing-tables-excel/ http://software-solutions-online.com/vba-list-powerful-tool-processing-tables-excel/#respond Sat, 17 Feb 2018 18:07:07 +0000 http://software-solutions-online.com/?p=11206 The ListObjects property of the Worksheet object returns the ListObjects collection. The ListObjects collection contains all the list objects on a worksheet. The ListObject object is a member of the ListObjects collection. Each ListObject object represents a table (previously known as a list) in the worksheet. An

The post VBA List – A Powerful Tool for Processing Tables in Excel appeared first on Software Solutions Online.

]]>
The ListObjects property of the Worksheet object returns the ListObjects collection. The ListObjects collection contains all the list objects on a worksheet. The ListObject object is a member of the ListObjects collection. Each ListObject object represents a table (previously known as a list) in the worksheet.

An Excel table typically contains related data in a series of worksheet rows and columns that have been formatted as a table. By using the table features, you can then manage the data in the table rows and columns independently from the data in other rows and columns on the worksheet.

Here is how a table (list) looks like. It can be identified by a small blue arrow at the right-most bottom-most cell of the table.

Whenever you import data from a file (Excel / Text / XML / JSON) or from a database (SQL / Access), the imported data is always in the form of a table.

You can also convert the selected range in Excel to a table by using the Format as Table option. For that simply select your data range, in the home tab, go to “Format as Table” and select the desired formatting. You will asked to confirm the selected data range and whether your table has headers. Input the data and click on OK and a table will be created.

To convert a table back to normal range, use the convert to range option. For that, click anywhere on the table, the design tab will be visible. In the design tab, click on convert to range.

Now, that we know what is a table let us look at how to use VBA to modify these tables.

Example 1: Loop through all the tables (lists) in a worksheet

The code below creates a new ListObjects collection which represents all the tables in a worksheet and displays the name of each of the table in the collection. The code along with the comments is self-explanatory.

Sub excelLists()
    Dim dataSheet As Worksheet
    Dim tableList As ListObjects
    Dim table As ListObject
    
    Set dataSheet = Sheet1
    
    'create a new ListObjects collection which represents all the tables in Sheet1
    Set tableList = dataSheet.ListObjects
    
    'Loop through each table in the tableList ListObjects collection
    For Each table In tableList
    
        'Display the table name
        MsgBox table.Name
    
    Next table
    
End Sub

The name of the table can be seen in the design tab. Select any cell in the table and the design tab will be shown. The name of the selected table is seen in the left side of the tab. You can edit it from here. You can also see a list of all the tables in the workbook along with their names and ranges in the Name Manager (in the Formulas tab).

Example 2: Column operations on a table

In this example we will see few of the most common operations that you can perform on the table columns. Namely, looping through all the columns of a table and printing their names, inserting columns at the end or at a specified position, deleting a particular column and copying only the data from a particular column.

Sub ListCols()
    Dim dataSheet As Worksheet
    Dim table As ListObject
    Dim tblCols As ListColumns
    Dim tblCol As ListColumn
    Dim newCol As ListColumn
    
    Set dataSheet = Sheet1
    
    'Refer a table by it's name
    Set table = dataSheet.ListObjects("Table2")
    
    'Get all the columns of a table
    Set tblCols = table.ListColumns
    
    'Loop through all the columns of a table
    For Each tblCol In tblCols
        MsgBox tblCol.Name
    Next tblCol
    
    'Insert a column at the last position
    Set newCol = tblCols.Add
    newCol.Name = "Last"
    
    'Insert a column at the third position (after title)
    Set newCol = tblCols.Add(3)
    newCol.Name = "Third"
        
    'Delete the fifth column (i.e. DOB)
    table.ListColumns(5).Delete
    
    'Copy only the data in column 1 (excluding the header)
    'We are pasting it in the "Last" column for demo
    table.ListColumns(1).DataBodyRange.Copy (Cells(3, 9))

End Sub

Here is how the above table will look after executing the code

Example 3:  Row operations

In this example let us have a look at some of the row operations in a table. As with columns, you can loop through all the rows, add and delete rows, work with totals row and header row.

Sub excelLists()
    Dim dataSheet As Worksheet
    Dim table As ListObject
    Dim tblRows As ListRows
    Dim tblRow As ListRow
    Dim newRow As ListRow
    
    Set dataSheet = Sheet2
    Set table = dataSheet.ListObjects("Table5")
    
    'Get all the Rows of a table
    Set tblRows = table.ListRows
    
    'Loop through all the Rows of a table
    For Each tblRow In tblRows
        'Display the value in each row for column 1
        'The row index will always start at 1, irrespective of its 
        'position on the worksheet 
        MsgBox table.DataBodyRange(tblRow.Index, 1)
    Next tblRow
    
    'Insert a Row at the last position
    tblRows.Add
    
    'Insert a Row at the third position (excluding header row)
    Set newRow = tblRows.Add(3)
        
    'Delete the fifth Row (i.e. with ID 5148)
    table.ListRows(5).Delete
    
    'Display the totals row at the bottom
    table.ShowTotals = True
    
    'Change color of only the header row
    table.HeaderRowRange.Interior.Color = vbBlue
    

End Sub

 

This is how the original table will look like after executing the code

See Also:

Excel VBA, Find and List All Files in a Directory and its Subdirectories

The post VBA List – A Powerful Tool for Processing Tables in Excel appeared first on Software Solutions Online.

]]>
http://software-solutions-online.com/vba-list-powerful-tool-processing-tables-excel/feed/ 0
ActiveCell in Excel VBA – When to Use and When It’s Downright Dangerous http://software-solutions-online.com/activecell-excel-vba-use-downright-dangerous/ http://software-solutions-online.com/activecell-excel-vba-use-downright-dangerous/#respond Fri, 02 Feb 2018 17:59:40 +0000 http://software-solutions-online.com/?p=11191 In this example we will see how to use the ActiveCell property of VBA. The ActiveCell property returns a Range object of the active cell in the active workbook. You can then apply any of the properties or methods of a Range object to it. Though

The post ActiveCell in Excel VBA – When to Use and When It’s Downright Dangerous appeared first on Software Solutions Online.

]]>
In this example we will see how to use the ActiveCell property of VBA. The ActiveCell property returns a Range object of the active cell in the active workbook. You can then apply any of the properties or methods of a Range object to it.

Though you may find a very practical scenarios to use ActiveCell, it is best to avoid using it as much as possible. The reason being, if you accidentally change the active cell during the execution of the macro or you happen to open / activate another workbook, it will cause run-time errors in your code.

So, in this article, I will also suggest few ways to avoid the use of ActiveCell and also how to minimize some errors that can result from using ActiveCell.

Before looking at a practical example, let us have a look at a few examples on how to use the ActiveCell property and the various methods / properties associated with it.

Example 1: Getting the value of the active cell

This example shows how to display the value of an active cell in a message box

    Dim selectedCell As Range
    Set selectedCell = Application.activecell
    MsgBox selectedCell.Value

However, please note that if another workbook is active, the ActiveCell from that workbook will be considered, irrespective of workbook in which the code is written. So, always make sure to activate the current workbook before using ActiveCell.

So, a better way of doing it will be

    Dim selectedCell As Range
    ThisWorkbook.Activate
    Set selectedCell = Application.activecell
    MsgBox selectedCell.Value

 

Example 2: Getting the address / row / column of the active cell

Use the following properties to display the address / row number and column number of the active cell

    Dim selectedCell As Range
    ThisWorkbook.Activate
    Set selectedCell = Application.activecell
    MsgBox selectedCell.Address
    MsgBox selectedCell.Row
    MsgBox selectedCell.Column

 

The address will be displayed as below:

And for row and column, the respective numbers will be displayed.

Example 3: Activating / Selecting a cell

You can make a cell active either by using the activate method or by using the select method on the range you want to activate

    ThisWorkbook.Activate
    Worksheets("Sheet1").Range("B4").Activate

which is equivalent to

    ThisWorkbook.Activate
    Worksheets("Sheet1").Range("B4").Select

And now when you run MsgBox selectedCell.Address you will get the output as “$B$4”

Example 4: Select last row in the active column using ActiveCell

Consider the below snapshot. The ActiveCell is in the first column.

If you want to select the last cell that has data in this active column, you can use the code snippet below.

    ThisWorkbook.Activate
    Application.activecell.End(XlDirection.xlDown).Select

After the execution of the code, the last cell will be selected like this

Example 5: Selecting the cells that contain data around the ActiveCell using CurrentRegion

The CurrentRegion property returns a range of cells bounded by blank rows and columns. In the following example, the selection is expanded to include the cells adjoining the active cell that contain data and the background color of the current region is modified. The entire range is copied to another sheet at the same location.

Sub CurrRegion()
    
    Dim curReg As Range
    
    ThisWorkbook.Activate
    
    'Get the current region and assign it to a Range variable
    Set curReg = ActiveCell.CurrentRegion
    ActiveCell.CurrentRegion.Select
    
    'Format it
    Selection.Interior.Color = vbCyan
    
    'Select the first cell in the range
    Application.ActiveCell.End(XlDirection.xlUp).Select
    Application.ActiveCell.End(XlDirection.xlToLeft).Select
    
    'Paste the current region in another sheet at the same location
    curReg.Copy Worksheets("Sheet2").Range(Application.ActiveCell.Address)

End Sub

 

The current region can be useful when the range of data is not fixed and you need to perform certain operations on it, like format it, copy it, insert charts or send an email using that range.

Example 6: Using offset with ActiveCell

Now let us look at a more practical example of using ActiveCell. Say, in your Excel sheet you have multiple lines of data as shown below and you need to process data only for a single selected row.

The desired output is that in the column “Gaining”, Y or N should be inputted based on the price level and the background color should be set to Green or Red respectively.

Here, we will assume that the stock name is selected before running the macro. To get the values of the Previous Close and Current Price we will use the Offset Method

Sub offset()
    
    Dim preClose As Double, currPrice As Double
    
    ThisWorkbook.Activate
    
    'Get value from the second column i.e. offset of zero rows and one column
    preClose = ActiveCell.offset(0, 1).Value
    
    'Get value from the third column i.e. offset of zero rows and two columns
    currPrice = ActiveCell.offset(0, 2).Value

    If currPrice < preClose Then
        'Set value and format of the forth column i.e. offset of zero rows and three columns
        ActiveCell.offset(0, 3).Value = "N"
        ActiveCell.offset(0, 3).Interior.Color = vbRed
    Else
        ActiveCell.offset(0, 3).Value = "Y"
        ActiveCell.offset(0, 3).Interior.Color = vbGreen
    End If

End Sub

For further details on the Offset Method, please refer to the article “How to use VBA Range.Offset Method

You can easily avoid the use of ActiveCell here, by using the input box to get the stock name / row number from the user.  After running the code on the last row the output will look like this.

See also: “VBA, Excel Automation From Other Applications

The post ActiveCell in Excel VBA – When to Use and When It’s Downright Dangerous appeared first on Software Solutions Online.

]]>
http://software-solutions-online.com/activecell-excel-vba-use-downright-dangerous/feed/ 0
How to Use VBA to Pull Excel Data from Hyperlinks http://software-solutions-online.com/use-vba-pull-excel-data-hyperlinks/ http://software-solutions-online.com/use-vba-pull-excel-data-hyperlinks/#respond Sun, 14 Jan 2018 21:06:00 +0000 http://software-solutions-online.com/?p=11155 In this article, we will look at how to extract data from a website using VBA. For this we will be using the navigate method on the InternetExplorer object. Let us see this in detail. Example 1: Say, you want to pull the current temperature of

The post How to Use VBA to Pull Excel Data from Hyperlinks appeared first on Software Solutions Online.

]]>
In this article, we will look at how to extract data from a website using VBA. For this we will be using the navigate method on the InternetExplorer object. Let us see this in detail.

Example 1:

Say, you want to pull the current temperature of the city of Vancouver from this site. Before we begin our coding, we need to know the tag element that contains the required data in the web site.

To do that, navigate to the site in the browser. Right click on the data to be retrieved and click on inspect element.

The element will be highlighted in the Developer Tools window that will be opened.

So, we basically want to extract the inner text of a “p” tag with class “temperature”. This can be done as follows.

First of all, we need to make sure that the required libraries are included in your VBA project, namely, Microsoft HTML Object Library and Microsoft Internet Controls.

Now, let’s start with the code. Create a new InternetExplorer object using


Dim IE As New InternetExplorer

Specify the URL from which to extract data and navigate to it using


url = "https://www.theweathernetwork.com/ca/weather/british-columbia/vancouver"

IE.navigate url

 

For troubleshooting purpose, you can make the browser window visible by using:


 IE.Visible = True

After navigating to a URL, you need to wait till the web page is entirely loaded. This can be done by using


 Do
 DoEvents
 Loop Until IE.readyState = READYSTATE_COMPLETE

(After the webpage is completely loaded, the readyState property of the InternetExplorer object is set to READYSTATE_COMPLETE)

Next, you save the contents of the webpage loaded using the document property


  Dim Doc As HTMLDocument

Set Doc = IE.document

 

You can then extract all elements of a particular type from the HTML document using


 Dim tagElements As Object

 Set tagElements = Doc.all.tags("p")

To loop through all these “p” tag elements


 Dim element As Object

For Each element In tagElements

'Code to pull temperature goes here

Next

From all the p tags, we are looking for the tag that contains temperature (°C) and has class name “temperature”. For this we use the element.innerText and element.className properties as follows


 If InStr(element.innerText, "°C") And InStr(element.className, "temperature") Then
 Sheet1.Cells(1, 1).Value = element.innerText
 End If

Finally, we do the cleanup using


 IE.Quit
 Set IE = Nothing

Here is the entire thing put together


Sub extractVancouverData()

Dim IE As New InternetExplorer
 Dim url As String
 Dim item As HTMLHtmlElement
 Dim Doc As HTMLDocument
 Dim tagElements As Object
 Dim element As Object
 Dim lastRow
 
 Application.ScreenUpdating = False
 Application.DisplayAlerts = False
 Application.EnableEvents = False
 Application.Calculation = xlCalculationManual
 
 url = "https://www.theweathernetwork.com/ca/weather/british-columbia/vancouver"

IE.navigate url
 
 IE.Visible = True
 
 Do
 DoEvents
 Loop Until IE.readyState = READYSTATE_COMPLETE

Set Doc = IE.document

lastRow = Sheet1.UsedRange.Rows.Count + 1
 
 Set tagElements = Doc.all.tags("p")
 For Each element In tagElements

  If InStr(element.innerText, "°C") &gt; 0 And InStr(element.className, "temperature") &gt; 0 Then
    Sheet1.Cells(lastRow, 1).Value = element.innerText
    ' Exit the for loop once you get the temperature to avoid unnecessary processing
    Exit For
  End If
 Next

IE.Quit
 Set IE = Nothing
 
 Application.ScreenUpdating = True
 Application.DisplayAlerts = True
 Application.EnableEvents = True
 Application.Calculation = xlCalculationAutomatic

End Sub

You can also extract all elements from the HTMLDocument by the element’s ID, className, Name or tagName using the respective method as shown below


Set tagElements = Doc.getElementsByClassName("temperature")

For Each element In tagElements

If InStr(element.innerText, "°C") Then
Sheet1.Cells(lastRow, 1).Value = element.innerText
End If

Next

 

Example 2:

Many times while extracting data from a website, you need to go to a page and click on a link as you cannot directly access the results using a URL. For this you can use the element.Click method. Say you click on the link “Excel” on the home page of this site. This is how you can do it


Sub clickOnLink()

Dim IE As New InternetExplorer
Dim str As String
Dim Doc As HTMLDocument
Dim tagElements As Object
Dim element As HTMLObjectElement

str = "http://software-solutions-online.com/"

IE.navigate str
IE.Visible = True

Do
DoEvents
Loop Until IE.readyState = READYSTATE_COMPLETE

Set Doc = IE.document

'First get all the links

Set tagElements = Doc.all.tags("a")

' Loop through all the links
For Each element In tagElements

' Look for the link that contains the text Excel
If element.innerText = "Excel" Then

'Click on the link
element.Click

Do
DoEvents
Loop Until IE.readyState = READYSTATE_COMPLETE

Exit For
End If
Next

If you run this code with the IE visible, you will see that the code clicks on the Excel link. Now you can extract the required data using the methods described above.

If you’re interested in doing something similar via recording a macro, please have a look at this article and for using a query table check out this one.

 

The post How to Use VBA to Pull Excel Data from Hyperlinks appeared first on Software Solutions Online.

]]>
http://software-solutions-online.com/use-vba-pull-excel-data-hyperlinks/feed/ 0
Set a Column in VBA as Header and Other Columns as Subheader http://software-solutions-online.com/set-column-vba-header-columns-subheader/ http://software-solutions-online.com/set-column-vba-header-columns-subheader/#respond Tue, 02 Jan 2018 20:53:43 +0000 http://software-solutions-online.com/?p=11164 In this article we will look at an example of how to transform columns into headers and sub-headers using Excel VBA. Example 1: So, let’s say you have a monthly expense report like this in a sheet called Expenses. And you need to transform the

The post Set a Column in VBA as Header and Other Columns as Subheader appeared first on Software Solutions Online.

]]>
In this article we will look at an example of how to transform columns into headers and sub-headers using Excel VBA.

Example 1:

So, let’s say you have a monthly expense report like this in a sheet called Expenses.

And you need to transform the columns Wages, Lease and Office Supplies into sub-headers for each month, in a format like this into a sheet called Output

Here is how we can achieve this. First we get the last row on the expense sheet so that we can loop through each row, as shown below:


 Set expenseSheet = Sheets("Expenses")
 Set outputSheet = Sheets("Output")
 
 'Get the last row from the expense sheet
 lastExpenseRow = expenseSheet.Cells(Rows.Count, 1).End(xlUp).Row
 
 For currentExpenseRow = 2 To lastExpenseRow

'Actual code goes here

Next currentExpenseRow

Next, within the for loop, for each row we get the number of columns. Most of the times, this will be same for all rows and can be hard-coded outside the for loop (as we have done in the next example).


 'get the number of columns in the current row
 noOfCols = expenseSheet.Cells(currentExpenseRow, Columns.Count).End(xlToLeft).Column

Then, get the row number to paste into.


 '+2 so that a blank row is inserted between two months
 rowToPaste = outputSheet.Cells(Rows.Count, 2).End(xlUp).Row + 2

Note: As we will be leaving a blank row in between 2 months, we are using + 2 at the end instead of + 1

While transforming data, we will first copy the name of the month


 'copy the month name
 expenseSheet.Cells(currentExpenseRow, 1).Copy Destination:=outputSheet.Cells(rowToPaste, 1)

 

The actual expenses will be pasted from the next row, so increment the counter


 'increment the row on the output sheet
 rowToPaste = rowToPaste + 1

For all the remaining columns (the expense columns), we will copy the expense header and the expense data from each column (of the respective month) and paste in the subsequent rows (for that month), like this


'For all the remaining expense columns
For colNo = 2 To noOfCols

'First copy the expense header
expenseSheet.Cells(1, colNo).Copy Destination:=outputSheet.Cells(rowToPaste, 1)

'And then the actual expenses for the corresponding month
expenseSheet.Cells(currentExpenseRow, colNo).Copy Destination:=outputSheet.Cells(rowToPaste, 2)

rowToPaste = rowToPaste + 1
Next colNo

Here is the entire code put together.


Sub colToHeaders()

Dim expenseSheet As Worksheet, outputSheet As Worksheet
Dim currentExpenseRow As Long, lastExpenseRow As Long, rowToPaste As Long
Dim noOfCols As Long, colNo As Long

Set expenseSheet = Sheets("Expenses")
Set outputSheet = Sheets("Output")

'get the last row from the expense sheet
lastExpenseRow = expenseSheet.Cells(Rows.Count, 1).End(xlUp).Row

For currentExpenseRow = 2 To lastExpenseRow

With expenseSheet

'get the number of columns in the current row
noOfCols = .Cells(currentExpenseRow, Columns.Count).End(xlToLeft).Column

'+2 so that a blank row is inserted between two months
rowToPaste = outputSheet.Cells(Rows.Count, 2).End(xlUp).Row + 2

'copy the month name
.Cells(currentExpenseRow, 1).Copy Destination:=outputSheet.Cells(rowToPaste, 1)

'increment the row on the output sheet
rowToPaste = rowToPaste + 1

'For all the remaining expense columns
For colNo = 2 To noOfCols

'First copy the expense header
.Cells(1, colNo).Copy Destination:=outputSheet.Cells(rowToPaste, 1)

'And then the actual expenses for the corresponding month
.Cells(currentExpenseRow, colNo).Copy Destination:=outputSheet.Cells(rowToPaste, 2)

rowToPaste = rowToPaste + 1
Next colNo

End With

Next currentExpenseRow
End Sub

 

Example 2:

Let us look at how to do the reverse — that is — you have data in headers and sub-headers format like this in the expenses sheet,

And you want to convert it into column format like this in the output sheet

Here we will assume that each month has exactly same sub-headers below it. The code is pretty similar to the above one and hence, the explanation is provided in the comments itself, in code below.


Sub headersToCol()

Dim expenseSheet As Worksheet, outputSheet As Worksheet
 Dim currentExpenseRow As Long, lastExpenseRow As Long, rowToPaste As Long
 Dim noOfCols As Long, colNo As Long
 
 Set expenseSheet = Sheets("Expenses")
 Set outputSheet = Sheets("Output")
 
 'get the last row from the expense sheet
 lastExpenseRow = expenseSheet.Cells(Rows.Count, 1).End(xlUp).Row
 
 'This is the number of sub-headers under each month
 noOfCols = 3
 
 'Loop through each row on the expense sheet
 For currentExpenseRow = 3 To lastExpenseRow
 
 With expenseSheet
 
 'Get the row to paste into the output sheet
 rowToPaste = outputSheet.Cells(Rows.Count, 1).End(xlUp).Row + 1
 
 'copy the month name
 .Cells(currentExpenseRow, 1).Copy Destination:=outputSheet.Cells(rowToPaste, 1)
 
 'increment the row on the output sheet as the expense data starts from the next row
 currentExpenseRow = currentExpenseRow + 1
 
 'For each of the expense columns below every month
 'We are looping till noOfCols + 1 as the expense columns start from column 2
 For colNo = 2 To noOfCols + 1
 
 'Copy the actual expenses for the corresponding month
 .Cells(currentExpenseRow, 2).Copy Destination:=outputSheet.Cells(rowToPaste, colNo)
 
 'Go to the next expense row
 currentExpenseRow = currentExpenseRow + 1
 
 Next colNo
 
 End With
 
 'Increment for the next month
 rowToPaste = rowToPaste + 1
 
 Next currentExpenseRow
End Sub

 

Thus, we can easily do column to headers / sub-headers transformation and vice-versa using the two example codes above. What’s the next step? Let’s say you want to take these values and output them to Word, then click to find out more.

The post Set a Column in VBA as Header and Other Columns as Subheader appeared first on Software Solutions Online.

]]>
http://software-solutions-online.com/set-column-vba-header-columns-subheader/feed/ 0
Excel VBA: Display File Name as Hyperlink http://software-solutions-online.com/excel-vba-display-file-name-hyperlink/ http://software-solutions-online.com/excel-vba-display-file-name-hyperlink/#comments Mon, 18 Dec 2017 20:44:19 +0000 http://software-solutions-online.com/?p=11147 In this article we will show you how to display file name as a hyperlink to a file in Excel. We first introduced this concept in this article but will expand upon it here. For this we will use the Hyperlinks.Add Method. Let’s have a

The post Excel VBA: Display File Name as Hyperlink appeared first on Software Solutions Online.

]]>
In this article we will show you how to display file name as a hyperlink to a file in Excel. We first introduced this concept in this article but will expand upon it here. For this we will use the Hyperlinks.Add Method. Let’s have a look at the syntax first.

Hyperlinks.Add (Anchor , Address , SubAddress , ScreenTip , TextToDisplay)

where

Anchor: is the anchor for the hyperlink. Can be either a Range or Shape object (required)

Address: Address of the hyperlink (Path to the file in our case; can also be a URL or email hyperlink) (required)

SubAddress: Sub-address of the hyperlink (optional)

ScreenTip: The screen tip to be displayed when the mouse pointer is hovered over the hyperlink (optional)

TextToDisplay (string): The text (file name in our case) to be displayed for the hyperlink. (optional)

The method returns a Hyperlink object that represents the new hyperlink

So, let us look at an example on how to implement this. Say, you want to create one hyperlink each for all the files in a folder. First, we will need to create a FileSystemObject and then get the folder object for the folder whose files we need to list.

'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")

'Get the folder object
Set objFolder = objFSO.GetFolder("E:\FolderName")

 

Then we loop through each of the files in the folder and assign a hyperlink to it. Clicking on the hyperlink will open the file.


i = 1

'Loop through each file in the folder
For Each objFile In objFolder.Files
 
ActiveSheet.Hyperlinks.Add Anchor:=Cells(i, 1), Address:=objFile.Path, TextToDisplay:=objFile.Name, ScreenTip:=objFile.Path
 i = i + 1

Next objFile

 

The hyperlinks will be created in a new row each in column 1 — specified by Cells(i, 1)

Address contains the absolute path to the file — specified by objFile.Path

TextToDisplay is the name of the file — specified by objFile.Name

ScreenTip is set to the file path, so, you can view the path when you mouse over the filename (i.e. the hyperlink)

Here is all the code put together:


Option Explicit

Sub addHyperlinks()

Dim objFSO As Object
 Dim objFolder As Object
 Dim objFile As Object
 Dim i As Integer
 Dim dataSheet As Worksheet
 
 Set dataSheet = Sheet1
 
 'Create an instance of the FileSystemObject
 Set objFSO = CreateObject("Scripting.FileSystemObject")
 
 'Get the folder object
 Set objFolder = objFSO.GetFolder("E:\FolderName")
 
 i = 1
 
 'Loop through each file in the folder
 For Each objFile In objFolder.Files
 
 dataSheet.Hyperlinks.Add Anchor:=Cells(i, 1), Address:=objFile.Path, TextToDisplay:=objFile.Name, ScreenTip:=objFile.Path
 i = i + 1
 
 Next objFile

End Sub

So, if the contents of the folder are as shown below:

The output will be like this:

Let us look at a couple of other examples of how to add other types of hyperlinks.

Example 1: Add a web address as a hyperlink


 With Sheet1
.Hyperlinks.Add Anchor:=.Range("A1"), _
Address:="http://google.com", _
ScreenTip:="Google Home Page", _
TextToDisplay:="Click for Google Search"
 End With

The hyperlink will be displayed like this

Clicking on it will take you to Google Search

Example 2: Add an email hyperlink


With Sheet1
.Hyperlinks.Add Anchor:=.Range("A1")
Address:="mailto:someone@example.com?subject=Thank You"
ScreenTip:="Email us today"
TextToDisplay:="Contact Us"
End With

The hyperlink will be displayed like this

Clicking on the hyperlink will open your default mail client with the recipient and subject populated.

You can also edit the hyperlinks by right clicking on it > Edit Hyperlink. This is how the mail hyperlink dialog box looks.

Example 3: Add hyperlink to a picture


With Sheet1
.Hyperlinks.Add Anchor:=.Shapes("Picture1"), _
Address:="http://google.com", _
ScreenTip:="Google Web Site"
End With

So, a hyperlink will be assigned to the shape with name Picture1, clicking on it will take you to the specified web address

Example 4: Loop through all the hyperlinks in the sheet

You can also loop through all the hyperlinks in the sheet and get their properties, like, Name, Address, EmailSubject, ScreenTip, TextToDisplay and SubName among others.

The following code displays the name of all the hyperlinks one by one and then deletes them.


With Sheet1
 For Each hLink In .Hyperlinks
    MsgBox hLink.Name
    hLink.Delete 
 Next
End With

You can also follow the hyperlink using hLink.Follow

The post Excel VBA: Display File Name as Hyperlink appeared first on Software Solutions Online.

]]>
http://software-solutions-online.com/excel-vba-display-file-name-hyperlink/feed/ 1
ByRef Argument Type Mismatch Error: Fixes http://software-solutions-online.com/byref-argument-type-mismatch-error-fixes/ http://software-solutions-online.com/byref-argument-type-mismatch-error-fixes/#respond Sat, 02 Dec 2017 21:21:04 +0000 http://software-solutions-online.com/?p=11125 In this article, we will look at the ByRef argument type mismatch error.  First, let us have a look at what is ByRef and the difference between ByRef and ByVal. In Visual Basic, you can pass an argument to a procedure or function by value or

The post ByRef Argument Type Mismatch Error: Fixes appeared first on Software Solutions Online.

]]>
In this article, we will look at the ByRef argument type mismatch error.  First, let us have a look at what is ByRef and the difference between ByRef and ByVal.

In Visual Basic, you can pass an argument to a procedure or function by value or by reference. This is known as the passing mechanism, and it determines whether the procedure or function can modify the variable that has been passed. The declaration of the function determines the passing mechanism for each parameter by specifying the ByVal or ByRef keyword.

The advantage of passing an argument ByRef is that the procedure can return a value to the calling code through that argument. The advantage of passing an argument ByVal is that it protects a variable from being changed by the procedure. The default in VBA is to pass arguments by reference. For more details, you can refer to the article here.

Whenever an argument is passed ByRef (by reference), the default, you must match the precise data type in the argument passed and the argument in the function definition. So, let us have a look at some of the most likely causes of the error and how to fix them:

Case 1: You passed an argument of one type that could not be forced to the type expected.

For example, this error occurs if you try to pass an Integer variable when a Long is expected.


Sub callByRef()

Dim amount As Integer

amount = 80
Call processAmt(amount)

'Rest of the code

End Sub

Public Function processAmt(amount As Long)
'Do your processing here
End Function

The error that you will get is:

Let us look at possible solutions to this:

Solution 1:

If possible, always try to match the data type. This is easiest and quickest solution. So, in our case, the amount variable should be integer (or long, based on the requirement) in both the places.


Dim amount As Long

Solution 2:

Force coercion to occur by passing the argument in its own set of parentheses (even if it causes information to be lost).


Sub callByRef()

Dim amount As Integer

amount = 80

Call processAmt((amount))

End Sub

Placing the argument in its own set of parentheses the fractional portion of the number is rounded to make it conform to the expected argument type. The result of the evaluation is placed in a temporary location and the original amount retains its value.

Solution 3:

Similar to the above solution, you can explicitly convert the data type of the variable while passing


Sub callByRef()

Dim amount As Integer
 
 amount = 80
 
 Call processAmt(CLng(amount))
 
 End Sub

 

Solution 4:

Pass the variable by value. For that, specify the keyword “ByVal” before the variable name in the function definition.


Public Function processAmt(ByVal amount As Long)
'Do your processing here
End Function

Case 2: You have not declared the variable in the calling sub.


Sub callByRef()

amount = 80

Call processAmt(amount)

End Sub

Public Function processAmt(amount As Long)
'Do your processing here
End Function

Here you need to make sure that the variable is defined along with the data type


Dim amount As Long

As a standard practice, you should always have “Option Explicit” added to your code as the first line. This makes declaring variables mandatory and helps preventing many errors. Here is an example of where to place it


Option Explicit
Sub callByRef()

'Code here
End Sub

 

Case 3: Variable is declared but the data type is not specified


Dim firstName

 

In VB, if you declare a variable without specifying the data type, by default the variable is assigned the type “variant”. So, you need to explicitly specify the variable data type before passing it to a function.

Another common source of error here is when you declare multiple variables on a single line and specify the data type only for the last one. For example,


Dim firstName, lastName As String

Here, VBA sets lastName as a String. However, for firstName it is a variant data type and not String. This is because in VBA, you have to specify data type for each and every variable separately (even if the variables are declared on the same line).

So, the above statement is equivalent to:


Dim firstName As Variant, lastName As String

And the right way to declare the variable is

 Dim firstName As String, lastName As String 

So, to summarize, the argument data type should always be same while calling a function and in the function definition. If you get this error, you can fix it by using one of following methods

  1. Make sure the variable is defined with correct data type
  2. Use explicit conversion while passing the argument
  3. Use an own set of parentheses while passing the argument
  4. Pass the variable by value if you do not intend to change the value in the called function

 

The post ByRef Argument Type Mismatch Error: Fixes appeared first on Software Solutions Online.

]]>
http://software-solutions-online.com/byref-argument-type-mismatch-error-fixes/feed/ 0
Excel VBA Find – How to find any value in a range of cells with VBA http://software-solutions-online.com/excel-vba-find-find-value-range-cells-vba/ http://software-solutions-online.com/excel-vba-find-find-value-range-cells-vba/#respond Sun, 26 Nov 2017 17:48:24 +0000 http://software-solutions-online.com/?p=11187 Many times as a developer you might need to find a match to a particular value in a range or sheet, and this is often done using a loop. However, VBA provides a much more efficient way of accomplishing this using the Find method. In

The post Excel VBA Find – How to find any value in a range of cells with VBA appeared first on Software Solutions Online.

]]>
Many times as a developer you might need to find a match to a particular value in a range or sheet, and this is often done using a loop. However, VBA provides a much more efficient way of accomplishing this using the Find method. In this article we’ll have a look at how to use the Range.Find Method in your VBA code. Here is the syntax of the method:

expression.Find (What , After , LookIn , LookAt , SearchOrder , SearchDirection , MatchCase , MatchByte , SearchFormat )

where:

What: The data to search for. It can be a string or any of the Microsoft Excel data types (the only required parameter, rest are all optional)

After: The cell after which you want the search to begin. It is a single cell which is excluded from search. Default value is the upper-left corner of the range specified.

LookIn: Look in formulas, values or notes using constants xlFormulas, xlValues, or xlNotes respectively.

LookAt: Look at a whole value of a cell or part of it (xlWhole or xlPart)

SearchOrder: Search can be by rows or columns (xlByRows or xlByColumns)

SearchDirection: Direction of search (xlNext, xlPrevious)

MatchCase: Case sensitive or the default insensitive (True or False)

MatchByte: Used only for double byte languages (True or False)

SearchFormat: Search by format (True or False)

All these parameters correspond to the find dialog box options in Excel.

Return Value: A Range object that represents the first cell where the data was found. (Nothing if match is not found).

Let us look at some examples on how to implement this. In all the examples below, we will be using the table below to perform the search on.

Example 1: A basic search

In this example, we will look for a value in the name column.

    Dim foundRng As Range
    
    Set foundRng = Range("D3:D19").Find("Andrea")
    MsgBox foundRng.Address

 

The rest of the parameters are optional. If you don’t use them then Find will use the existing settings. We’ll see more about this shortly.

The output of this code will be the first occurrence of the search string in the specified range.

If the search item is not found then Find returns an object set to Nothing. And an error will be thrown if you try to perform any operation on this (on foundRng in the above example)

So, it is always advisable to check whether the value is found before performing any further operations.

    Dim foundRng As Range
    
    Set foundRng = Range("D3:D19").Find("Andrea")
    
    If foundRng Is Nothing Then
        MsgBox "Value not found"
    Else
        MsgBox foundRng.Address
    End If

 

Let us know have a look at the optional parameters. To keep it simple, we will exclude the above error handling in the subsequent examples.

Example 2: Using after

    
    Set foundRng = Range("D3:D19").Find("Andrea", Range("D6"<span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span>))
    MsgBox foundRng.Address

OR

    
    Set foundRng = Range("D3:D19").Find("Andrea", After:=Range("D6"))
    MsgBox foundRng.Address

The highlighted cell will be searched for

Example 3: Using LookIn

Before seeing an example, here are few things to note with LookIn

  1. Text is considered as a value as well as a formula
  2. xlNotes is same as xlComments
  3. Once you set the value of LookIn all subsequent searches will use this setting of LookIn (using VBA or Excel)
    'Look in values
    Set foundRng = Range("A3:H19").Find("F4", , xlValues)
    MsgBox foundRng.Address
    'Output --> $B$4

    'Look in values and formula
    Set foundRng = Range("A3:H19").Find("F4", LookIn:=xlFormulas)
    MsgBox foundRng.Address
    'Output --> $B$4

    'Look in values and formula (as previous setting is preserved)
    Set foundRng = Range("H3:H19").Find("F4")
    MsgBox foundRng.Address
    'Output --> $H$4
    
    'Look in comments
    Set foundRng = Range("A3:H19").Find("F4", , xlNotes)
    MsgBox foundRng.Address
    'Output --> $D$4

Example 4: Using LookAt

    'Match only a part of a cell
    Set foundRng = Range("A3:H19").Find("John", , xlValues, xlPart)
    MsgBox foundRng.Address
    'Output --> $D$8

    'Match entire cell contents
    Set foundRng = Range("A3:H19").Find("John", LookAt:=xlWhole)
    MsgBox foundRng.Address
    'Output --> $D$9

LookAt setting too is preserved for subsequent searches.

Example 5: Using SearchOrder

    'Searches by rows
    Set foundRng = Range("A3:H19").Find("Sa", , , xlPart, xlRows)
    MsgBox foundRng.Address
    'Output --> $G$4

    'Searches by columns
    Set foundRng = Range("A3:H19").Find("Sa", SearchOrder:=xlColumns)
    MsgBox foundRng.Address
    'Output --> $F$5

SearchOrder setting is preserved for subsequent searches.

Example 6: Using SearchDirection

    'Searches from the bottom
    Set foundRng = Range("A3:H19").Find("Alexander", , , , , xlPrevious)
    MsgBox foundRng.Address
    'Output --> $D$18

    'Searches from the top
    Set foundRng = Range("A3:H19").Find("Alexander", SearchDirection:=xlNext)
    MsgBox foundRng.Address
    'Output --> $D$11

Example 7: Using MatchCase

    'Match Case
    Set foundRng = Range("A3:H19").Find("Sa", , , , xlRows, , True)
    MsgBox foundRng.Address
    'Output --> $F$5

    'Ignore case
    Set foundRng = Range("A3:H19").Find("Sa", MatchCase:=False)
    MsgBox foundRng.Address
    'Output --> $G$4

 

Example 8: Using SearchFormat

When you search for a format it is important to note that the format settings stick until you change them. So, before you use SearchFormat, it is a good practice to always clear any previous formats that have been set.

    'Clear any previous format set
    Application.FindFormat.Clear
    
    'Set the format for find operation
    Application.FindFormat.Interior.Color = 14348258
        
    'Match format
    Set foundRng = Range("A3:H19").Find("SA", MatchCase:=True, SearchFormat:=True)
    MsgBox foundRng.Address
    'Output --> $G$15

    'Search without matching the format
    Set foundRng = Range("A3:H19").Find("SA", MatchCase:=True, SearchFormat:=False)
    MsgBox foundRng.Address
    'Output --> $G$4

    'Search only for cells of a particular format
    Set foundRng = Range("B3:H19").Find("*", MatchCase:=True, SearchFormat:=True)
    MsgBox foundRng.Address
    'Output --> $B$3


Example 9FindNext and FindPrevious

In all the previous examples, we have been looking for just the first occurrence of the search criteria. If you want to find multiple occurrences, we use the FindNext and FindPrevious methods. Both of these need a reference to the last cell found, so that the search continues after that cell. If this argument is dropped, it will keep returning the first occurrence.

    'First occurrence
    Set foundRng = Range("A3:H19").Find("Ms")
    MsgBox foundRng.Address
    'Output --> $C$5

    'Find the next occurrence
    Set foundRng = Range("A3:H19").FindNext(foundRng)
    MsgBox foundRng.Address
    'Output --> $C$10
        
    'Find the previous occurrence again
    Set foundRng = Range("A3:H19").FindPrevious(foundRng)
    MsgBox foundRng.Address
    'Output --> $C$5

If you are looking to find or list all files and directories in a folder / sub-folder, you can refer to the articles below:

Find and List all Files and Folders in a Directory

Excel VBA, Find and List All Files in a Directory and its Subdirectories

The post Excel VBA Find – How to find any value in a range of cells with VBA appeared first on Software Solutions Online.

]]>
http://software-solutions-online.com/excel-vba-find-find-value-range-cells-vba/feed/ 0
MS Access Type Mismatch in Expression – What Causes this Error? http://software-solutions-online.com/ms-access-type-mismatch-expression-causes-error/ http://software-solutions-online.com/ms-access-type-mismatch-expression-causes-error/#respond Sun, 19 Nov 2017 21:21:02 +0000 http://software-solutions-online.com/?p=11128 In this article, we will talk about the Data Type Mismatch errors in MS Access. The “Type mismatch in expression” error indicates that Access cannot match an input value to the data type it expects for the value. For example, if you give Access a

The post MS Access Type Mismatch in Expression – What Causes this Error? appeared first on Software Solutions Online.

]]>
In this article, we will talk about the Data Type Mismatch errors in MS Access.

The “Type mismatch in expression” error indicates that Access cannot match an input value to the data type it expects for the value. For example, if you give Access a text string when it is expecting a number, you receive a data type mismatch error.

Let us look at some situations where this error can occur.

Example 1: You are trying to join two tables on a field, but the data types of the joined fields are not the same.

Imagine you are trying to join the customer and supplier tables below on Postcode. But the postcode fields have different data types in the two tables as seen below:

So, if you try to join using the condition

WHERE customer.postcode = supplier.postcode

You will get the data type mismatch error. In this case, you need to verify that the data type of each pair of joined fields in the query is the same. If not, either

  1. Change the data type of one of the joined fields to match the data type of the other so you don’t get the mismatch error OR
  2. Use conversion function to convert the data type

WHERE customer.postcode = CStr(supplier.postcode)

Example 2: 

Similar to above example, you need to verify that the criteria for a column matches the data type of the column’s underlying field in the WHERE clause of an SQL query. If you specify text criteria for say a numeric or date/time field,

WHERE customer.age > “60”

or

WHERE customer.dateofbirth < “01/01/1977”

you’ll get this error:

An error message is returned because Access interprets values in quote marks as text, not numbers. So, the valid syntax will be:

WHERE customer.age > 60

(Numbers without quotes for numeric data)

and

WHERE customer.dateofbirth < #01/01/1977#

(Dates should be entered within two hashes – #<Date>#)

Example 3: The expression for default value of a field does not evaluate to the same data type as the field.

In the above example, the field is of numeric type and we are trying to assign it a text value. When you try to save, you will get the below error.

As mentioned above, any data within double quotes (“”) is treated as a string. So, you will get the error even if you try to enter a number with double quotes – “4086” as the default value. A valid value will be only – 4086 – without the quotes

Note: To change the default value of a field, you need to go to the table’s design mode.

Example 4: You typed the dollar sign ($) in criteria you specified for a Currency field.

While building a query through design mode, if you enter a condition for a currency field as, say, >$50, Access automatically encloses the string you type in quote marks. Thus, it will be interpreted as a String instead of currency and an error will be thrown. You need to remove the dollar sign, and then view the results.

Other situations where this error can occur:

You’re specifying criteria for a Lookup field, and the criteria use the values that are shown (like a name) in the lookup list instead of their associated foreign key values (like an ID). Because the foreign key values are the values actually stored in the underlying table, you should use them when you specify criteria for a field.

 

The post MS Access Type Mismatch in Expression – What Causes this Error? appeared first on Software Solutions Online.

]]>
http://software-solutions-online.com/ms-access-type-mismatch-expression-causes-error/feed/ 0
Excel VBA Color Index: Complete Guide to Fill Effects and Colors In Cells http://software-solutions-online.com/excel-vba-color-index-complete-guide-fill-effects-colors-cells/ http://software-solutions-online.com/excel-vba-color-index-complete-guide-fill-effects-colors-cells/#respond Sun, 05 Nov 2017 21:21:01 +0000 http://software-solutions-online.com/?p=11118 In this article, let’s look at the various ways to set or remove the interior/background color of a cell or range – ie to fill the cell.  We’ll also have a look at how to fill a cell/range with a pattern. Finally, we’ll review how

The post Excel VBA Color Index: Complete Guide to Fill Effects and Colors In Cells appeared first on Software Solutions Online.

]]>
In this article, let’s look at the various ways to set or remove the interior/background color of a cell or range – ie to fill the cell.  We’ll also have a look at how to fill a cell/range with a pattern. Finally, we’ll review how to get the color input from the user using xlDialogEditColor and working with color gradients.

Example 1: Set the color of a cell / range

The .Interior.Color property is used to set the color of a cell or a range. There are various methods in which we can do this.

'Using XlRgbColor Enumeration - for few cells in a row
Range("B2:D2").Interior.Color = rgbDarkGreen

'Using Color Constants - for a cell using row and column number
Cells(3, 2).Interior.Color = vbYellow

'Specifying the RGB values - using A1 notation
Range("B4").Interior.Color = RGB(255, 0, 0)

'Using Color Code - for few cells in a column
Range("B5:B6").Interior.Color = 15773696

'Using Color Index - for a range
Range("B7:D8").Interior.ColorIndex = 7

This is how the output will look

For more details, refer to article Excel VBA, Cell Fill Color

Example 2: Set the color of a an entire row

You can use the .Interior.Color property on an entire row. Say you want to highlight all rows where the value of a column satisfies a condition:

Sub highlightRows()
    Dim rowNo As Integer
    For rowNo = 3 To 12
        If Sheet1.Cells(rowNo, 3).Value < 30 Then
            Rows(rowNo).Interior.Color = vbRed
        End If
    Next
End Sub

Here is the Excel before and after executing the code.

Example 3: Set the color of a an entire column

Similar to Example 2, you can fill an entire column using:

'Set color for column
Columns(2).Interior.Color = vbCyan

 

Example 4: Remove the color from a cell / range

You can also remove the background color of a cell by setting it to xlNone

'Remove color
Range("A1").Interior.Color = xlNone

or you can set a cell to have automatic color using xlColorIndexAutomatic

'Set color to automatic
Range("A1").Interior.ColorIndex = xlColorIndexAutomatic

Example 5: Get the color code of a cell

You can also get the color code of a cell. The line below gets the color code of the color used to fill cell A1 and prints it in cell B1:

'gets the color code used to fill cell A1
Cells(1, 2) = Range("A1").Interior.Color

 

Example 6: Get the color input from the user using xlDialogEditColor

The xlDialogEditColor is a dialog used to get a color code from the user. This dialog has 2 tabs: Standard and which we will see soon.

Syntax:

intResult = Application.Dialogs(xlDialogEditColor).Show(intIndex, [intRed], [intGreen], [intBlue])

intResult: Zero if the user cancels the dialog and -1 if the user selects a color.
intIndex: Selected color when the edit color dialog is opened. It is also used as an identifier to get the value of the color selected by the user. (More details below).
intRed, intGreen, intBlue: Red, blue and green components of a color

There are 2 methods for calling this dialog:

1. Displaying the standard tab: If only the intIndex is specified and the last 3 parameters are omitted, standard tab will be displayed. intIndex will decide the color index initially selected in the standard tab. This is a number between zero and 56.

intResult = Application.Dialogs(xlDialogEditColor).Show(20)

2. The custom tab is initially displayed. If all the 4 parameters, including the RGB values, are specified, the custom tab will be displayed.

 
intResult = Application.Dialogs(xlDialogEditColor).Show(20, 100, 100, 200) 

So, here is the complete code to get the color code from the user:


Sub changeColor()

Dim intResult As Long, intColor As Long

'displays the color dialog
intResult = Application.Dialogs(xlDialogEditColor).Show(40, 100, 100, 200)

'gets the color selected by the user
intColor = ThisWorkbook.Colors(40)

'changes the fill color of cell A1
Range("A1").Interior.Color = intColor

End Sub

Note: The intIndex specified in the xlDialogEditColor (40 in our example) is also the index used by ThisWorkbook.Colors. You need to make sure that these two numbers match.

Example 7: Gradient’s Colors

You can create a gradient using “xlPatternLinearGradient”


Range("A1").Interior.Pattern = xlPatternLinearGradient

It will look like this:

A gradient can have one or more colorStops, and each ColorStop has a position (a value between 0 and 1) and a color property. When you create a gradient, by default, the gradient has two ColorStop objects. One of the color stop objects has the position 1 and the other has the position 2. In order to be able to fully use the gradient properties in VBA, it is best to change the default positions to 0 and 1. In this way we would be able to have additional positions (colorStops) in between (i.e 0.5, 0.3). Let us now look at an example.


Sub multiColorStops()
Dim objColorStop As ColorStop
Dim lngColor1 As Long

'First create a gradient
Range("A1").Interior.Pattern = xlPatternLinearGradient

'Changes orientation to vertical (default is horizontal) - optional
Range("A1").Interior.Gradient.Degree = 90

'Clears all previous colorStop objects as they are at position 1 and 2
Range("A1").Interior.Gradient.ColorStops.Clear

'Start creating multiple colorStops at various positions from 0 to 1
Set objColorStop = Range("A1").Interior.Gradient.ColorStops.Add(0)

'Set the color for each colorstop
objColorStop.Color = vbYellow

Set objColorStop = Range("A1").Interior.Gradient.ColorStops.Add(0.33)
objColorStop.Color = vbRed

Set objColorStop = Range("A1").Interior.Gradient.ColorStops.Add(0.66)
objColorStop.Color = vbGreen

Set objColorStop = Range("A1").Interior.Gradient.ColorStops.Add(1)
objColorStop.Color = vbBlue

End Sub

The final result will look like this.

For more details, please refer to the article Excel VBA, Gradient’s Colors

Example 8: Color Patterns

Using VBA, you can also apply various patterns to cells in Excel. The patterns available can be seen in the snapshot below (Right click on a Cell > Format Cells > Fill tab > Pattern Style):

The pattern of a cell can be changed using the xlPattern enumeration. The code below changes the pattern of cell A1 to the checker pattern:


range("A1").Interior.Pattern = XlPattern.xlPatternChecker

Result:

You can also change the color of the pattern using the code below:

Range("A1").Interior.PatternColor = vbBlue

 

Result:

You can get a complete list of the XlPattern Enumeration in Excel here.

To get the index (as specified in the link above) of the pattern applied in a cell use:

MsgBox Range("A1").Interior.Pattern

It will display 9 for the checker pattern that we have applied earlier

For more details, refer to the article Excel VBA, Fill Pattern

The post Excel VBA Color Index: Complete Guide to Fill Effects and Colors In Cells appeared first on Software Solutions Online.

]]>
http://software-solutions-online.com/excel-vba-color-index-complete-guide-fill-effects-colors-cells/feed/ 0
How to Copy Rows to Other Worksheets Using Selection Criteria http://software-solutions-online.com/copy-rows-worksheets-using-selection-criteria/ http://software-solutions-online.com/copy-rows-worksheets-using-selection-criteria/#respond Fri, 20 Oct 2017 20:54:10 +0000 http://software-solutions-online.com/?p=11090 Introduction During your day-to-day use of Excel, you might end up needing to copy row data from one worksheet to another worksheet. To allow greater flexibility for a user to choose which worksheet the row data is to be copied to, we will introduce a

The post How to Copy Rows to Other Worksheets Using Selection Criteria appeared first on Software Solutions Online.

]]>
Introduction

During your day-to-day use of Excel, you might end up needing to copy row data from one worksheet to another worksheet. To allow greater flexibility for a user to choose which worksheet the row data is to be copied to, we will introduce a selection criteria technique in this tutorial.

Scenario:

Suppose the user has a workbook which contains 5 worksheets with names “DATA”, “FUEILOIL”, “GASOIL”, ULSD” and “KERO” respectively. The “Data” worksheet is a master sheet which contains all relevant data rows to be copied to other sheets, while “FUEILOIL”, “GASOIL”, ULSD” and “KERO” worksheets are recipient sheets to receive these data rows.

The key focus in this tutorial, is to make use of a copy-to-destination criterion column G on “DATA” worksheet, to let the user indicate which worksheets should the corresponding data rows be copied to. After the user inputs the criterion worksheet names manually under column G, the job will get done by means of VBA code.

Before we proceed, have a look below at what our “Data” worksheet looks like. Here we assume all 5 worksheets share the same headers “Order No.”, “Date”, ”Item”, ”Price”, “Quantity” and “Notes” from A1:F1, except that there is 1 extra column header named “Copy-To-Criterion ( Worksheet Name )” on “Data” worksheet.

  • Worksheets(“DATA”)

  • Worksheets(“FUELOIL”)

 


Sub CopyRow_UponCriteria()
 Application.ScreenUpdating = False
 Application.CutCopyMode = False
 Dim ws As Worksheet
 Dim src_ws As Worksheet
 Dim Cell As Range
 Dim wsName As String
 Set src_ws = Worksheets("DATA")
 eRow_src = src_ws.Range("G" & Rows.Count).End(xlUp).Row
 For r = eRow_src To 2 Step -1
 With src_ws
 If .Cells(r, 7).Value <> "" Then
 wsName = .Cells(r, 7).Value
 eRow = Worksheets(wsName).Range("A" & Rows.Count).End(xlUp).Row
 .Range(.Cells(r, 1), .Cells(r, 6)).Copy Worksheets(wsName).Range("A" & eRow + 1)
 .Range(.Cells(r, 1), .Cells(r, 6)).EntireRow.Delete
 End If
 End With
 Next
 Application.CutCopyMode = True
End Sub

VBA Code Analysis:

#002 This ScreenUpdating line intends to speed up the VBA execution efficiency by turning off the screen updating feature of Excel. This is particularly useful when the data rows to be copied are gigantic in amount.
#003 By turning off CutCopyMode, it avoids the user to view the strange dotted line triggered during the Excel-copying process
#008 Here an object variable named “src_ws” is used to refer to worksheets(“DATA”) object.
#009 Here an number variable named “ eRow_src” is used to store the row number of the last occupied cells under column G on worksheets(“DATA”). This prepares for our looping later on.
#010 The for-loop here starts with last occupied row under column G first, and then loop backward to the initial row 2 by using Step -1. At first glance, it may seem oddly to some but the reason behind is justifiable. As in this task, we would also delete the whole data row after it has been successfully copied to other worksheets. This deletion process, however, will trigger any other untouched rows beneath to move upwards. In this way, the originally pattern of destined row numbers for VBA to loop through will be disrupted, if we deem to loop in a normal forward approach. To avoid it, looping backward can be one of the solutions.
#012 The line is to make sure that the criterion range does not contain empty worksheet name. Row-copying process will then activate as long as the criterion cell under column G is not text-empty.
#014 The line intends to setup a number variable named “eRow” to retrieve the row number of last occupied cell in corresponding recipient worksheet. This helps to locate the next row number the data row should be copied to later.
#015 The line makes use of 2 embedded cell objects within a range object, to limit the column of a targeted copy row from column A to F. ( Hint: In Excel, column A takes a numeric column value of 1, while column F takes a numeric column value of 6). After that, a copy method is introduced to copy the current row under looping. The right hand side of the copy method contains a destination parameter to let VBA identify which worksheet, and which cell or row should the copied data row be pasted to. As you can see, eRow has to be added up by 1, such that a new blank row is ready to be received the copied data row.
#016 After the data row is copied, we use EntireRow to extend our current row from column A – F to the truly entire row to be deleted. Without doubt, during our coding on #15, we can also extend our range to be copied using EntireRow. However, we simply do not do so because of efficiency consideration, i.e. our table only contains a few headers.
#020 After the looping finishes it job, we then let the dotted line for normal Excel copying back to its normal visibility.

Attached below are pictures of finished screenshots.

  • Worksheets(“DATA”)

  • Worksheets(“FUELOIL”)

  • Worksheets(“GASOIL”)

Conclusion:

As a quick re-cap, the pivotal key in this tutorial is to introduce a column for the user to decide and input manually which worksheets are for the relevant data rows to be transmitted. On the realm of VBA coding, as there will be row deletion after the data row is successfully copied, we have to utilize the approach of a backward for-loop to avoid complications during row deletion. And always remember to check whether we should add extra 1 row for the destination to be copied to.

Related References:

If you would like to further advance the manipulation of worksheets objects in Excel VBA, such as different ways of worksheet referencing, creation, naming, copying, insertion, etc., you may visit our other link in the following: http://software-solutions-online.com/excel-vba-working-with-sheets/

If you are to retrieve data from another workbook, instead of within a worksheet, you may integrate the techniques from this tutorial with the following:

http://software-solutions-online.com/excel-vba-get-data-from-another-workbook-through-automation/

The post How to Copy Rows to Other Worksheets Using Selection Criteria appeared first on Software Solutions Online.

]]>
http://software-solutions-online.com/copy-rows-worksheets-using-selection-criteria/feed/ 0