Friday, February 24, 2012

Google Translate by Internet Explorer Automation

This VBA Macro Code translates text using Google Translate by automation of Internet Explorer controlled through Excel.

Explanation

The program automatically writes text from Excel into Internet Explorer and uses the Google Translate service to translate the text into desires language. It is possible to translate from and to many different languages, just change the language code and the program is set up accordingly. Today all the major languages are available using google translate. It is one of few services that enables translation of entire sentences not just words. The service is free of charge and can be executed through API. The exact technology used for the translation is not public. Google has started to translate entire web pages on the internet as well when using the google seach function.  

Code

Public Sub Google_Translate()

Dim Google_Translate_Internet_Explorer_Automation As Object
Set Google_Translate_Internet_Explorer_Automation = CreateObject("InternetExplorer.Application")
Google_Translate_Internet_Explorer_Automation.Navigate "http://translate.google.com/translate_t#"
Google_Translate_Internet_Explorer_Automation.Visible = True
Wait_Between_Google_Translate_Cycles = Range("G1").Value

Column = 0
While Range("f9").Offset(0, Column).Value <> tom

    Do While Google_Translate_Internet_Explorer_Automation.busy
        Call WaitSeconds(Wait_Between_Google_Translate_Cycles)
    Loop
   
    to_language_code = Range("f9").Offset(0, Column).Value

    Do While Google_Translate_Internet_Explorer_Automation.busy
        Call WaitSeconds(Wait_Between_Google_Translate_Cycles)
    Loop

    Google_Translate_Internet_Explorer_Automation.document.forms("text_form").elements(5).Value = to_language_code

    Do While Google_Translate_Internet_Explorer_Automation.busy
        Call WaitSeconds(Wait_Between_Google_Translate_Cycles)
    Loop

    rad = 0
    While Range("c10").Offset(rad, 0).Value <> tom

        If Range("f10").Offset(rad, Column).Value = tom Then

            from_language_code = Range("a10").Offset(rad, 0).Value
            Google_Translate_Internet_Explorer_Automation.document.forms("text_form").elements(4).Value = from_language_code

            Do While Google_Translate_Internet_Explorer_Automation.busy
                Call WaitSeconds(Wait_Between_Google_Translate_Cycles)
            Loop

            Google_Translate_Text = Range("c10").Offset(rad, 0).Value

            While Google_Translate_Internet_Explorer_Automation.busy
                Call WaitSeconds(Wait_Between_Google_Translate_Cycles)
            Wend

            Google_Translate_Internet_Explorer_Automation.document.forms("text_form").elements("source").Value = Google_Translate_Text

            While Google_Translate_Internet_Explorer_Automation.busy
                Call WaitSeconds(Wait_Between_Google_Translate_Cycles)
            Wend

            Google_Translate_Internet_Explorer_Automation.document.getElementById("text_form").submit

            While Google_Translate_Internet_Explorer_Automation.busy
                Call WaitSeconds(Wait_Between_Google_Translate_Cycles)
            Wend

            dd2 = Google_Translate_Internet_Explorer_Automation.document.forms(1).elements(4).Value

            While Google_Translate_Internet_Explorer_Automation.busy
                Call WaitSeconds(Wait_Between_Google_Translate_Cycles)
            Wend

            Google_Translate_Variable1 = Replace(dd2, Chr(13), "")
            Range("f10").Offset(rad, Column).Value = Google_Translate_Variable1

        End If

        rad = rad + 1
    Wend

    Column = Column + 1
Wend

Google_Translate_Internet_Explorer_Automation.Quit
Set Google_Translate_Internet_Explorer_Automation = Nothing

End Sub

Public Sub WaitSeconds(sek)

newHour = Hour(Now())
newMinute = Minute(Now())
newSecond = Second(Now()) + sek
waitTime = TimeSerial(newHour, newMinute, newSecond)
Application.Wait waitTime

End Sub

Extract, Get Data from MySQL PHP

This VBA Macro code extracts data from a MySQL Database and writes the data to an excel file. Many use this for large quantities of data control for PHP web development.

Explanation

The approach is straight forward. Download the file fill in the data regarding set up of MySQL connection. Push the button and all data from the selected table will be displayed. This program is good to use if you have a MySQL database from a website for example and you need to perform a massive amount of data update. Simply automate the process and get the data you need.
To be able to run the VBA Macro code make sure you have enabled the Microsoft ActiveX Data Objects X.X Library. Also a ODBC connector check mysql.com needs to be installed on your computer. 

