Category: Excel VBA


ExcelYou may develop an Excel application that needs to adjust itself depending on the video resolution of the user. For

example, you might have an application that requires a certain range to show so you’ll need to adjust Excel’s zoom factor.

Here is a way by using GetSystemMetrics API function of windows :

CODE :

Declare Function GetSystemMetrics32 Lib "User32" Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long 

Sub DisplayScreenResolution() 
    Dim lngWidth            As Long
    Dim lngHeight           As Long    

    lngWidth = GetSystemMetrics32(0) ' width in points
    lngHeight = GetSystemMetrics32(1) ' height in points

    MsgBox Format(lngWidth, "#,##0") & " x " & Format(lngHeight, "#,##0"), vbInformation, "Screen Resolution (width x height)"
    
End Sub

Some time you have seen that your workbook has some connection and got this kind of notification to enable data connection

Data connection

Data connection

If you want to remove all data connection at once here is the code to do it:

Code:
Sub RemoveConnections() 
    Dim lngLoop             As Long    
    With ActiveWorkbook.Connections
        For lngLoop = 1 To objCon.Count
            If objCon.Count = 0 Then Exit Sub
            objCon.Item(lngLoop).Delete
            lngLoop = lngLoop - 1
        Next lngLoop
    End With 
End Sub

This procedure will remove all existing data connection in excel workbook.


If you are creating ribbon for Excel, Word or PowerPoint and you want to add office ribbon control image to your custom control at that time you need name of that image.

Here i have attached office add-ins to get there ribbon control image name which you can use to your ribbon control.

Attachments:

ExcelOffice2007IconsGallery.xlam
PowerPoint2007IconGallery.ppam
WordOffice2007IconsGallery.dotm

Here is the screen shot of add-in:

icongallery

After downloading you just need to remove “.key” from extension and use it.

For all attached add-in you can find icon gallery under Developer tab.

Here, i will show you how we can filter pivot table field by using excel vba. Some time we need to change filter field value by using code to get the desired output but if we have thousands of entry in the field value then we need a lot time to do it manaully so here is the method to do it by code.

CODE:

 
Sub t_SigleSelection()
    'Here is how we can use it
    Call Apply_Filter("Sheet2", "P10", "PivotTable1", "Product", False)
End Sub
 
Sub t_MultipleSelection()
    'Here is how we can use it
    'To select multiple option just pass filter item with , delimeter
    Call Apply_Filter("Sheet2", "P1,P2,P3,P4", "PivotTable1", "Product", True)
End Sub
 
Sub Apply_Filter(ByVal strSheetName As String, ByVal strFilterVal As String _
                 , ByVal strPvtTblName As String, ByVal strPvtFieldName As String _
                 , Optional ByVal blnMultiSelection As Boolean = False)
 
    Dim pvtTable                As PivotTable
    Dim pvtField                As PivotField
    Dim pvtItem                 As PivotItem
    Dim varItem                 As Variant
    Dim lngLoop                 As Long
    
    Const strDelimeter          As String = ","
    
    varItem = Split(strFilterVal, strDelimeter)
    Set pvtTable = ThisWorkbook.Worksheets(strSheetName).PivotTables(strPvtTblName)
    Set pvtField = pvtTable.PivotFields(strPvtFieldName)
        
    pvtField.EnableMultiplePageItems = blnMultiSelection
    
    If blnMultiSelection Then
        pvtField.PivotItems(varItem(LBound(varItem))).Visible = True
        For lngLoop = 2 To pvtField.PivotItems.Count
            pvtField.PivotItems(lngLoop).Visible = False
        Next lngLoop
        For Each pvtItem In pvtField.PivotItems
            For lngLoop = LBound(varItem) + 1 To UBound(varItem)
                If LCase(Trim(pvtItem.Value)) = LCase(Trim(varItem(lngLoop))) Then
                    pvtField.PivotItems(pvtItem.Value).Visible = True
                End If
            Next lngLoop
        Next pvtItem
    Else
        For Each pvtItem In pvtField.PivotItems
            If LCase(Trim(pvtItem.Value)) = LCase(Trim(strFilterVal)) Then
                pvtField.CurrentPage = pvtItem.Value
                Exit For
            End If
        Next pvtItem
    End If
    
    Set pvtTable = Nothing
    Set pvtField = Nothing
    Set pvtItem = Nothing
    varItem = Empty
    lngLoop = Empty
    
