Tuto
Tuto
When we import the data we are importing to a worksheet range on the Import sheet that is being referenced by a
dynamic named range to form the rowsource in our Userform.
That being the case we are going to need to create a dynamic named range for our import data.
Open the Name Manager and add this New named range.
Named range called: DataAccess
=OFFSET(Import!$A$1,1,,COUNTA(Import!$A$2:$A$10000),7)
Enabling a ADO
Hit ALT +F11 to open the VBA editor in Microsoft Excel and then also you can repeat this process in your Microsoft
Access program as well.
Click on Tools and then References, scroll down until you find Microsoft ActiveX Data Objects.
Click on the latest available library as shown in the illustration below.
Make sure that you name the text boxes and command buttons are exactly as shown in the video above. Failures to
do this will result in our code throwing an error.
13 Labels
8 Textboxes (Arec1 to Arec7) (txtSearch)
3 Command Buttons (cmdAdd,cmdImport,cmdClose)
1 Checkbox (do not rename)
1 Listbox (lstDataAccess)
Userform Close
This is the code for the close button on our Userform.
Private Sub cmdClose_Click()
Unload Me
End Sub
Enabling a ADO
See previous tutorial
Code to Delete
You will notice again in this procedure that we are referencing our ID field. This is for the reason given above.
Private Sub cmdDelete_Click()
'Declaring the necessary variables.
Dim cnn As ADODB.Connection 'dim the ADO collection class
Dim rs As ADODB.Recordset 'dim the ADO recordset class
Dim dbPath As String
Dim i As Integer
Dim x As Integer
'add error handling
On Error GoTo errHandler:
If Me.Arec1.Value = "" Then
MsgBox "You must enter a valid ID number.", _
vbOKOnly Or vbInformation, "Insufficent data"
Exit Sub
End If
'get the path to the database
dbPath = Sheet1.Range("I3").Value
Set cnn = New ADODB.Connection ' Initialise the collection class variable
'Connection class is equipped with a —method— named Open
'—-4 aguments—- ConnectionString, UserID, Password, Options
'ConnectionString formula—-Key1=Value1;Key2=Value2;Key_n=Value_n;
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
Set rs = New ADODB.Recordset 'assign memory to the recordset
'Create the SQL statement to retrieve the data from table.
rs.Open "SELECT * FROM PhoneList " & _
"WHERE ID = " & CLng(Me.Arec1), ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
Options:=adCmdText
If rs.EOF And rs.BOF Then
'Close the recordet and the connection.
rs.Close
cnn.Close
'clear memory
Set rs = Nothing
Set cnn = Nothing
'Enable the screen.
Application.ScreenUpdating = True
'In case of an empty recordset display an error.
MsgBox "There are no records in the recordset!", vbCritical, "No Records"
Exit Sub
End If
'delete the record set
rs.Delete
'clear the userform values
For x = 1 To 7
Me.Controls("Arec" & x).Value = ""
Next
'Close the recordset and the connection.
rs.Close
cnn.Close
'clear memory
Set rs = Nothing
Set cnn = Nothing
'Enable the screen.
Application.ScreenUpdating = True
'refresh the listbox
ImportUserForm
'set the rowsourse
Me.lstDataAccess.RowSource = "DataAccess"
'Inform the user that the macro was executed successfully.
MsgBox "Congratulation the data has been deleted", vbInformation, "Deletion successful"
'error handler
On Error GoTo 0
Exit Sub
errHandler:
'clear memory
Set rs = Nothing
Set cnn = Nothing
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Import_Data"
End Sub
1. View Data
2. Sort Data
3. Filter Data
4. Delete Records
5. Add Records
6. Update Data in Existing Record
7. Show Unique Values
8. Write an expression to generate new column
9. LookUp data from another table
10. Pivot Table
To perform operations listed above, I’ll use the data listed below (Employee)\:
1. View Data
In excel, we can view all the records directly. But, SQL requires a command to process this
request. This can be done by using SELECT command.
Syntax:
Exercise:
2. Sort Data
Organizing information becomes important when you have more data. It helps to generate
quick inferences. You can quickly organize an excel worksheet by sorting your data in
ascending or descending order.
Syntax:
3. Filter Data
In addition to sorting, we often apply filter to analyze data in a better way. When data is
filtered, only rows that meet the filter criteria is displayed while other rows get hidden. Also,
we can apply multiple criterion to filter data.
Syntax:
Below are the common list of operators, we can use to form a condition.
Operator Description
= Equal
Exercise:
4. Delete Records
Deleting records or columns is a commonly used operation in Excel. In excel, we simply
press ‘Delete’ key on keyboard to delete a record. Similarly, SQL has command DELETE to
remove records from a table.
Syntax:
DELETE FROM table_name WHERE some_column=some_value;
Exercise:
It removes two record only since these two observations satisfy the condition stated above.
But be careful! if we do not provide any condition, it will remove all records from a table.
Above command will remove only one record which satisfies the condition.
5. Add records
We have seen methods to remove records, we can also add records to SQL table as we do
in excel. INSERT command helps to perform this operation.
Syntax:
OR,
INSERT INTO table_name (column1,column2,column3,…) VALUES
(value1,value2,value3,…); -> Insert values to selected columns
Exercise:
12',0.8,'Female','Admin',12.05,26,313.3,'Mumbai');
Syntax:
Syntax:
B. Create a new column City_Code which has first three characters of City.
For more details on SQL functions, I would recommend you to refer this link.
SQL JOIN is used to combine rows from two or more tables, based on a common field
between them. It has multiple types:
INNER JOIN: Return rows when there is a match in both tables
LEFT JOIN: Return all rows from the left table and the matched rows from the right
table
RIGHT JOIN: Return all rows from the right table and the matched rows from the left
table
FULL JOIN: Return all rows when there is a match in ONE of the tables
Syntax:
Exercise: Below is city category table “City_Cat”, now I want to map city category to
Employee.City = City_Cat.City;
To know more about JOIN operations, I would recommend you to refer this link.
10. Pivot Table
Pivot Table is an advanced way of analyzing data in excel. Not only it is useful, but it allows
you to extract the hidden insights from data.
Syntax:
Exercise:
City;
Add Progress Bar Macros
When your progress bar pops up, you don’t want the ugly title bar with the red X to show up,
right? I didn’t think so.
The IsMac check in this routine is what prevents the macro from crashing for users running
Excel on a Mac. Instead of the sleek UserForm without a title bar, they’ll see the title bar. In
other words, their Progress Bars won’t be as pretty as you Windows users, but that’s okay,
right!? ;)
This is where you may have to adapt the solution I provide into your own application. This
might require you to think outside the box a bit, but I’m confident you can do that!
The best way to show you how to include the progress bar in your macro is to give you a
demonstration and then walk you through the important pieces.
In this example, I loop through all the rows in my spreadsheet and update my progress bar
after each row. Here’s the sample macro (pay attention to the comment cards):
This sample has 3 important steps. These 3 steps are common whether or not your macro
uses a For loop like the one above.
At some point in your macro, you want to make your progress bar appear on your
screen.Chances are, you want to do this right after your macro starts to run. To do that, you
want to make sure the width of your progress bar is set to 0 at the beggining and then show
your UserForm. All you have to do is add the following lines to your macro, like I did in the
example above:
ufProgress.LabelProgress.Width = 0
ufProgress.Show
At some point, you want to update the length of your progress bar to indicate how far along
your macro is. That’s the point of a progress bar, right? In my example, I used a formula to
calculate what percentange of the way through the macro I was, based on which row I was
processing.Inside the loop, I included the following code:
pctdone = i / lastrow
With ufProgress
.LabelCaption.Caption = "Processing Row " & i & " of " & lastrow
.LabelProgress.Width = pctdone * (.FrameProgress.Width)
End With
DoEvents
Each time I get to a new row, I update the LabelCaption text and the width of
myLabelProgress label.
This is a great way to indicate progress if your macro consists of a loop where you know the
starting position and you know the ending position. Examples where a solution like the one
above will work are when you’re processing each line of data in a spreadsheet, or looping
through files in a folder.
When your macro is nearing completion, make sure you close your Progress Bar. In my
example, I closed the VBA Progress Bar UserForm when I got to the last row. I did that via
this line of code:
The progress bar will be made from 3 controls. 1 Frame control and 2 label controls.
The frame will be the border of the progress bar. It is the light grey box you can see above.
Then 1 labels will be used for the bar, and another label for the text showing the percentage
complete above the bar.
1. Switch to the Visual Basic Editor by pressing Alt + F11, or clicking the Developer tab and
then Visual Basic.
2. Click Insert and then Userform.
3. Using the Properties window (if the Properties window is not shown, click View > Properties
Window) enter a name and caption for your userform.
In the image below you can see that my userform is named Progress, and I have used the
caption of Macro Progress.
Using the Toolbox, we will now insert the three controls that we need. These controls will
also be named using the Properties window for each. The caption has been deleted for
each control.
4. Click the Frame button on the Toolbox, and click and drag to draw it onto the userform. I
have named my frame as Border. I have also enter the Width as 200 (this will be used later).
5. Click on the Label button and draw that inside the frame. This label will be the bar, so I have
named it Bar. Click the BackColor property and select a colour you wish to use for the bar.
The palette tab offers a good selection.
6. Click the Label button again and draw this one above the progress bar. This one will show the
percentage complete, so I have named it Text. I have ensured that it is aligned with the frame
below it.
Update the Progress Bar with the Macros Progress
Now that we have the physical bar on the userform (it does not look like much yet) we need
it to automatically change width as the macro progresses.
This macro is a simple one that loops through every row of a sheet and multiplies the value
in column 10 (column J) by 1.1. We do not care about this, it is just some code to keep the
macro busy so we can see the progress bar working correctly.
Sub ProgressBar()
Dim i As Long
Dim TotalRows As Long
Dim CurrentProgress As Double
Dim ProgressPercentage As Double
Dim BarWidth As Long
i=2
TotalRows = Application.CountA(Range("A:A"))
Call InitProgressBar
CurrentProgress = i / TotalRows
BarWidth = Progress.Border.Width * CurrentProgress
ProgressPercentage = Round(CurrentProgress * 100, 0)
Progress.Bar.Width = BarWidth
Progress.Text.Caption = ProgressPercentage & "% Complete"
DoEvents
i=i+1
Loop
Unload Progress
End Sub
Sub InitProgressBar()
With Progress
.Bar.Width = 0
.Text.Caption = "0% Complete"
.Show vbModeless
End With
End Sub
Call InitProgressBar
This macro is used to initialise the progress bar on the userform. It sets the bar width to 0,
the text to 0% and then most importantly shows the userform.
With Progress
.Bar.Width = 0
.Text.Caption = "0% Complete"
.Show vbModeless
End With
The userform is set to be modeless. This means that the user can interact with other parts
of the spreadsheet whilst the userform is open. Modal forms do not allow this.
We then calculate the progress through the macro, and what width the progress bar should
be at. This is entered inside the loop so after each row of the loop, the user is aware of the
macro progress.
CurrentProgress = i / TotalRows
BarWidth = Progress.Border.Width * CurrentProgress
ProgressPercentage = Round(CurrentProgress * 100, 0)
Progress.Bar.Width = BarWidth
Progress.Text.Caption = ProgressPercentage & "% Complete"
The CurrentProgress is calculated by dividing the current row number (i variable) by the total
number of rows. There are 12931 rows on this sheet. If you are at row 9523, then you do
9523/12931 which results in 0.736447 through the macro.
Once we know this we can find out what width the progress bar should be by multiplying the
width of the border by this value. I set the width of the frame control named Border to 200,
so this would be 200 * 0.736447. The answer of 147 is assigned to the BarWidth variable.
We then calculate the progress as a percentage by multiplying the CurrentProgress value
by 100. The ROUND function is used to round this figure to 0 decimals. This results is
assigned to the ProgressPercentage variable to be used for the Text label.
The width of the progress bar and caption for the text label are then set.
The final bit of code is then the DoEvents statement. This ensures that events can still occur
whilst the macro runs.
DoEvents
Option Explicit
Sub InsertHeaderFooter()
Format
code Description
&"fontname" Prints the characters that follow in the specified font. Be sure to include the double
quotation marks.
Format
code Description
&nn Prints the characters that follow in the specified font size. Use a two-digit number to
specify a size in points.
&color Prints the characters in the specified color. User supplies a hexadecimal color value.
&"+" Prints the characters that follow in the Heading font of the current theme. Be sure to
include the double quotation marks.
&"-" Prints the characters that follow in the Body font of the current theme. Be sure to
include the double quotation marks.
&K xx. S nn Prints the characters that follow in the specified color from the current theme.
n
xx is a two-digit number from 1 to 12 that specifies the theme color to use.
S nnn specifies the shade (tint) of that theme color. Specify S as + to produce a lighter
shade; specify S as - to produce a darker shade.
If the values that specify the theme color or shade are not within the described limits,
Excel will use the nearest valid value.