Code

Sub ExtractDataFromMySQL()

Dim Password As String
Dim SQLStr As String
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim User_ID As String
Dim Database_Name As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
   
Range("a5:bb60000").ClearContents

Server_Name = Range("e4").Value             ' IP number or servername
Database_Name = Range("e1").Value         ' Name of database
User_ID = Range("h1").Value                      ' id user or username
Password = Range("e3").Value                    ' Password
Tabellen = Range("e2").Value                     ' Name of table to write to

SQLStr = "SELECT * FROM " & Tabellen
   
Set Cn = New ADODB.Connection
Cn.Open "Driver={MySQL ODBC 3.51 Driver};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
   
rs.Open SQLStr, Cn, adOpenStatic
  
Dim myArray()

myArray = rs.GetRows()
 
kolumner = UBound(myArray, 1)
rader = UBound(myArray, 2)

For K = 0 To kolumner

Range("A5").Offset(0, K).Value = rs.Fields(K).Name
For R = 0 To rader
 Range("A5").Offset(R + 1, K).Value = myArray(K, R)
Next
Next

rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing

End Sub

Email Sender VBA Outlook

Email Sender VBA Outlook is an emailing program that sends emails by communicating with Microsoft Outlook.

Explanation

Email Sender VBA Outlook is a VBA Excel program that communicates with Microsoft Outlook. The program sends email templates from a predefined place on you computer, the file needs to be an .oft-file. There is also a function for blocking certain email addresses. The program requires the reference “Microsoft Outlook XX.X Object Library” to be enabled. In the new version of office it is easy to block communication between excel and outlook make sure to enable the communication before trying the code otherwise it will not work

Code

Sub Email_Sender_VBA_Microsoft_Outlook()

Dim NoMailList(1500)
Call LoadNoMailList(NoMailList)

WaitTimeSecondsBetweenMail = Range("c4").Value
PlaceToStoreEmailTemplate = Range("c5").Value

RowA = 0
While Range("A14").Offset(RowA, 0).Value <> tom
    ToAdress = Range("c14").Offset(RowA, 0).Value
    Subject = Range("d14").Offset(RowA, 0).Value
    FileName = Range("D14").Offset(RowA, 0).Value
    Call WaitTimeProgram(WaitTimeSecondsBetweenMail)
    Subject = Range("e14").Offset(RowA, 0).Value
    Call MatchAdressWithNoMailList(ToAdress, Funnen, NoMailList)
    If Funnen = False Then
        Call EmailSenderProgram(ToAdress, FileName, Subject, PlaceToStoreEmailTemplate)
    End If
    RowA = RowA + 1
Wend

End Sub

Sub EmailSenderProgram(ToAdress, FileName, Subject, PlaceToStoreEmailTemplate)

Dim VBAOutlookEmailSend As Object, vItem As Object, vStr As String
Set VBAOutlookEmailSend = CreateObject("Outlook.Application")
Dim temp2 As String
temp2 = FileName
Set vItem = VBAOutlookEmailSend.CreateItemFromTemplate(PlaceToStoreEmailTemplate + temp2 + ".oft")
vItem.Subject = Subject
Dim ToContact As Outlook.Recipient
Set ToContact = vItem.Recipients.Add(ToAdress)
vItem.ReadReceiptRequested = False
vItem.Send
Set vItem = Nothing
Set VBAOutlookEmailSend = Nothing

End Sub

Public Sub LoadNoMailList(NoMailList)

rad = 0
While Range("g14").Offset(rad, 0).Value <> tom
    NoMailList(rad + 1) = Range("g14").Offset(rad, 0).Value
    rad = rad + 1
Wend

End Sub

Public Sub MatchAdressWithNoMailList(ToAdress, Funnen, NoMailList)

Funnen = False
plats = 1
While NoMailList(plats) <> tom
    komp = InStr(ToAdress, NoMailList(plats))
    If komp <> 0 Then Funnen = True
    plats = plats + 1
Wend

End Sub

Public Sub WaitTimeProgram(sek)

newHour = Hour(Now())
newMinute = Minute(Now())
newSecond = Second(Now()) + sek
waitTime = TimeSerial(newHour, newMinute, newSecond)
Application.Wait waitTime