End Sub
 

Some time we use array for hudge data to copy and paste values in excel from one range to other and if in case some cell contains a text which is greater then 255 character in length then it gives an error that you can not paste value to the range.

Below code will help you to paste these kind of array to range

Code:
Sub HowToUse()
    'Here is how you can use it
    Call ArrayToRange(varArrWhichYouWantTOPaste, rangeNameWhereYouWantTOPaste) 
End Sub 
Sub ArrayToRange(ByVal varArrayToPaste As Variant, ByVal rngRange As Range) 
    Dim strArr1()               As String
    Dim strArr2()               As String
    Dim lngLoop                 As Long
    Dim lngLoop1                As Long
    Dim lngCount                As Long
    Dim rngTemp                 As Range
    Dim strVal                  As String
    Dim lngSu                   As Long
 
    With Application
        lngSu = .ScreenUpdating
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
    End With 
    ReDim strArr1(1 To UBound(varArrayToPaste, 1), 1 To UBound(varArrayToPaste, 2))
    ReDim strArr2(1 To UBound(varArrayToPaste, 1) * UBound(varArrayToPaste, 2), 1 To 3)
    For lngLoop = 1 To UBound(varArrayToPaste, 1)
        For lngLoop1 = 1 To UBound(varArrayToPaste, 2)
            If Len(varArrayToPaste(lngLoop, lngLoop1)) > 255 Then
                lngCount = lngCount + 1
                strArr2(lngCount, 1) = varArrayToPaste(lngLoop, lngLoop1)
                strArr2(lngCount, 2) = lngLoop
                strArr2(lngCount, 3) = lngLoop1
                'strArr2(lngCount) = Cells(lngRngCount + 3, lngLoop1 + 23).Address(0, 0)
            Else
                If Left$(varArrayToPaste(lngLoop, lngLoop1), 1) = Chr(61) Then
                    strArr1(lngLoop, lngLoop1) = Chr(39) & varArrayToPaste(lngLoop, lngLoop1)
                Else
                    strArr1(lngLoop, lngLoop1) = varArrayToPaste(lngLoop, lngLoop1)
                End If
            End If
        Next lngLoop1
    Next lngLoop
    With rngRange
        '.Parent.UsedRange.ClearContents
        .Resize(UBound(strArr1, 1), UBound(strArr1, 2)) = strArr1
        If lngCount Then
            For lngLoop = 1 To lngCount
                'strVal = rngTemp.Range(strArr2(lngLoop)).Value
                If Left$(strArr2(lngLoop, 1), 1) = Chr(61) Then strArr2(lngLoop, 1) = Chr(39) & strArr2(lngLoop, 1)
                .Cells(CLng(strArr2(lngLoop, 2)), CLng(strArr2(lngLoop, 3))).Value = strArr2(lngLoop, 1)
                'If Left$(strVal, 1) = Chr(61) Then strVal = Chr(39) & strVal
                '.Range(strArr2(lngLoop)) = strVal
            Next lngLoop
        End If
    End With    
    Application.ScreenUpdating = lngSu    
    Erase strArr1
    Erase strArr2
    lngLoop = Empty
    lngLoop1 = Empty
    Set rngTemp = Nothing
    strVal = vbNullString
    lngSu = Empty    
End Sub

Find link below to see how we can send mail by using specific account in outlook:

http://www.rondebruin.nl/win/s1/outlook/account.htm

Sub test()
    Dim var         As Variant
    var = List_Files_In_Folder(“C:\”, “*.*”, True)
