Excel VBA: Empty Clipboard Excel

Do you ever think or need to clear/empty Clipboard Excel?

I have a big Excel file which abusing the power of copy and paste to format the data and formula. I prefer to update the formula once, then save the result as values, especially for lookup formula. If I am not doing this, each time I am changing something, it will trigger the lookup formula and make the Excel freeze a few minutes.

The down side of the approach, after several hours, Excel will become slower and slower. It’s look like after extensive abuse of copy and paste, the memory will full of data and slower the Excel application.

Fortunately, after applying empty clipboard Excel using VBA macro, the Excel application keep running smoothly until the end of the day.

There are two ways to clear Excel clipboard using VBA.

1. Empty Clipboard Excel Using Excel Application properties

Application.CopyObjectsWithCells = False

2. Empty Clipboard Excel Using Windows Empty Clipboard function

Public Declare Function OpenClipboard Lib "user32" ( _
    ByVal NewOwner As Long) As Boolean
Public Declare Function EmptyClipboard Lib "user32" () As Boolean
Public Declare Function CloseClipboard Lib "user32" () As Boolean

Sub ClearClipboard()
    ' call ClearClipboard() from your other VBA macro to clear/empty Windows Clipboard

    If OpenClipboard(0) Then
        EmptyClipboard
        CloseClipboard
    End If
End Sub

Both approach will empty the Clipboard, but the first approach will only empty copied data from Excel cells, both values and format. It will not empty Clipboard for any data that belong to application. Using Windows Empty Clipboard function, it will empty Clipboard regardless who is the owner of those data.

Just call one of the two functions above inside your macro, before or after you perform any extensive copy and paste macro to clear your Clipboard. For the 2nd approach, you need to put it in one of your VBA modules first.

Do you have another method to clear/empty Excel Clipboard? Please leave your comments below. Thanks.

Posted in Excel VBA Function | 5 Comments

How to Get a Full File Path in Excel?

Ever needed to find out the full path of your current file? What I mean by full path here is the full location of the active file including the directory path and full file name.

If you did, then what you need is this following code:

Application.ActiveWorkbook.FullName

The one line code will return the full directory path + filename of the active file, ex:
D:\My Directory\filename.xls

To simply use it from our formula bar, we can wrap the code into excel vba function like this:

Function FULLFILENAME()

     FULLFILENAME = Application.ActiveWorkbook.FullName

End Function

Every time we needed the information, just call the FULLFILENAME function from the formula bar.

Posted in Excel Formula, Excel VBA Function, Workbook and Worksheet | Tagged , , | 6 Comments

Remove Non-AlphaNumeric Characters from String

The function below will allow us to remove a non alphanumeric character from an input string.

Be careful though, lengther the string, more time needed to evaluate each string on the sentence.

To bad that I don’t have any idea on how to use Regular Expression in Excel VBA, if we can use regex to replace all the unwanted character directly, it would be great :)

Function GETALPHANUMERIC(text)

str_all = "abcdefghijklmnopqrstuvwxyz1234567890"
For lenstr = 1 To Len(text)
    If InStr(str_all, LCase(Mid(text, lenstr, 1))) Then
        GETALPHANUMERIC = GETALPHANUMERIC & Mid(text, lenstr, 1)
    End If
Next

End Function

If somehow what we need is only the apha part without the numeric part or vice versa, simply adjusting the value of str_all variable will solve it.

Posted in Excel Formula, Excel VBA Function | Tagged , | 5 Comments

Sum Unique/Distinct Values in Excel

Usually in the sequential database system, we can SUM only unique values in table column by adding all the values from SELECT DISTINCT query result only.

Based on the same principle, we can also create a simple VBA function in Microsoft Excel by adding the values only available in a collection of unique values we have created before hand.

Public Function DISTINCTSUM(Rg As range)
    Dim rCell As range
    Dim cCells As New Collection
    Dim vValue As Variant

    ' create a unique no duplicate value collection
    For Each rCell In Rg
        On Error Resume Next
        cCells.Add rCell.Value, CStr(rCell.Value)
    Next rCell

    ' sum all the data in previous collection
    For Each vValue In cCells
        DISTINCTSUM = vValue + DISTINCTSUM
    Next vValue

    Set cCells = Nothing