End Sub

Determine If File or Directory Exists

The VBA Macro determines if a file or directory exists.

Explanation

To be able to determine if a file or directory exists can be useful in some coding situations. This code is a straight forward approach that logs if a error occurs when trying to use the GetAttr() if a error occurs then the file or directory clearly does not exist. This function is useful when you want to communicate or write to a certain file and you are uncertain if the file really exists and if you refer the file you might crash the program, thus check if the file exist if it does communicate with the file or terminate the program. 

Code

Public Sub DetermineIfFileDirectoryExists()
    
Dim DetermineFileExists As Integer
Dim PathOfName As String
    
Range("C8").Value = ""
Range("C8").Interior.ColorIndex = 0
    
' If the file does not exist the program will log an error
On Error Resume Next
PathOfName = Range("C5").Value + "\" + Range("C6").Value
   
DetermineFileExists = GetAttr(PathOfName)
    
Select Case Err.Number
Case Is = 0
    Range("C8").Value = "The File or Directory Exists"
    Range("C8").Interior.ColorIndex = 4
Case Else
    Range("C8").Value = "The File or Directory does NOT Exists"
    Range("C8").Interior.ColorIndex = 3
End Select
   
On Error GoTo 0
End Sub

Database connection, retrieve data from database, querying data into excel using VBA DAO

The VBA code makes a database connection and retrieves data by calling and giving input to existing database query.

Explanation

A database connection is established through the VBA Macro and a query that is all ready created and stored in the database is executed. The query is also created to retrieve data of two different parameters. The parameters can be excluded in case of retrieving all data from a query without specific filters. This type of database connection can be established to all major business systems and can save time and money by eliminating time consuming manual data transfer. For example a days manual work can easily be done automatically using VBA macro automation. It is important to perform analyzes of your own work continuously in order to be efficient.

In order to make the VBA code work the following reference needs to be enabled “Microsoft DAO 3.6 Object Library”.

The entire VBA program can be downloaded in an excel file at the end of this web page or just copy and paste the code directly from the page!

Code

Public Sub database_connection_retrieve_data_from_database_querying_data_into_excel_using_VBA_DAO()

Dim Database_RetrieveData_VBA_Excel As String
Dim Query_RetrieveData_VBA_Excel As String
Dim Parameter1_RetrieveData_VBA_Excel As String
Dim Parameter2_RetrieveData_VBA_Excel As String
Dim DAO_Connection_RetrieveData_VBA_Excel As String
   
Database_RetrieveData_VBA_Excel = Range("G3").Value
Query_RetrieveData_VBA_Excel = Range("G4").Value
Parameter1_RetrieveData_VBA_Excel = Range("G5").Value
Parameter2_RetrieveData_VBA_Excel = Range("G6").Value
DAO_Connection_RetrieveData_VBA_Excel = 0
   
DB1 = DBEngine.OpenDatabase(Database_RetrieveData_VBA_Excel)

Set QD1 = DB1.QueryDefs(Query_RetrieveData_VBA_Excel)
       
QD1.Parameters("p1") = Parameter1_RetrieveData_VBA_Excel
QD1.Parameters("p2") = Parameter2_RetrieveData_VBA_Excel
        
Set RS1 = QD1.OpenRecordset(dbOpenSnapshot, dbReadOnly)
Range("b11").Offset(0, 0).CopyFromRecordset RS1

RS1.Close
QD1.Close
DB1.Close


End Sub


Merge data from all workbooks in a folder

Code Examples that use DIR

There are four basic examples:
1) Merge a range from all workbooks in a folder (below each other)
2) Merge a range from every workbook you select (below each other)
3) Merge a range from all workbooks in a folder (next to each other)
4) Merge a range from all workbooks in a folder with AutoFilter

The code will create a new workbook for you with the data from all workbooks
with in column A or in row 1 the file name of the data in that row or column.
It is up to you if you save the workbook.

Information and Tips

The examples below are only working for one folder (no option for subfolders).
Note: the workbook with the code must be outside the merge folder

Tip 1: Useful Workbooks.Open arguments

Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum), _
Password:="ron", WriteResPassword:="ron", UpdateLinks:=0)


If your workbooks are protected you can us this in the Workbooks.Open arguments
Password:="ron” and WriteResPassword:="ron"