End Sub
Function List_Files_In_Folder(ByVal strFolderPath As String, Optional strFilter As String = “*.*”, Optional bolFullPath As Boolean = False) As Variant
    Dim strTemp                 As String
    Dim strFile                 As String
    Const strDelimeter          As String = “|”
    strTemp = Dir(strFolderPath & strFilter)
    If bolFullPath Then strTemp = strFolderPath & strTemp
    If strTemp = “” Then
        List_Files_In_Folder = False
        Exit Function
    End If
    Do
        strFile = Dir
        If strFile = “” Then Exit Do
        If bolFullPath Then strFile = strFolderPath & strFile
        strTemp = strTemp & strDelimeter & strFile
     Loop
    List_Files_In_Folder = Split(strTemp, strDelimeter)
End Function
Sub a()
Dim r As Range
Set r = Intersect(ActiveSheet.UsedRange.SpecialCells(xlCellTypeAllValidation), ActiveSheet.UsedRange.SpecialCells(xlCellTypeVisible))
If Intersect(ActiveCell, r) Is Nothing Then
    MsgBox “Cell has no validation”
Else
    MsgBox “Cell has validation”
End If
End Sub
Option Explicit
Option Compare Text
Private Const mc_strModuleName       As String = “modGetUNCPath”
Private Declare Function WNetGetConnection Lib “mpr.dll” Alias “WNetGetConnectionA” (ByVal lpszLocalName As String, ByVal lpszRemoteName As String, cbRemoteName As Long) As Long
‘Purpose   :    Returns the UNC Path given a path
‘Inputs    :    sPathName           The path to convert
‘Outputs   :    The UNC path of sPathName
‘Notes     :    Requires NT/2000
‘Revisions :
Function ConvertToUNC(sPathName As String) As String
    Dim szValue As String, szValueName As String, sUNCName As String
    Dim lErrCode As Long, lEndBuffer As Long
    Const lLenUNC As Long = 520
    ‘Return values for WNetGetConnection
    Const NO_ERROR As Long = 0
    Const ERROR_NOT_CONNECTED As Long = 2250
    Const ERROR_BAD_DEVICE = 1200&
    Const ERROR_MORE_DATA = 234
    Const ERROR_CONNECTION_UNAVAIL = 1201&
    Const ERROR_NO_NETWORK = 1222&
    Const ERROR_EXTENDED_ERROR = 1208&
    Const ERROR_NO_NET_OR_BAD_PATH = 1203&
    ‘Verify whether the disk is connected to the network
    If Mid$(sPathName, 2, 1) = “:” Then
        sUNCName = String$(lLenUNC, 0)
        lErrCode = WNetGetConnection(Left$(sPathName, 2), sUNCName, lLenUNC)
        lEndBuffer = InStr(sUNCName, vbNullChar) – 1
        ‘Can ignore the errors below (will still return the correct UNC)
        If lEndBuffer > 0 And (lErrCode = NO_ERROR Or lErrCode = ERROR_CONNECTION_UNAVAIL Or lErrCode = ERROR_NOT_CONNECTED) Then
            ‘Success
            sUNCName = Trim$(Left$(sUNCName, InStr(sUNCName, vbNullChar) – 1))
            ConvertToUNC = sUNCName & Mid$(sPathName, 3)
        Else
            ‘Error, return original path
            ConvertToUNC = sPathName
        End If
    Else
        ‘Already a UNC Path
        ConvertToUNC = sPathName
    End If
End Function
Option Explicit
Enum PathType
    VbFilePath = 0
    VbFolderPath = 1
End Enum
Function BrowseFile() As String
    BrowseFile = ConvertToUNC(getFilePath(“Select Database(Only MDB)”, “mdb”))
End Function
Function BrowseFolder() As String
    BrowseFolder = ConvertToUNC(getFilePath(“Select Output Folder Path”, , , False))