End Function

In here, first we create a Collection object that contains unique values only. Only then will we loop throught the collection and add up all the values stored there to get the DISTINCT SUM value.

Now we can call the above DISCTINCTSUM formula directly from Excel formula bar to sum only the unique or disctinct values in some range of cells, with the cell range as parameter.

=distinctsum(D4:D8)

Will sum all the unique values in range of D4 until D8. This is really helpful if we have a lot of duplicate data that we don’t want to count.

The other way around to get the sum of unique/distinct values in Excel is using Pivot Table.

Create a Pivot Table, then drop the column containing duplicate values in the Row fields area. Excel will then automatically filtered all the values and remove any duplicate values in that column. Later on, simply SUM all the data in the row fields to get the distinct sum.

The final result will be the same, but we don’t want to create a Pivot Table for every column we wanna sum, right?

Another way to get a list of unique values is to use the Advanced Filter feature. In advanced filtering options, check the option Copy to another location, and Unique records only option. Then select the cell where we want to put the unique values.

Easier to do compare to Pivot Table, but we still don’t have the flexibility of the previous DISTINCTSUM macro.

Posted in Excel VBA Function | 13 Comments

Excel Extract Cell Comments

Excel VBA/Macro example below will extract comment from every cells with comment, and put the summary in the cell selected by user using Excel input box (read more about how to get cell reference using input box here).

Sub CreateCommentsSummary()

    Dim rgComments As Range, rgCell As Range, rgOutput As Range, iRow As Integer, iCol As Integer

    ' get all cells with comment
    Set rgComments = ActiveSheet.Cells.SpecialCells(xlCellTypeComments)

    ' get cell reference where user want to place the summary
    Set rgOutput = _
        Application.InputBox(Prompt:="Select cell where you want to put the comments summary", _
            Title:="Comments Summary", Type:=8)

    iRow = rgOutput.Row
    iCol = rgOutput.Column

    ' read each cell with comment and build the summary
    For Each rgCell In rgComments
        Cells(iRow, iCol) = rgCell.Address    ' print cell address
        Cells(iRow, iCol + 1) = rgCell.Value    ' print cell value
        Cells(iRow, iCol + 2) = rgCell.Comment.Text    'print cell comment text
        iRow = iRow + 1
    Next rgCell

End Sub

Happy coding :D

Posted in Cells and Range | Tagged , , , , , | 5 Comments

How to get an Acronym using Excel VBA?

The purpose of the following example of Excel VBA macro is to get the acronym or an abbreviation of each of the first letter of any given words.

Function Acronym(Words As Variant) As String

    Dim aWord() As String, ix As Integer

    aWord = Split(Words.Value, " ")
    For ix = 0 To UBound(aWord)
        Acronym = Acronym & UCase(Left(aWord(ix), 1))
    Next ix

End Function

Using Split function and space as delimiter, we create an array of word. Then using simple for … to loop, we do looping of each word and take the first letter of each word in array using Left function.

By using iteration and array like this, we will get the acronym of the word in question.

We can directly use the function in Excel formula bar with a reference to the cell that contains the collection of words we want to make an acronym from it as input.

acronym

For the details information of each function in use, Split/Ucase/Left, select each function and push F1 while in the Visual Basic Editor.

Posted in Excel Formula | Tagged , , , , , , | 9 Comments

Get Position of Last Column Containing Data with Excel VBA

If you read my latest update on how we can get position of last row containing data, then most probably you already have a glimpse on how we perform the same task with last column containing data in Excel.

The VBA code is the exact replica of the code to get the last row, only this time, we change the row into column.

Function LastColumn() As Long

    Dim ix As Long
    ix = ActiveSheet.UsedRange.Column - 1 + ActiveSheet.UsedRange.Columns.Count
    LastColumn = ix

End Function

The function above will return the appropriate position of the column even when the last column containing data in a hidden state.

The results of this function is the column number, not the column name (1 for A, 2 for B, etc). If what we need is the column name, then we can use the excel column number to column name converter that I wrote before.

Posted in Cells and Range | Tagged , , , , , , , , | 39 Comments