If you have links in your workbook this (UpdateLinks:=0) will avoid the message
do you want to update the links or not "0 Doesn't update any references"
Use 3 instead of 0 if you want to update the links.

See the VBA help for more information about the Workbooks.Open arguments

Tip 2: merge from all Files with a name that start with for example week
Use this then
FilesInPath = Dir(MyPath & "week*.xl*")


Tip 3 : Copy values and formats

the macro examples below will copy only the values, if you want to copy
the formats also replace this :
With SourceRange
    Set destrange = destrange. _
                    Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = SourceRange.Value

With
SourceRange.Copy
With destrange
    .PasteSpecial xlPasteValues
    .PasteSpecial xlPasteFormats
    Application.CutCopyMode = False
End With
Before you restore ScreenUpdating, Calculation and EnableEvents also add this line

Application.Goto BaseWks.Cells(1)




Merge a range from all workbooks in a folder (below each other)

There are a few things you must change before you can run the code

Fill in the path to the folder
MyPath = "C:\Users\Ron\test"

I use the first worksheet of each workbook in my example (index 1)
Change the worksheet index or fill in a sheet name: mybook.Worksheets("YourSheetName")
And change the range A1:C1 to your range
With mybook.Worksheets(1)
    Set SourceRange = .Range("A1:C1")
End With
If you want to copy all cells from the worksheet or from A2 till the last cell on the worksheet.
Then replace the code above with this
With mybook.Worksheets(1)
    FirstCell = "A2"
    Set SourceRange = .Range(FirstCell & ":" & RDB_Last(3, .Cells))
    'Test if the row of the last cell >= then the row of the FirstCell
    If RDB_Last(1, .Cells) < .Range(FirstCell).Row Then
         Set SourceRange = Nothing
    End If
End With
Add also this dim line at the top of the macro
Dim FirstCell As String

Note: the code above use the function RDB_Last, copy this function also in your code module
if you use it. You find the function in the last section of this page.

Fill in the first cell here and the code will find the last cell on the worksheet for you.
FirstCell = "A2"

Sub Basic_Example_1()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String
    Dim SourceRcount As Long, Fnum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim rnum As Long, CalcMode As Long

    'Fill in the path\folder where the files are
    MyPath = "C:\Users\Ron\test"

    'Add a slash at the end if the user forget it
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If

    'If there are no Excel files in the folder exit the sub
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If

    'Fill the array(myFiles)with the list of Excel files in the folder
    Fnum = 0
    Do While FilesInPath <> ""
        Fnum = Fnum + 1
        ReDim Preserve MyFiles(1 To Fnum)
        MyFiles(Fnum) = FilesInPath
        FilesInPath = Dir()
    Loop

    'Change ScreenUpdating, Calculation and EnableEvents
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Add a new workbook with one sheet
    Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    rnum = 1

    'Loop through all files in the array(myFiles)
    If Fnum > 0 Then
        For Fnum = LBound(MyFiles) To UBound(MyFiles)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
            On Error GoTo 0

            If Not mybook Is Nothing Then

                On Error Resume Next

                With mybook.Worksheets(1)
                    Set sourceRange = .Range("A1:C1")
                End With

                If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                Else
                    'if SourceRange use all columns then skip this file
                    If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
                        Set sourceRange = Nothing
                    End If
                End If
                On Error GoTo 0

                If Not sourceRange Is Nothing Then

                    SourceRcount = sourceRange.Rows.Count

                    If rnum + SourceRcount >= BaseWks.Rows.Count Then
                        MsgBox "Sorry there are not enough rows in the sheet"
                        BaseWks.Columns.AutoFit
                        mybook.Close savechanges:=False
                        GoTo ExitTheSub
                    Else

                        'Copy the file name in column A
                        With sourceRange
                            BaseWks.cells(rnum, "A"). _
                                    Resize(.Rows.Count).Value = MyFiles(Fnum)
                        End With

                        'Set the destrange
                        Set destrange = BaseWks.Range("B" & rnum)

                        'we copy the values from the sourceRange to the destrange
                        With sourceRange
                            Set destrange = destrange. _
                                            Resize(.Rows.Count, .Columns.Count)
                        End With
                        destrange.Value = sourceRange.Value

                        rnum = rnum + SourceRcount
                    End If
                End If
                mybook.Close savechanges:=False
            End If

        Next Fnum
        BaseWks.Columns.AutoFit
    End If

