Posts

Showing posts from 2014

Get the Values of all SPAN Elements with the same Class Name using jQuery

I am using the snippet below on one of my blogs in blogger to dynamically get the classname of a span element which contains a text of the post ID of the entry and process the iframe tags within that element. $(document).ready(function(){ $.each($('span.post-id'),function(i,v){ var s = $(this).text(); getiFrame(s); //this is a separate function to process iframe tags. }); });

How to Extract Data From HTML (.aspx) website into Excel using VBA

Image
In this example I used the following VBA code to extract the data stored in a script variable. You can see the example data from an HTML file at the end of this post. Below is the snapshot of the page that I was trying to extract data from. VBA CODE: '******************************************************** ' DESCRIPTION: GET DATA FROM TABLE OF A .ASPX WEBSITE ' BY: CROMWELL D. BAYON ' EMAIL: OMELSOFT@GMAIL.COM '******************************************************** Sub GetOfflineData() Dim file As String, Data As String Dim delimQ As String Dim lineContentLoc As Long delimQ = Chr(34) file = Application.ActiveWorkbook.Path & "\Source of Select.html" Open file For Input As #1 Do Until EOF(1) Line Input #1, linefromfile 'Check only the line containing this pattern (var best_idear_data =[) If InStr(1, linefromfile, "var best_idear_data =[...

Count number of occurrence in a string using Excel VBA.

The following code snippet allows you to get the number of text occurrences in a string using VBA in Excel. Function StringCountOccurrences(strText As String, strFind As String, _                                 Optional lngCompare As VbCompareMethod) As Long Dim lngPos As Long Dim lngTemp As Long Dim lngCount As Long     If Len(strText) = 0 Then Exit Function     If Len(strFind) = 0 Then Exit Function     lngPos = 1     Do         lngPos = InStr(lngPos, strText, strFind, lngCompare)         lngTemp = lngPos         If lngPos > 0 Then             lngCount = lngCount + 1             lngPos = lngPos + Len(strFind)         End If     Loop Until lngPos = 0     StringCountOccurrences = lngCount End Functi...

How to detect Scroll position of a webpage using jQuery's .scrollTop()

The .scrollTop() function in jQuery allows you to get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element. You can extract the scroll position of a certain page or element using the jQuery's .scrollTop() method . $(window).scroll(function (event) { var scroll = $(window).scrollTop(); // Do something }); You can also determined the percentage and alert the user that he has scrolled certain amount within the document. >$(document).scroll(function(e){ // get the scroll value and the document height var scrollVal = $(window).scrollTop(); var docHeight = $(document).height(); // calculate the percentage when the user scrolls down the page var percentage = (scrollVal / docHeight) * 100; if(percentage > 50) { // call the function called alertUser alertUser(percentage); } function alertUser(scr...

How to Add an Adsense Code Manually into Blogger Template

Image
In this article you'll be able to learn on how to Add an AdSense Code manually into blogger template. If you have an AdSense Account and wanted to setup a blog using blogger. You can however incorporate your approved email account with AdSense in which blogger creates the widget and automatically insert your adcode in between, before or after each posts. You can find anywhere in the web on how to do this thing but here I'm going to give you the instructionswith ease. Let's take a look at the layout below. What we're going to do is put an AdSense code in the green square with "your add here" caption. And we only wanted it to appear on items and or blog posts. 1 On your Blogger's dashboard, Click the Template  then Click "Edit HTML" . 2 Click anywhere on the Template editor window and Press Ctrl+F  then type the following b:widget id='Blog1' in the search box and press Enter. You should see similar to the image below. Within the ...

VB.Net Print PDF Document

Image
Portable Document Format ( PDF ) is a file format used to present documents in a manner independent of application software, hardware, and operating systems. Each PDF file encapsulates a complete description of a fixed-layout flat document, including the text, fonts, graphics, and other information needed to display it. In some applications, web or desktop there are several options where you can convert or Print a PDF version of a form or document you're reading. So, the question is how is it done and is it possible to create your own PDF document from scratch? We'll you're still lucky as I am. In this tutorial you'll be able to learn on how can VB.Net Print PDF Documents . Requirements 1.) CodePlex.com provides a freely downloadable version of the PDFSharp-MigraDocFoundation-Assemblies . 2.) Extract the downloaded .zip file to your project folder. The file name if not updated is PDFsharp-MigraDocFoundation-Assemblies-1_31.zip. Creating the Project 1.) S...

Formatting Date and Time VB.NET

The Date literal must be enclosed within number signs ( #date# ) and specify the date value in the format M/d/yyyy like #09/06/2014# . Else, the way how your code is interpreted may vary depending on the locale in which your application is deployed. With this requirement the meaning of your code should never change whether if it has a different date and time format settings. For example, you hard-coded a Date literal of #9/6/2014# which means September 6, 2014. That will compile 9/6/2014 as you want mm/dd/yyyy. However, if you deploy application in several locales using dd/mm/yyyy date format, your hard-coded literal would compile to June 9, 2014. For other locales using yyyy/mm/dd, the literal would be invalid causing compilation error. To convert a Date literal to the format of your locale or to a custom format, use the Format function of String class, specifying either a predefined or user-defined date format. Predefined Date/Time Formats The following table identifies the ...

Working with Date and Time VB.Net

VB.NET's DateTime structure represents an instant in time which is commonly expressed as a particular date and time of the day. It's a part of your daily life while creating your applications which makes it easy for you to manipulate system's date and time. In this article I'll be showing you the commonly used properties and methods and example usage of the Date and Time in VB.Net. Use the Date data type to contain date values, time values, or date and time values. The default value of Date is 0:00:00 (midnight) on January 1, 0001. You can get the current date and time from the DateAndTime class. DateTime Properties The table below shows some of the commonly used properties of the DateTime Structure: Property Description Date Gets the date component of this instance. Day Gets the day of the month represented by this instance. DayOfWeek Gets the day of the week represented by this instance. DayOfYear Gets the day of the year represented by this instance. H...

Commonly Used VBA Statements for Excel VBA Programming

Image
The following table shows a list of commonly used VBA statements that might be useful when creating macros for your Excel projects. To know more information about each statement, consult Excel’s Help system by pressing "F1".

Remove and Replace All Characters in Microsoft Excel using VBA

The following FindandReplace() function allows you to replace or remove specific text and characters you want in Microsoft Excel. Just copy the code below on your VBA code class or module. Sub FindandReplace(FindWhat as String, ReplaceWith as String)         Cells.Replace What:=FindWhat, Replacement:=ReplaceWith, LookAt:=xlPart, SearchOrder:= _         xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False End Sub Put this in your Sub or Function. To Replace several text with new text. FindandReplace "OldText", "NewText" To remove several text just leave the second argument blank. FindandReplace "OldText", ""

How to Minimize/Send an App Icon to System Tray in Visual Basic 6

The following code snippet allows to manipulate the system tray by adding your apps icon when you minimize the form and restore when you double click on the app's icon on the system tray area. Option Explicit Public Type NOTIFYICONDATA cbSize As Long hWnd As Long uId As Long uFlags As Long uCallBackMessage As Long hIcon As Long szTip As String * 64 End Type Public Const NIM_ADD = &H0 Public Const NIM_MODIFY = &H1 Public Const NIM_DELETE = &H2 Public Const WM_MOUSEMOVE = &H200 Public Const NIF_MESSAGE = &H1 Public Const NIF_ICON = &H2 Public Const NIF_TIP = &H4 Public Const WM_LBUTTONDBLCLK = &H203 'Double-click Public Const WM_LBUTTONDOWN = &H201 'Button down Public Const WM_LBUTTONUP = &H202 'Button up Public Const WM_RBUTTONDBLCLK = &H206 'Double-click Public Const WM_RBUTTONDOWN = &H204 'Button down Public Const WM_RBUTTONUP = &H205 'Button up Public Declare Function Shel...

How to Set Windows Form Always on Top of Other Applications in VB6

The following code snippets allows to set Windows Form Always on Top of Other applications in Visual Basic 6.0. Public Const SWP_NOMOVE = 2 Public Const SWP_NOSIZE = 1 Public Const FLAGS = SWP_NOMOVE Or SWP_NOSIZE Public Const HWND_TOPMOST = -1 Public Const HWND_NOTOPMOST = -2 Declare Function SetWindowPos Lib "user32" _ (ByVal hWnd As Long, _ ByVal hWndInsertAfter As Long, _ ByVal x As Long, _ ByVal y As Long, _ ByVal cx As Long, _ ByVal cy As Long, _ ByVal wFlags As Long) As Long The following SetTopMostWindow() function takes two parameters as follows:       hWnd : the window handle       Topmost : It is either True to set the on top or False if Not. Public Function SetTopMostWindow(hWnd As Long, Topmost As Boolean) As Long If Topmost = True Then 'Make the window topmost SetTopMostWindow = SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, FLAGS) Else SetTopMostWindow = SetWindowPos(hW...

How to Make Windows Form Transparent using Visual Basic 6/VB6

The following code snippets allows you to make windows form transparent using VB6. In a standard module, copy and paste the following declarations and function. [ Module1.bas ] Option Explicit Const LWA_COLORKEY = 1 Const LWA_ALPHA = 2 Const LWA_BOTH = 3 Const WS_EX_LAYERED = &H80000 Const GWL_EXSTYLE = -20 Private Declare Function SetLayeredWindowAttributes Lib "user32" (ByVal hWnd As Long, ByVal color As Long, ByVal x As Byte, ByVal alpha As Long) As Boolean Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As Long Private Declare Function WindowFromPoint Lib "user32" (ByVal xPoint As Long, ByVal yPoint As Long) As Long Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAP...

Internet Connection Speed Booster

Image
Internet Speed Booster is a simple tool that can be used to reset internet connection, flush DNS resolver cache, and renew dynamic IP addresses. This tool allows online and massive gamers to feel like a boss in the games arena. This tool primarily solves the problem if you're having limited connectivity or frequent disconnection from the internet. Internet Speed Booster is just right for you for FREE. Internet Speed Booster is available for free download .

How to Get the Count of Filtered Sets of Data Rows in Excel using VBA

Image
The following function below allows you to get the number of visible rows from a filtered sets of rows in Excel using VBA. The function takes two arguments which is the Column and StartRow. Calling the FilterCount() function returns the number of visible rows. Also added an error handler which process the error description to determine if there's a visible row. Parameters: Column : The column of the data to be filtered. If you have multiple columns being filtered you can just set the first Column or any column in the dataset.         StartRow : Start row of the data to be filtered. Function FilterCount(ByVal Column As String, ByVal StartRow As Long) As Long     On Error GoTo errHandler       FilterCount = Application.WorksheetFunction.CountA(ActiveSheet.Range(Column & StartRow, Cells(ActiveSheet.UsedRange.Rows.Count, Range(Column & StartRow).Column)).SpecialCells(xlCellTypeVisible))     'Debug.Print FilterC...

How to Copy Only the Visible Rows of a Filtered Data in Excel using VBA

Image
You might be working on a project where you need to filter sets of data and create a raw data of that filtered sets of data to a new sheet or range. By default, Excel copies hidden or filtered cells in addition to visible cells. If some cells, rows, or columns on your worksheet are not displayed, you have the option of copying all cells or only the visible cells.  The following snippet allows you to automate the process in microseconds. [ VBA ] Public Function GetFilteredData() Dim rawWs As Worksheet 'RAW DATA WORKSHEET Dim tarWs As Worksheet 'TARGET WORKSHEET 'Replace this with your actual Worksheets Set rawWs = Sheets("Raw Data") Set tarWs = Sheets("Filtered Data Visualizations") Application.ScreenUpdating = False 'Clear old contents of the Target Worksheet tarWs.Range("A2:N" & Rows.Count).ClearContents '****************************************...

How to Get the Addresses of Visible Rows from a Filtered Data in Excel using VBA

Image
The following function allows you to get the Address of each visible rows from a filtered sets of data in Excel using VBA. [ VBA ] Dim FilteredRows as Variant Public Function GetFilteredRows(Optional ByVal RowPrefixed As Boolean) Dim Rng As Range, rngF As Range, rngVal As Range 'Ranges Dim val As Variant 'Range Value Dim i As Integer 'Counter Dim lRow as long 'Last Row Application.ScreenUpdating = False Sheets("Raw Data").Select lRow = WorksheetFunction.CountA(Range("A:A")) 'Set the range of all visible cells of the filtered data Set rngF = Range("A2", Cells(ActiveSheet.UsedRange.Rows.Count, _ Range("A2").Column)).SpecialCells(xlCellTypeVisible) For Each Rng In Range("$A2:$A$" & lRow) If Not Intersect(Rng, rngF) Is Nothing Then If rngVal Is Nothing Then Set rngVal = Rng Else ...

How to Populate Data from Textbox to Datagridview in C#/CSharp

Image
The following example allows you to populate data from a TextBox to DataGridView Control in C#/CSharp. using System; using System.Collections.Generic; using System.Windows.Forms; namespace TextBoxToDataGridView { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { DataGridView dgv = this.dataGridView1; //SET DATAGRIDVIEW PROPERTIES dgv.AutoGenerateColumns = false; dgv.AllowUserToAddRows = false; dgv.RowHeadersVisible = false; dgv.MultiSelect = false; //SETS UP THE COLUMN HEADERS dgv.Columns.Add("FName", "First Name"); dgv.Columns.Add("LName", "Last Name"); dgv.Columns.Add("Age", "Age"); } private void btnAdd_Click(object sender, Event...

Populate Website Directory Listing into ListView Control using C#/CSharp

Directory listings are just HTML pages generated by a web server. Each web server generates these HTML pages in its own way because there is no standard way for a web server to list these directories.  The web server you'd like to list directories from must have directory browsing turned on to get this HTML representation of the files in its directories. So you can only get the directory listing if the HTTP server wants you to be able to. [C#] using System; using System.IO; using System.Net; using System.Text; using System.Windows.Forms; using System.Text.RegularExpressions; namespace DirectoryListing { public partial class frmMainDownloader : Form { public frmMainDownloader() { InitializeComponent(); } public static string GetDirectoryListingRegexForUrl(string url) { return "<a href=\".*\">(?<name>.*)</a>"; } private void btnFetchUrl_Click(object ...

Populate Data into DataGridView using DataTable in C#/CSharp

The following snippet allows to populate data into DataGridView Control using DataTable in CSharp. First, we establish a connection to our database. string sConnect = "Data Source=" + Properties.Settings.Default.Server + ";Initial Catalog=" + Properties.Settings.Default.Database + ";"; if (Properties.Settings.Default.UseIntegratedSecurity) sConnect += "Integrated Security=SSPI;"; else sConnect += "User Id=" + Properties.Settings.Default.Username + ";Password=" + Properties.Settings.Default.Password + ";"; this.sSQLConnectString = sConnect; This DataTable returns the Books Table. public DataTable GetBooks() { string sql = "select * from Book order by ISBN13, ISBN10"; SqlDataAdapter da = new SqlDataAdapter(sql, sqlConnection); try { DataTable dt = new DataTable(); da.Fill(dt); return dt; } catch (Exception ex) { throw ex; ...

How to Kill or Start a New Background Process in C#/Csharp

The following snippet allows you to check if a process is already running in the background. If the process is already running it will prompt the user to whether start a new process or continue with the existing one that is running.         private void checkForDataInProgress()         {             if (!this.bConnectedToDatabase)                 return;             Process proc = new Process();             string sNumThreads = Properties.Settings.Default.NumberOfLocalThreads.ToString();             string sProcArgs = "\"" + this.sSQLConnectString + "\" \"" + Properties.Settings.Default.XMLSaveDir + "\" \"" + Properties.Settings.Default.DLLDir + "\" " + sNumThreads;             proc.StartInfo = new ProcessStartInfo(Properties.Settings.Default.DataImporterAp...

Handle Keypress Event on a Search Box in jQuery

Image
I have this problem before when I tried to search a keyword from a database using jQuery-AJAX-PHP. Where in the query is fired up multiple times which slows down process. After searching reading various solution for this problem. I've came up with the jQuery function below. This handles the keypress event of the textbox with an id keyword . $('#keyword').live('keypress', KeywordSearch); Javascript Function: function KeywordSearch(event) { if (event.handled !== true) { if (event.keyCode == 13){ var type = $('#searchType').val(); var keyword = $('#keyword').val(); var result = $.ajax({ type: "GET", url: "search.php?keyword=" + keyword + "&type=" + type, async: false}).responseText; $('#results').html(result); $('#myTable').fadeIn('fast'); event.handled = true; event.preventDefault(); } } }

How to Suppress Warning and Alerts in Excel using VBA

Image
In Microsoft Excel, you can suppress the message warning and alerts especially when you try to create a copy of a worksheet from a workbook containing macros to a new workbook which you wanted to save it as .xls or .xlsx extensions. By that, when you save the document it will prompt you to whether save the work as macro-enabled or macro-free workbook. You can do that by setting DisplayAlerts to False with VBA code. Application.DisplayAlerts = False 'DO SOME TASKS HERE Application.DisplayAlerts = True

How to Create a Custom Checkbox using only the Cells in Microsoft Excel

Image
You might be creating templates with Microsoft Excel, and one of the feature you want is add a check boxes control where users can choose their option.  We'll, if you want to have another look aside from the default check box control. You can still create and customize your check box controls with a little VBA code to get it done. In this example, I have here choices for the reason of a leave application form. I make use of the Microsoft Excel's Cell as a check box. It's just a matter of resizing the rows and columns to make the size of the cell equal.  1.)  Now, let's create first the list of choices, as you can see below I've resized the cells and add borders on the cells which we'll set as a check-cell box control. 2.)  Right Click on the Worksheet, then Click " View Code ". 3.)  Then Copy and Paste the following codes below into the code editor window. The following code will set the Target Range of when the Check-Cell box will be...

Load Data of DataGridView's Selected Row to TextBox Control in C#/CSharp

Image
The following example loads the data of the Selected Row in a DataGridView control into a TextBox control in CSharp. As shown on the previous example  Populate Data Into DataGridView using For-Loop in C#/CSharp , we'll use that method to fill our DataGridView with data. To begin with: 1.) Start start a new C# project. 2.) Add the following controls onto Form1. (1) DataGridView Control (2) TextBoxes (2) Labels 3.) Open the Windows Form Designer and Update the DataGridView's generated code with the following. // // dataGridView1 // this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Location = new System.Drawing.Point(12, 12); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.Size = new System.Drawing.Size(240, 221); this.dataGridView1.TabIndex = 0; this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellC...

Populate Data Into DataGridView using For-Loop in C#/CSharp

Image
The following example will populate data into a DataGridView Control using For-Loop. To begin with: 1.) Create a new C# Project. 2.) Add a DataGridView Control onto Form1. 3.) Then copy the code below and paste on Form1_Load() event. Random rand = new Random(); DataGridView dgv = this.dataGridView1; //DATAGRIDVIEW SETTING dgv.AllowUserToAddRows = false; dgv.RowHeadersVisible = false; dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect; //ADD COLUMN HEADERS dgv.Columns.Add("Product", "Product"); dgv.Columns.Add("Price", "Price"); //ADD 10 ROWS dgv.Rows.Add(10); //NOW, POPULATE THE DATA INTO THE CELLS for (int i = 0; i < 10; i++) {     double price = rand.Next(1, 30) * rand.NextDouble();     dgv.Rows[i].Cells[0].Value = "Product " + i;     dgv.Rows[i].Cells[1].Value = "$ " + price; } //CLEARS THE DEFAULT SELECTION WHICH IS THE FIRST ROW dgv.ClearSelection(); 4.) Build and Comp...

Using Named Ranges in Microsoft Excel

Image
Named Ranges in Excel enable you to give one, or a group of cells a name other than the default B4 for a single cell, or B2:E20 for a range of cells. So that you can refer to them in formulas using that name. You can view the complete tutorial here How to Use Named Ranges in Microsoft Excel  . When using Named Ranges there are also set of rules which you need to know like the scope where you can use the specified named range. If it's within only a single worksheet or the entire workbook. Check this out Named Range Rules  and be totally aware of the do's and don'ts when using this functions. Managing Your Named Ranges There'll come a time when you want to edit or delete a Named Range. To do this access the Name Manager on the Formulas tab of the ribbon. The Name Manager Dialog box will open. From here you can Edit and Delete your Named Ranges, or even create new ones. Remember, once you delete a name you cannot undo that action. Different uses fo...