End Function
Function getFilePath(ByVal strTitle As String, _
                     Optional strFilter As String, _
                     Optional blnMultiSelect As Boolean = False, _
                     Optional blnSetDefaultFolder As Boolean = False, _
                     Optional blnFileBrowser As Boolean = True) As String
    Dim Fname           As Variant
    Dim strDefAppPath   As String
    Dim strFilePath     As String
    Dim strSavedPath    As String
    Dim intLoop         As Integer
    Select Case strFilter
        Case “mdb”
            strFilter = “Access Database Files (*.mdb*),*.mdb*”
        Case “xls”
            strFilter = “Excel Files (*.xls*),*.xls*”
        Case “csv”
            strFilter = “Excel Files (*.csv),*.csv”
    End Select
    If blnFileBrowser Then
        Fname = Application.GetOpenFilename(FileFilter:=strFilter, Title:=strTitle, MultiSelect:=blnMultiSelect)
        If IsArray(Fname) Then
            For intLoop = LBound(Fname) To UBound(Fname)
                If intLoop = LBound(Fname) Then
                    getFilePath = Fname(intLoop)
                Else
                    getFilePath = getFilePath & “;” & Fname(intLoop)
                End If
            Next intLoop
        Else
            If Fname = False Then
                getFilePath = “”
                Exit Function
            End If
            If Fname <> False Then
                getFilePath = Fname
            End If
        End If
    Else
        With CreateObject(“Shell.Application”)
            ‘Fname = .BrowseForFolder(hWnd:=0, sTitle:=strTitle, iOptions:=512, vRootFolder:=””)
            On Error Resume Next
            If blnSetDefaultFolder Then
                getFilePath = .BrowseForFolder(0, strTitle, 512, ActiveWorkbook.Path).self.Path
            Else
                getFilePath = .BrowseForFolder(0, strTitle, 512).self.Path
            End If
            On Error GoTo 0: Err.Clear
        End With
    End If
End Function
Function FileOrDirExists(ByVal PathName As String, Optional Path_Type As PathType = VbFilePath) As Boolean
‘Macro Purpose: Function returns TRUE if the specified file
‘               or folder exists, false if not.
‘PathName     : Supports Windows mapped drives or UNC
‘             : Supports Macintosh paths
‘File usage   : Provide full file path and extension
‘Folder usage : Provide full folder path
‘               Accepts with/without trailing “\” (Windows)
‘               Accepts with/without trailing “:” (Macintosh)
    Dim FSO                     As Object
    Set FSO = CreateObject(“scripting.filesystemobject”)
    ‘Ignore errors to allow for error evaluation
    With FSO
        On Error GoTo CheckExist
        If Path_Type = VbFolderPath Then
            .GetFolder (PathName)
        ElseIf Path_Type = VbFilePath Then
            .getfile (PathName)
        End If
    End With
     ‘Check if error exists and set response appropriately
CheckExist:
    Select Case Err.Number
    Case Is = 0
        FileOrDirExists = True
    Case Else
        FileOrDirExists = False
    End Select
     ‘Resume error checking
    On Error GoTo 0: Err.Clear
End Function
Function ListFiles( _
                                ByVal strSourcePath As String, _
                                Optional bolGetFullName As Boolean = False, _
                                Optional bolIncludeSubfolders As Boolean = False _
                   ) As String
    Dim objFiles                    As Object
    Dim objSubFolder                As Object
    Dim strFiles                    As String
    Const strDelima                 As String = “|”
    ‘Set MyObject = New Scripting.FileSystemObject
    ‘Set mySource = MyObject.GetFolder(mySourcePath)
    On Error Resume Next
    With CreateObject(“scripting.filesystemobject”).GetFolder(strSourcePath)
        strFiles = “”
        For Each objFiles In .files
            ‘strFiles = strFiles & IIf(strFiles = “”, “‘” & objFiles.Name & “‘”, “,'” & objFiles.Name & “‘”)
            If bolGetFullName Then
                strFiles = strFiles & IIf(strFiles = “”, objFiles, strDelima & objFiles)
            Else
                strFiles = strFiles & IIf(strFiles = “”, objFiles.Name, strDelima & objFiles.Name)
            End If
        Next objFiles
        If bolIncludeSubfolders Then
            For Each objSubFolder In .SubFolders
                Call ListFiles(objSubFolder.Path, True)
            Next objSubFolder
        End If
    End With
    On Error GoTo 0: Err.Clear
    ListFiles = strFiles
    Set objFiles = Nothing
    Set objSubFolder = Nothing
    strFiles = vbNullString
End Function