ExitTheSub:
    'Restore ScreenUpdating, Calculation and EnableEvents
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub

Merge a range from every workbook you select (below each other)

This code example will do the same as the example above only when you run the code
you are able to select the files you want to merge.

Fill in the path to the folder
ChDirNet "C:\Users\Ron\test"

and change the sheet and range to yours (see first example)

It is also possible to set the start folder with ChDrive and ChDir but I choose to use the
SetCurrentDirectoryA  function in this example because it also is working with network folders.


Note: Copy all code below in a normal module
#If VBA7 Then
    Declare PtrSafe Function SetCurrentDirectoryA Lib _
    "kernel32" (ByVal lpPathName As String) As Long
#Else
    Declare Function SetCurrentDirectoryA Lib _
    "kernel32" (ByVal lpPathName As String) As Long
#End If


Sub ChDirNet(szPath As String)
    SetCurrentDirectoryA szPath
End Sub

Sub Basic_Example_2()
    Dim MyPath As String
    Dim SourceRcount As Long, Fnum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim rnum As Long, CalcMode As Long
    Dim SaveDriveDir As String
    Dim FName As Variant


    'Change ScreenUpdating, Calculation and EnableEvents
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    SaveDriveDir = CurDir
    ChDirNet "C:\Users\Ron\test"

    FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
                                        MultiSelect:=True)
    If IsArray(FName) Then

        'Add a new workbook with one sheet
        Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
        rnum = 1


        'Loop through all files in the array(myFiles)
        For Fnum = LBound(FName) To UBound(FName)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(FName(Fnum))
            On Error GoTo 0

            If Not mybook Is Nothing Then

                On Error Resume Next
                With mybook.Worksheets(1)
                    Set sourceRange = .Range("A1:C1")
                End With

                If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                Else
                    'if SourceRange use all columns then skip this file
                    If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
                        Set sourceRange = Nothing
                    End If
                End If
                On Error GoTo 0

                If Not sourceRange Is Nothing Then

                    SourceRcount = sourceRange.Rows.Count

                    If rnum + SourceRcount >= BaseWks.Rows.Count Then
                        MsgBox "Sorry there are not enough rows in the sheet"
                        BaseWks.Columns.AutoFit
                        mybook.Close savechanges:=False
                        GoTo ExitTheSub
                    Else

                        'Copy the file name in column A
                        With sourceRange
                            BaseWks.Cells(rnum, "A"). _
                                    Resize(.Rows.Count).Value = FName(Fnum)
                        End With

                        'Set the destrange
                        Set destrange = BaseWks.Range("B" & rnum)

                        'we copy the values from the sourceRange to the destrange
                        With sourceRange
                            Set destrange = destrange. _
                                            Resize(.Rows.Count, .Columns.Count)
                        End With
                        destrange.Value = sourceRange.Value

                        rnum = rnum + SourceRcount
                    End If
                End If
                mybook.Close savechanges:=False
            End If

        Next Fnum
        BaseWks.Columns.AutoFit
    End If

ExitTheSub:
    'Restore ScreenUpdating, Calculation and EnableEvents
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
    ChDirNet SaveDriveDir
End Sub



Merge a range from all workbooks in a folder (next to each other)

This example will past the data next to each other. In column A you see the data from the first
workbook and in Column B the data from the next and in.....

There are a few things you must change before you can run the code

Fill in the path to the folder
MyPath = "C:\Users\Ron\test"

I use the first sheet of each workbook in my example (index 1)
Change the sheet index or fill in a sheet name: mybook.Worksheets("YourSheetName")
And change the range A1:A10 to your range.

