VBA – Loop Through All (.txt) Files in a User Specified Directory – Excel Macro

This VBA code will loop though all the text files in a directory that user picks from an application box and print a list of them. This code can be modified to be used in many scenarios for any file type.

 

Sub LoopThroughAllTextFilesInFolder()

    'Declarations
        Dim wb As Workbook
        Dim DirPath As String
        Dim FileName As String
        Dim FileExt As String
        Dim UserFolderChoice As FileDialog
        Dim i As Integer
        Dim howmany As Integer
    'Declarations End

    'Regular Stuff
        Application.ScreenUpdating = False
        Application.EnableEvents = False
        Application.Calculation = xlCalculationManual
    'Regular Stuff End

    'User's Folder Choice
        Set UserFolderChoice = Application.FileDialog(msoFileDialogFolderPicker)

        With UserFolderChoice
          .Title = "Select A Target Folder"
          .AllowMultiSelect = False
            If .Show <> -1 Then GoTo AllGood
            DirPath = .SelectedItems(1) & "\"
        End With
    'User's Folder Choice End

AllGood:

    'Check if path is empty
      If DirPath = "" Then GoTo JumpToEnd

    'File Extension
      FileExt = "*.txt"

    'Let's find the first file & how many total files we have
      FileName = Dir(DirPath & FileExt)
      howmany = Len(Dir(DirPath & FileExt))

        'let's loop though them
            For i = 1 To howmany

                'print the name of the file
                Debug.Print FileName

                'move to the next file
                FileName = Dir
            Next i

'Done!!!

JumpToEnd:

    'Regular Stuff
        Application.EnableEvents = True
        Application.Calculation = xlCalculationAutomatic
        Application.ScreenUpdating = True
    'Regular Stuff End

End Sub

Posted by Excel Instructor:
http://www.chicagocomputerclasses.com/excel-classes/

VBA – Get Information From a Web Page – Excel Macro – Amazon Example

This is a basic VBA code to get started with InternetExplorer.Application object and work with web browsers and data extraction. This code is written strictly for learning proposes and should be used as such. Everything is well commenced out so it should be really easy to understand. In this example we use Internet Explorer to open a product page on Amazon and we extract the page title & product price and add the data to our spreadsheet.

 

Sub Basics_Of_Web_Macro()

    Dim myIE As Object
    Dim myIEDoc As Object

    'Start Internet Explorer
    Set myIE = CreateObject("InternetExplorer.Application")

    'if you want to see the window set this to True
    myIE.Visible = False

    'Now we open the page we'd like to use as a source for information
    myIE.Navigate "http://www.amazon.com/gp/product/B00J34YO92/ref=s9_ri_gw_g421_i1?pf_rd_m=ATVPDKIKX0DER&pf_rd_s=desktop-3&pf_rd_r=090F56JZ7KPTB48JWMDW&pf_rd_t=36701&pf_rd_p=2090151042&pf_rd_i=desktop"

    'We wait for the Explorer to actually open the page and finish loading    
    While myIE.Busy
        DoEvents
    Wend

    'Now lets read the HTML content of the page        
    Set myIEDoc = myIE.Document

    'Time to grab the information we want            

        'We'll start with the Title of the page        
        Range("A1") = myIEDoc.Title
        'Then we'll get something from teh inner page content by using the ID        
        Range("B1") = myIEDoc.getElementById("priceblock_ourprice").innerText

End Sub

Posted by Excel Instructor:
http://www.chicagocomputerclasses.com/excel-classes/

Excel Tutoring

Microsoft Excel Class – Advanced

VBA – Get All Numbers in a Text String & Incresae by One – Excel Macro

The following procedure will take any numbers within text and increase them by 1.

For Example:
For20Example51Text will transform into For21Example52Text

 

Sub UpNumbersByOne()

cell = "YOUR16STRING1HERE10"

Dim v As Variant
 endresult = ""

With CreateObject("VBScript.RegExp")
    .Pattern = "(\d+|\D+)"
    .Global = True
        v = Split(Mid(.Replace(cell, "|$1"), 2), "|")
        For Each num In v
        If IsNumeric(num) = True Then
        num = num + 1
        End If
        endresult = endresult & num
        Next num
End With

Debug.Print endresult

End Sub

Posted by Excel Instructor:
http://www.chicagocomputerclasses.com/excel-classes/

VBA – Get First Number & Then Text & Following Number – Excel Macro

This Excel Macro will transform the text data placed in column A and Break it down into 3 Columns.

Data Format Required:
15654 Text goes Here 16 2 6 1595
1 Different Text 1 6
number (space) text of any lenght (space) number (space) other characters