Set sourceRange = mybook.Worksheets(1).Range("A1:A10")
Sub Basic_Example_3()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String
    Dim SourceCcount As Long, Fnum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim Cnum As Long, CalcMode As Long

    'Fill in the path\folder where the files are
    MyPath = "C:\Users\Ron\test"

    'Add a slash at the end if the user forget it
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If

    'If there are no Excel files in the folder exit the sub
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If

    'Fill the array(myFiles)with the list of Excel files in the folder
    Fnum = 0
    Do While FilesInPath <> ""
        Fnum = Fnum + 1
        ReDim Preserve MyFiles(1 To Fnum)
        MyFiles(Fnum) = FilesInPath
        FilesInPath = Dir()
    Loop

    'Change ScreenUpdating, Calculation and EnableEvents
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Add a new workbook with one sheet
    Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    Cnum = 1

    'Loop through all files in the array(myFiles)
    If Fnum > 0 Then
        For Fnum = LBound(MyFiles) To UBound(MyFiles)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
            On Error GoTo 0

            If Not mybook Is Nothing Then

                On Error Resume Next
                Set sourceRange = mybook.Worksheets(1).Range("A1:A10")

                If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                Else
                    'if SourceRange use all rows then skip this file
                    If sourceRange.Rows.Count >= BaseWks.Rows.Count Then
                        Set sourceRange = Nothing
                    End If
                End If
                On Error GoTo 0

                If Not sourceRange Is Nothing Then

                    SourceCcount = sourceRange.Columns.Count

                    If Cnum + SourceCcount >= BaseWks.Columns.Count Then
                        MsgBox "Sorry there are not enough columns in the sheet"
                        BaseWks.Columns.AutoFit
                        mybook.Close savechanges:=False
                        GoTo ExitTheSub
                    Else

                        'Copy the file name in the first row
                        With sourceRange
                            BaseWks.cells(1, Cnum). _
                                    Resize(, .Columns.Count).Value = MyFiles(Fnum)
                        End With

                        'Set the destrange
                        Set destrange = BaseWks.cells(2, Cnum)

                        'we copy the values from the sourceRange to the destrange
                        With sourceRange
                            Set destrange = destrange. _
                                            Resize(.Rows.Count, .Columns.Count)
                        End With
                        destrange.Value = sourceRange.Value

                        Cnum = Cnum + SourceCcount
                    End If
                End If
                mybook.Close savechanges:=False
            End If

        Next Fnum
        BaseWks.Columns.AutoFit
    End If

ExitTheSub:
    'Restore ScreenUpdating, Calculation and EnableEvents
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With

End Sub


Merge a range from all workbooks in a folder with AutoFilter

This example will filter a range on a worksheet in every workbook in the folder and copy
the filter results to a new workbook.
There are five code lines that you must change before you run the code(see macro)

Note: the code use the function RDB_Last, copy this function also in your code module.
You find the function in the last section of this page.
Sub Basic_Example_4()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String
    Dim SourceRcount As Long, FNum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim rnum As Long, CalcMode As Long
    Dim rng As Range, SearchValue As String
    Dim FilterField As Integer, RangeAddress As String
    Dim ShName As Variant, RwCount As Long

    '**********************************************************
    '***Change this five code lines before you run the macro***
    '**********************************************************

    'Fill in the path\folder where the files are
    MyPath = "C:\Users\Ron\test"

    'Fill in the sheet name where the data is in each workbook
    'Use ShName = "Sheet1" if you want to use a sheet name instead if the index
    'We use the first sheet in every workbook in this example(I use the index)
    ShName = 1

    'Fill in the filter range: A1 is the header of the first column and G is
    'the last column in the range and it will filter on all rows on the sheet
    'You can also use a fixed range like A1:G2500 if you want
    RangeAddress = Range("A1:G" & Rows.Count).Address

    'Field that you want to filter in the range ( 1 = column A in this
    'example because the filter range start in column A
    FilterField = 1

    'Fill in the filter value ("<>ron" if you want the opposite)
    'Or use wildcards like "*ron" for cells that start with ron or use
    '"*ron*" if you look for cells where ron is a part of the cell value
    SearchValue = "ron"

    '**********************************************************
    '**********************************************************


    'Add a slash after MyPath if the user forget it
    If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
    End If

    'If there are no Excel files in the folder exit the sub
    FilesInPath = Dir(MyPath & "*.xl*")
    If FilesInPath = "" Then
        MsgBox "No files found"
        Exit Sub
    End If

    'Fill the array(myFiles)with the list of Excel files in the folder
    FNum = 0
    Do While FilesInPath <> ""
        FNum = FNum + 1
        ReDim Preserve MyFiles(1 To FNum)
        MyFiles(FNum) = FilesInPath
        FilesInPath = Dir()
    Loop

    'Change ScreenUpdating, Calculation and EnableEvents
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Add a new workbook with one sheet
    Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    rnum = 1

    'Loop through all files in the array(myFiles)
    If FNum > 0 Then
        For FNum = LBound(MyFiles) To UBound(MyFiles)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(MyPath & MyFiles(FNum))
            On Error GoTo 0

            If Not mybook Is Nothing Then

                On Error Resume Next
                'set filter range
                With mybook.Worksheets(ShName)
                    Set sourceRange = .Range(RangeAddress)
                End With

                If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                End If
                On Error GoTo 0

                If Not sourceRange Is Nothing Then
                    'Find the last row in BaseWks
                    rnum = RDB_Last(1, BaseWks.Cells) + 1

                    With sourceRange.Parent
                        Set rng = Nothing

                        'Firstly, remove the AutoFilter
                        .AutoFilterMode = False

                        'Filter the range on the FilterField column
                        sourceRange.AutoFilter Field:=FilterField, _
                                               Criteria1:=SearchValue

                        With .AutoFilter.Range

                            'Check if there are results after you use AutoFilter
                            RwCount = .Columns(1).Cells. _
                                      SpecialCells(xlCellTypeVisible).Cells.Count - 1

                            If RwCount = 0 Then
                                'There is no data, only the header
                            Else
                                ' Set a range without the Header row
                                Set rng = .Resize(.Rows.Count - 1, .Columns.Count). _
                                          Offset(1, 0).SpecialCells(xlCellTypeVisible)


                                'Copy the range and the file name in column A
                                If rnum + RwCount < BaseWks.Rows.Count Then
                                    BaseWks.Cells(rnum, "A").Resize(RwCount).Value _
                                          = mybook.Name
                                    rng.Copy BaseWks.Cells(rnum, "B")
                                End If
                            End If

                        End With

                        'Remove the AutoFilter
                        .AutoFilterMode = False

                    End With
                End If

                'Close the workbook without saving
                mybook.Close savechanges:=False
            End If

            'Open the next workbook
        Next FNum

        'Set the column width in the new workbook
        BaseWks.Columns.AutoFit
        MsgBox "Look at the merge results in the new workbook after you click on OK"
    End If

    'Restore ScreenUpdating, Calculation and EnableEvents
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub


RDB_Last function to find the last cell or row
Function RDB_Last(choice As Integer, rng As Range)
'Ron de Bruin, 5 May 2008
' 1 = last row
' 2 = last column
' 3 = last cell
    Dim lrw As Long
    Dim lcol As Integer

    Select Case choice

    Case 1:
        On Error Resume Next
        RDB_Last = rng.Find(What:="*", _
                            after:=rng.cells(1), _
                            Lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
        On Error GoTo 0

    Case 2:
        On Error Resume Next
        RDB_Last = rng.Find(What:="*", _
                            after:=rng.cells(1), _
                            Lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByColumns, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Column
        On Error GoTo 0

    Case 3:
        On Error Resume Next
        lrw = rng.Find(What:="*", _
                       after:=rng.cells(1), _
                       Lookat:=xlPart, _
                       LookIn:=xlFormulas, _
                       SearchOrder:=xlByRows, _
                       SearchDirection:=xlPrevious, _
                       MatchCase:=False).Row
        On Error GoTo 0

        On Error Resume Next
        lcol = rng.Find(What:="*", _
                        after:=rng.cells(1), _
                        Lookat:=xlPart, _
                        LookIn:=xlFormulas, _
                        SearchOrder:=xlByColumns, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Column
        On Error GoTo 0

        On Error Resume Next
        RDB_Last = rng.Parent.cells(lrw, lcol).Address(False, False)
        If Err.Number > 0 Then
            RDB_Last = rng.cells(1).Address(False, False)
            Err.Clear
        End If
        On Error GoTo 0

    End Select
End Function

Application.Evaluate

In Excel 2011 Application.Evaluate is broken

For example the test macro below will show you 1 in Excel 2004 and all Windows Excel versions.
Sub TestAppEvaluate()
    ThisWorkbook.Names.Add "Version", "=1"
    MsgBox Application.Evaluate("'" & ThisWorkbook.Name & "'!Version")
End Sub

But in Excel 2011 this will not work, you can use this as a workeround :
Sub TestAppEvaluate2()
    Dim VersionConstant As String
    ThisWorkbook.Names.Add "Version", "=2"
    VersionConstant = ThisWorkbook.Names("Version").RefersTo
    MsgBox Mid(VersionConstant, 2, Len(VersionConstant) - 1)
End Sub