Output will return:

  1. First column: full first number
  2. Second column: full text string in the middle of surrounded numbers
  3. Third Column: first full number after text
Sub BreakTextNum()
lr = ActiveSheet.Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row
    For Each cell In Range("a1:a" & lr)

    'grab teh number
    num = Left(cell, InStr(cell, " ") - 1)

    'grab teh text
        For i = 1 To Len(cell)
            Dim currentCharacter As String
            currentCharacter = Mid(cell, InStr(cell, " ") + i, 1)
            If IsNumeric(currentCharacter) = True Then
                GetPositionOfFirstNumericCharacter = i
                Exit For
            End If
        Next i

    txt = Mid(cell, InStr(cell, " ") + 1, i - 2)
    'grab teh after number
    lasti = i + InStr(cell, " ") - 2
    anum = Mid(cell, lasti + 2, InStr(lasti + 2, cell, " ") - lasti - 2)

    Cells(cell.Row, 2) = num
    Cells(cell.Row, 3) = txt
    Cells(cell.Row, 4) = anum

    Next cell

End Sub

Posted by Excel Instructor:
http://www.chicagocomputerclasses.com/excel-classes/

VBA – Delete Every Other Row – Odd or Even – Excel Macro

This Excel Macro will go through all the cells in column A, find the last cell that has data in it, and then delete every other row in that data range.

To Delete Odd Rows

Sub Delete_Odd()

 Application.ScreenUpdating = False
lr = Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row

If lr Mod 2 = 0 Then
lr = lr - 1
End If

For i = lr To 1 Step -2
    Rows(i & ":" & i).Delete Shift:=xlUp    
Next i

 Application.ScreenUpdating = True

End Sub

To Delete Even Rows

Sub Delete_Even()

 Application.ScreenUpdating = False
lr = Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row

If lr Mod 2 = 0 Then
Else
lr = lr - 1
End If

For i = lr To 1 Step -2
    Rows(i & ":" & i).Delete Shift:=xlUp    
Next i

  Application.ScreenUpdating = True

End Sub

Posted by Excel Instructor:
http://www.chicagocomputerclasses.com/excel-classes/

VBA – Letter Count for Each Alphabet Character – Excel Macro

This Excel Macro will go through all the cells in column A and output the count for each letter in column B. This is for English alphabet only and it will skip all the other characters and spaces.

 

Sub LetterCount()

Dim ws As Worksheet
Set ws = ActiveSheet

lastrow = Cells(Rows.Count, 1).End(xlUp).Row

rg = Range("a1:a" & lastrow)
i = 1

For c = 97 To 122

cnt = 0

    For Each cell In rg

    lth = Len(cell)
        For lt = 1 To lth

            chktext = Mid(cell, lt, 1)

              If chktext = Chr(c) Then

                cnt = cnt + 1
            End If

        Next lt

    Next cell

    If cnt > 0 Then
        ws.Cells(i, 2) = Chr(c) & " = " & cnt
        i = i + 1
    End If

Next c

End Sub

Posted by Excel Instructor:
http://www.chicagocomputerclasses.com/excel-classes/

Excel VBA – Export Each Worksheet to a Separate PDF – Macro

If you need to Export Each sheet to an individual .pdf file this Macro will do it for you.

It will go through all the sheets in your Workbook and save each one to a separate PDF file using the worksheet name as file name.

 

Sub ExportToPDFs()
' PDF Export Macro
' Change C:\Exports\ to your folder path where you need the diles saved
' Save Each Worksheet to a separate PDF file.

Dim ws As Worksheet

For Each ws In Worksheets
ws.Select
nm = ws.Name

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="C:\Exports\" & nm & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False

Next ws

End Sub

Posted by Excel Instructor:
http://www.chicagocomputerclasses.com/excel-classes/

Excel – Age Calculation – How to Get Age from Date of Birth (DOB)

The easiest way to calculate person’s age from using their birthday in Excel is by utilizing undocumented DATEDIF function. DATEDIF is a built-in Excel function, however, unlike all the other built-in functions it will not auto-populate, show up in auto-complete or give tooltips on the function.

So how do you use DATEDIF function?

The syntax for the function is as follows:

DATEDIF([start-date],[end-date],[return type])

To calculate person’s age using datedif function you can use the following formula:

Assumptions:

  • A1  –  the cell where you have person’s birthrate

Enter the formula where you want to output the age:

=DATEDIF(A1,TODAY(),”Y”)

If you do not want to use the dynamic TODAY() function you may reference to a call with a date on which you would like to calculate the age.

Assumptions:

  • A1  –  the cell where you have person’s birthrate
  • B1 – the date when you want to calculate teh age

Enter the formula where you want to output the age:

=DATEDIF(A1,B1,”Y”)