Étiquette : vba

  • Calculate the average age from a list of birthdates in Excel VBA

    Steps:

    1. Set up the Excel sheet with a list of birthdates.
    2. Write the VBA code to calculate each person’s age from their birthdate.
    3. Calculate the average age.
    4. Display the result.

    Example VBA Code:

    1. Excel Sheet Structure
    • Let’s assume birthdates are in column A, from A2 to A10 (you can adjust this range based on your actual data).
    • You want the average age to be displayed in cell B1.
    1. The VBA Code

    Here’s a sample VBA code to perform this task:

    Sub CalculateAverageAge()
        Dim ws As Worksheet
        Dim lastRow As Long
        Dim i As Long
        Dim totalAge As Double
        Dim numberOfPeople As Long
        Dim age As Integer
        Dim birthdate As Date
        Dim averageAge As Double   
        ' Reference to the active sheet
        Set ws = ThisWorkbook.Sheets("Sheet1") ' Change the sheet name if necessary   
        ' Find the last row of data in column A
        lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row   
        ' Initialize variables
        totalAge = 0
        numberOfPeople = 0   
        ' Loop through the birthdates (column A)
        For i = 2 To lastRow ' Start at row 2 to skip headers
            ' Check if the cell contains a valid date
            If IsDate(ws.Cells(i, 1).Value) Then
                ' Get the birthdate
                birthdate = ws.Cells(i, 1).Value
                ' Calculate age
                age = DateDiff("yyyy", birthdate, Date)
                ' Adjust if the birthday hasn't occurred yet this year
                If Month(birthdate) > Month(Date) Or (Month(birthdate) = Month(Date) And Day(birthdate) > Day(Date)) Then
                    age = age - 1
                End If
                ' Add the age to the total
                totalAge = totalAge + age
                ' Increment the number of people
                numberOfPeople = numberOfPeople + 1
            End If
        Next i   
        ' Calculate the average age
        If numberOfPeople > 0 Then
            averageAge = totalAge / numberOfPeople
            ' Display the average age in cell B1
            ws.Cells(1, 2).Value = "Average Age: " & averageAge
        Else
            ' If no valid data is found
            ws.Cells(1, 2).Value = "No valid data"
        End If
    End Sub

    Explanation of the Code:

    1. Reference to the active sheet: The code starts by setting a reference to the active worksheet (in this case, « Sheet1 »). If your sheet has a different name, update this line:
    Set ws = ThisWorkbook.Sheets("Sheet1")

    2. Finding the last row: The lastRow variable is used to find the last row of data in column A (where the birthdates are). This way, the code adjusts automatically if you add or remove data.

    3. Calculating the age:

      • The code loops through each cell in column A (from row 2 to the last row of data).
      • For each valid birthdate, it calculates the age using the DateDiff function, which returns the difference in years between the birthdate and the current date.
      • If the birthday hasn’t occurred yet this year, the code subtracts 1 from the age to adjust it.

    4. Calculating the average age:

      • The sum of ages is stored in totalAge, and the number of people is counted in numberOfPeople.
      • After the loop, if any valid birthdates were found, the average age is calculated by dividing the total age by the number of people.

    5. Displaying the result:

      • If there are valid dates, the average age is displayed in cell B1.
      • If no valid data is found, the message « No valid data » is shown in cell B1.

    How to Run This Code:

    1. Open the VBA editor:
      • In Excel, press Alt + F11 to open the VBA editor.
    2. Insert a Module:
      • Go to Insert > Module to add a new module.
    3. Copy and Paste the Code:
      • Paste the provided VBA code into the new module.
    4. Run the Code:
      • Press F5 or go to Run > Run Sub/UserForm to execute the macro and calculate the average age.

    After running the code, the average age will be displayed in cell B1 of your worksheet. If there’s no valid data in column A, the cell will display « No valid data ».

  • Calculate a person’s age from their birthdate in Excel VBA

    This code takes into account years, months, and days, ensuring accurate results even considering whether the birthday has already passed this year or not.

    Step 1: Access the VBA Editor

    1. Open Excel and press Alt + F11 to open the VBA editor.
    2. In the VBA editor, go to Insert > Module to create a new module.
    3. Copy and paste the following code into the new module.

    VBA Code: Calculate Age

    Function CalculateAge(BirthDate As Date) As String
        ' This function calculates age based on the birthdate   
        Dim CurrentDate As Date
        Dim AgeYears As Integer
        Dim AgeMonths As Integer
        Dim AgeDays As Integer
        Dim BirthdayThisYear As Date  
        ' Get the current date
        CurrentDate = Date   
        ' Calculate the birthday for this year
        BirthdayThisYear = DateSerial(Year(CurrentDate), Month(BirthDate), Day(BirthDate))   
        ' If the birthday hasn't passed yet this year, subtract 1 from the age
        If CurrentDate < BirthdayThisYear Then
            AgeYears = Year(CurrentDate) - Year(BirthDate) - 1
        Else
            AgeYears = Year(CurrentDate) - Year(BirthDate)
        End If   
        ' Calculate the age in months
        If Month(CurrentDate) < Month(BirthDate) Or (Month(CurrentDate) = Month(BirthDate) And Day(CurrentDate) < Day(BirthDate)) Then
            AgeMonths = Month(CurrentDate) - Month(BirthDate) + 12
        Else
            AgeMonths = Month(CurrentDate) - Month(BirthDate)
        End If   
        ' Calculate the remaining days
        If Day(CurrentDate) < Day(BirthDate) Then
            ' If the current day is smaller than the birth day, calculate the remaining days of the previous month
            AgeDays = Day(CurrentDate) + (Day(DateSerial(Year(CurrentDate), Month(CurrentDate), 0)) - Day(BirthDate))
        Else
            AgeDays = Day(CurrentDate) - Day(BirthDate)
        End If  
        ' Return the age as a string in the format "x years, y months, z days"
        CalculateAge = AgeYears & " years, " & AgeMonths & " months, " & AgeDays & " days"
    End Function

    Explanation of the Code

    1. Variable Declaration:
      • BirthDate: The person’s birthdate, passed as an argument to the function.
      • CurrentDate: The current date.
      • AgeYears, AgeMonths, AgeDays: These variables will hold the person’s age in years, months, and days, respectively.
      • BirthdayThisYear: The calculated birthday for the current year.
    2. Age Calculation (Years):
      • If the birthday hasn’t passed this year yet, subtract 1 year from the calculated age.
    3. Age Calculation (Months):
      • If the current month is earlier than the birth month or the current month is the same as the birth month but the birthday hasn’t occurred yet, adjust the month difference by adding 12 months.
    4. Remaining Days Calculation:
      • If the current day is less than the birth day in the month, calculate how many days are left in the previous month.
    5. Returning the Result:
      • The function returns the age as a text string in the format: « x years, y months, z days ».

    Step 2: Using the Function in Excel

    1. Go back to your Excel sheet.
    2. Use the function like a normal Excel function. For example, in a cell, you would type:
    =CalculateAge(A1)

    Where A1 is the cell containing the birthdate. Make sure the cell contains a valid date format.

    Example

    If the birthdate is March 25, 1990, and today’s date is November 28, 2024, the function will return:

    34 years, 8 months, 3 days

    Notes:

    • If you prefer to show the age in a different format, such as just in years, you can modify the code by removing or adjusting the portion that calculates months and days.
    • This function accounts for all date-related nuances (including leap years) and will give an accurate result, even if the birthday is yet to come this year

     

  • Adjusted R-squared calculation using VBA in Excel.

    What is Adjusted R-squared?

    The Adjusted R-squared (R² adjusted) is a statistical measure that provides a more accurate representation of the goodness of fit for a regression model. Unlike the traditional R-squared (R²), which can be misleading when you add more predictors to the model, the adjusted R² adjusts for the number of predictors and penalizes for overfitting.

    Adjusted R-squared Formula:

    Adjusted R-squared ) = 1 – ((1 – R-squared) * ((n – 1) / (n – k – 1)))

    Where:

    • R-squared is the coefficient of determination (regular R-squared),
    • n is the number of data points (observations),
    • k is the number of independent variables (predictors).

    Steps to Calculate Adjusted R-squared:

    1. Calculate R-squared: This is computed from the regression model between the dependent variable and the independent variables.
    2. Obtain nnn and kkk: nnn is the number of observations, and kkk is the number of predictors.
    3. Apply the Adjusted R-squared formula.

    VBA Code Example:

    Sub CalculateAdjustedRSquared()
        Dim ws As Worksheet
        Dim rngY As Range, rngX As Range
        Dim n As Long, k As Long
        Dim coeff As Double
        Dim residualSum As Double
        Dim totalSum As Double
        Dim SSR As Double, SST As Double, R2 As Double
        Dim R2Adjusted As Double
        ' Define worksheet and data ranges
        Set ws = ThisWorkbook.Sheets("Sheet1") ' Change to your sheet name
        Set rngY = ws.Range("B2:B101") ' Range for dependent variable Y
        Set rngX = ws.Range("A2:A101") ' Range for independent variable X
        ' Number of observations (n) and number of predictors (k)
        n = rngY.Rows.Count
        k = 1 ' For this example, we assume a simple linear regression (1 predictor X)
        ' Perform linear regression to get the coefficients
        With Application.WorksheetFunction
            coeff = .LinEst(rngY, rngX)(1, 1) ' Coefficient for the regression line
        End With
        ' Calculate the total sum of squares (SST)
        totalSum = 0
        For i = 1 To n
            totalSum = totalSum + (rngY.Cells(i, 1).Value - Application.WorksheetFunction.Average(rngY)) ^ 2
        Next i
        ' Calculate the sum of squared residuals (SSR)
        residualSum = 0
        For i = 1 To n
            residualSum = residualSum + (rngY.Cells(i, 1).Value - coeff * rngX.Cells(i, 1).Value) ^ 2
        Next i
        ' Calculate R-squared (R2)
        R2 = 1 - (residualSum / totalSum)
        ' Calculate Adjusted R-squared (R2 adjusted)
        R2 Adjusted = 1 - ((1 - R2) * (n - 1)) / (n - k - 1)
        ' Display the Adjusted R-squared result
        MsgBox "The Adjusted R-squared is: " & R2Adjusted
    End Sub

    Explanation of the Code:

    1. Variable Declaration:
      • ws: The worksheet object that contains the data.
      • rngY and rngX: Ranges for the dependent variable YYY and the independent variable XXX.
      • n: The number of observations (rows of data).
      • k: The number of independent variables (predictors). For a simple linear regression, this is 1.
      • R2: The R-squared value.
      • R2Adjusted: The adjusted R-squared value.
    2. Setting the Worksheet and Data Ranges: The code assumes your data is in « Sheet1 » with the dependent variable YYY in column B and the independent variable XXX in column A, from rows 2 to 101.
    3. Linear Regression Calculation:
      • The LinEst function in Excel calculates the slope (regression coefficient) of the linear model. In this case, it’s used for simple linear regression, so it’s accessing the first coefficient in the result.
    4. Sum of Squares Calculations:
      • SST (Total Sum of Squares): Measures the total variation in the dependent variable.
      • SSR (Sum of Squared Residuals): Measures the variation not explained by the regression model.
      • These are calculated manually by iterating through the data points.
    5. R-squared and Adjusted R-squared:
      • R-squared is calculated as 1−SSRSST1 – \frac{SSR}{SST}1−SSTSSR​.
      • Adjusted R-squared is then computed using the formula, which adjusts for the number of predictors kkk and the sample size nnn.
    6. Displaying the Result: The adjusted R-squared value is shown in a message box.

    How to Use:

    • Place your data in columns A and B in the Excel sheet (adjust ranges if your data set is larger or smaller).
    • Run the macro by pressing Alt + F8 and selecting CalculateAdjustedRSquared.
    • The result will be shown in a message box.

    Customization:

    • Multiple predictors (Multiple Linear Regression): If you have more than one predictor (e.g., X1,X2,…,XkX1, X2, \ldots, XkX1,X2,…,Xk), adjust the range of rngX to include the additional columns, like Set rngX = ws.Range(« A2:C101 ») for 3 predictors.
    • More Observations: Adjust the ranges (B2:B101 and A2:A101) to include more data points if necessary.
  • Automatically update data connections in Excel VBA

    The following example will allow you to refresh the data connections every time a specific sheet is opened or even schedule it to run at regular intervals. The core idea is to use the Workbook.Connections object to access all data connections and refresh them.

    Objective of the VBA Code:

    1. Automatically update all data connections in the workbook.
    2. Ensure all connections are refreshed before working with the data.
    3. Use a workbook open event or a button to trigger the refresh.

    VBA Code to Refresh Data Connections

    1. Refresh Connections when the Workbook is Opened (Using Workbook_Open Event)

    If you want to update data connections automatically every time the workbook is opened, you should add the following code inside the ThisWorkbook module.

    Steps:

    1. Open the VBA editor by pressing Alt + F11.
    2. In the « VBAProject » panel, find « ThisWorkbook » and double-click it to open the code window.
    3. Copy and paste the following code into the code window.
    Private Sub Workbook_Open()
        ' Call the function to refresh all data connections
        UpdateAllConnections
    End Sub
    
    Sub UpdateAllConnections()
        Dim conn As Object
        ' Loop through all data connections in the workbook
        For Each conn In ThisWorkbook.Connections
            ' Try to refresh each connection
            On Error Resume Next ' Ignore error if connection fails
            conn.Refresh
            On Error GoTo 0 ' Reset error handling
        Next conn
        MsgBox "All connections have been updated!", vbInformation
    End Sub

    Code Explanation:

    • Workbook_Open: This is an event that is automatically executed when the workbook is opened. It calls the UpdateAllConnections function that refreshes all connections.
    • UpdateAllConnections: This function loops through all data connections in the workbook (ThisWorkbook.Connections) and attempts to refresh them using conn.Refresh.
    • On Error Resume Next: This line ensures that any errors (like if a connection cannot be refreshed) are ignored.
    • MsgBox: A message box is displayed once all connections have been refreshed.
    1. Refresh Connections Using a Button

    If you prefer to have a button on a worksheet to trigger the refresh of connections, follow these steps:

    Steps:

    1. In your Excel sheet, insert a form button (via the Developer tab > Insert > Button).
    2. Link the button to a macro that will refresh the connections.
    3. Create a standard module to add the following code.

    VBA Code:

    Sub RefreshConnections()
        Dim conn As Object
        ' Loop through to refresh all connections
        For Each conn In ThisWorkbook.Connections
            ' Try to refresh each connection
            On Error Resume Next
            conn.Refresh
            On Error GoTo 0
        Next conn
        MsgBox "All connections have been updated!", vbInformation
    End Sub

    Code Explanation:

    • This code is very similar to the one used in the Workbook_Open event, except it is triggered manually through a button.
    • The RefreshConnections procedure is linked to the button you inserted in the worksheet. When the user clicks the button, all connections are refreshed.
    1. Automatically Refresh Connections at Regular Intervals (Optional)

    If you want the connections to refresh automatically at regular intervals, you can use the following code, which should be placed in a standard module.

    VBA Code for Regular Interval Refresh:

    Dim NextRefresh As Date
    Sub StartAutoRefresh()
        ' Start automatic refresh every X minutes
        NextRefresh = Now + TimeValue("00:05:00") ' Refresh every 5 minutes
        Application.OnTime NextRefresh, "AutoRefresh"
    End Sub
    
    Sub AutoRefresh()
        ' Refresh all connections
        Call UpdateAllConnections
        ' Restart automatic refresh
        Call StartAutoRefresh
    End Sub
    
    Sub UpdateAllConnections()
        Dim conn As Object
        ' Loop to refresh all connections
        For Each conn In ThisWorkbook.Connections
            On Error Resume Next
            conn.Refresh
            On Error GoTo 0
        Next conn
        MsgBox "All connections have been updated!", vbInformation
    End Sub

    Code Explanation:

    • StartAutoRefresh: This macro starts the auto-refresh process by setting the next refresh time using Application.OnTime.
    • AutoRefresh: This macro is automatically called at regular intervals to refresh all connections.
    • NextRefresh: This variable defines the time for the next refresh (here, it’s set to 5 minutes after the first execution).

    Conclusion:

    You now have a complete VBA code for automatically updating data connections in an Excel workbook. You can run it on workbook open, via a button, or on a scheduled timer at regular intervals.

  • Automating transportation and logistics planning in Excel using VBA

    Automating transportation and logistics planning in Excel using VBA can significantly enhance process efficiency and reduce human errors. Here is a detailed VBA code example that can be used to automate a part of the transport and logistics planning, such as assigning deliveries to drivers or planning routes. This example scenario includes the following steps:

    1. Data Entry: An Excel table contains delivery-related information, including departure address, destination, delivery date, cargo weight, etc.
    2. Automation of Assignment: The VBA code will analyze the data and assign each delivery to a driver or vehicle, based on criteria (such as vehicle capacity, proximity, etc.).
    3. Route Planning: The code can also plan the route based on distance or priority.

    Structure of the Data in Excel

    Let’s assume you have a table in Excel with the following columns:

    • A: Delivery ID
    • B: Departure Address
    • C: Destination Address
    • D: Cargo Weight
    • E: Delivery Date
    • F: Assigned Driver
    • G: Assigned Vehicle
    • H: Delivery Status (e.g., « Planned », « In Progress », « Delivered »)

    Example of VBA Code

    Sub TransportLogisticsPlanning()
        ' Declare variables
        Dim ws As Worksheet
        Dim row As Long
        Dim departureAddress As String
        Dim destinationAddress As String
        Dim weight As Double
        Dim deliveryDate As Date
        Dim availableDriver As String
        Dim availableVehicle As String
        Dim distance As Double
        Dim maxWeight As Double
        Dim vehicleCapacity As Double   
        ' Set reference to the planning table (Excel sheet)
        Set ws = ThisWorkbook.Sheets("Deliveries") ' Replace "Deliveries" with the name of your sheet   
        ' Initialize weight limits (e.g., max weight of a vehicle)
        vehicleCapacity = 1000 ' Example capacity in kg   
        ' Loop through all rows in the table (starting from row 2)
        row = 2
        Do While ws.Cells(row, 1).Value <> ""       
            ' Retrieve delivery data
            departureAddress = ws.Cells(row, 2).Value
            destinationAddress = ws.Cells(row, 3).Value
            weight = ws.Cells(row, 4).Value
            deliveryDate = ws.Cells(row, 5).Value       
            ' Check if the cargo weight is within the vehicle's capacity
            If weight <= vehicleCapacity Then           
                ' If the weight is within the limit, search for an available driver and vehicle
                availableDriver = FindAvailableDriver(deliveryDate)
                availableVehicle = FindAvailableVehicle(deliveryDate)           
                ' If a driver and vehicle are available, assign them to the delivery
                If availableDriver <> "" And availableVehicle <> "" Then
                    ws.Cells(row, 6).Value = availableDriver ' Assign the driver
                    ws.Cells(row, 7).Value = availableVehicle ' Assign the vehicle
                    ws.Cells(row, 8).Value = "Planned" ' Set status to "Planned"
                Else
                    ws.Cells(row, 8).Value = "No resources available"
                End If           
            Else
                ' If the weight exceeds the vehicle's capacity, display a message
                ws.Cells(row, 8).Value = "Weight too high"
            End If       
            ' Move to the next row
            row = row + 1
        Loop
    End Sub
    
    Function FindAvailableDriver(deliveryDate As Date) As String
        ' Example function to find an available driver for the given delivery date
        Dim driver As String
        driver = ""   
        ' Simplified: the example returns a fictional driver if available
        ' Add logic here to search in a table of available drivers
        If deliveryDate >= Date Then
            driver = "Driver 1" ' Replace with dynamic search
        End If  
        FindAvailableDriver = driver
    End Function
    
    Function FindAvailableVehicle(deliveryDate As Date) As String
        ' Example function to find an available vehicle for the given delivery date
        Dim vehicle As String
        vehicle = ""  
        ' Simplified: the example returns a fictional vehicle if available
        ' Add logic here to search in a table of available vehicles
        If deliveryDate >= Date Then
            vehicle = "Vehicle A" ' Replace with dynamic search
        End If
        FindAvailableVehicle = vehicle
    End Function

    Code Explanation

    1. Variables and Data Structure:
      • The code starts by declaring variables for the worksheet (ws), the delivery data for each row (departure address, destination, weight, etc.), and auxiliary functions to determine available resources (driver and vehicle).
    2. Loop Through Data Rows:
      • The code loops through each row in the planning table, starting at row 2 (assuming row 1 contains headers).
      • For each delivery, it checks if the cargo weight is within the vehicle’s capacity (vehicleCapacity). If yes, it proceeds to check for available drivers and vehicles for the specified delivery date.
    3. Auxiliary Functions:
      • The functions FindAvailableDriver and FindAvailableVehicle are simplified examples that return an available driver and vehicle. In a real application, these functions could perform searches in other sheets or tables that contain the schedules and availability of drivers and vehicles.
    4. Assigning Resources:
      • If a driver and vehicle are available for the specified delivery date, the code assigns these resources to the delivery by updating the corresponding columns in the Excel table (driver and vehicle assigned).
      • The delivery status is updated to « Planned » if the assignment is successful, or to « No resources available » or « Weight too high » if the planning fails.
    5. Delivery Status:
      • The status of the delivery is updated, either to « Planned » if successfully assigned, or to « No resources available » or « Weight too high » if there are issues with assigning resources.

    Customization and Extension

    • Dynamic Resource Search: You can replace the FindAvailableDriver and FindAvailableVehicle functions with dynamic searches in availability tables that contain actual schedules of drivers and vehicles.
    • Distance Calculation: You can integrate APIs like Google Maps to calculate the distance between departure and destination addresses and optimize routes.
    • Priority Management: You can add logic to assign priorities to urgent deliveries and allocate resources accordingly.

    Conclusion

    This VBA code provides a foundation for automating the planning of deliveries and logistics resources in Excel. It can be customized based on your specific needs, such as integrating advanced features for route optimization or managing a larger number of resources.

  • Automate text mining and sentiment analysis processes with Excel VBA

    Steps:

    1. Sign up for Azure Cognitive Services:
      • First, you need to sign up for the Text Analytics API from Microsoft Azure.
      • Once you sign up, you will get an API key and a endpoint URL.
    2. Prepare Your Excel File:
      • Create an Excel file with text data (for example, in column A).
      • In column B, we will display the sentiment analysis result (positive, negative, or neutral).
    3. VBA Code for Text Cleaning and Calling the Azure API.

    Detailed VBA Code:

    Sub AnalyzeSentiment()
        ' Variables
        Dim http As Object
        Dim url As String
        Dim apiKey As String
        Dim text As String
        Dim jsonRequest As String
        Dim jsonResponse As String
        Dim sentiment As String
        Dim i As Long   
        ' Insert your API Key and Endpoint URL here
        apiKey = "YOUR_API_KEY"
        url = "https://<your_endpoint>.cognitiveservices.azure.com/text/analytics/v3.0/sentiment"
        ' Create HTTP object to send the request
        Set http = CreateObject("MSXML2.XMLHTTP")   
        ' Loop through each row and analyze the sentiment
        For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
            text = Cells(i, 1).Value       
            ' Clean the text (remove unnecessary spaces and convert to lowercase)
            text = Trim(LCase(text))       
            ' Create JSON request
            jsonRequest = "{""documents"":[{""id"":""1"",""text"":""" & text & """}]}"
            ' Send the HTTP POST request
            http.Open "POST", url, False
            http.setRequestHeader "Content-Type", "application/json"
            http.setRequestHeader "Ocp-Apim-Subscription-Key", apiKey
            http.Send jsonRequest
            ' Get the response JSON
            jsonResponse = http.responseText       
            ' Extract the sentiment from the response
            sentiment = GetSentimentFromResponse(jsonResponse)
            ' Output the sentiment in column B
            Cells(i, 2).Value = sentiment
        Next i
        ' Release the memory
        Set http = Nothing
    End Sub
    ' Function to extract sentiment from the JSON response
    Function GetSentimentFromResponse(response As String) As String
        Dim startPos As Long
        Dim endPos As Long
        Dim sentiment As String
        ' Find the position of sentiment in the JSON response
        startPos = InStr(response, """sentiment"":""") + Len("""sentiment"":""")
        endPos = InStr(startPos, response, """")
        ' Extract sentiment value
        sentiment = Mid(response, startPos, endPos - startPos)
        ' Return the sentiment
        GetSentimentFromResponse = sentiment
    End Function

    Detailed Explanation of the Code:

    1. Variable Declarations:
      • http: An object used to send HTTP requests.
      • url: The endpoint URL of the Azure Cognitive Services Text Analytics API.
      • apiKey: Your API key to authenticate requests.
      • text: The text you want to analyze.
      • jsonRequest: The JSON structure containing the text to send in the request.
      • jsonResponse: The JSON response returned by the API after analyzing the text.
      • sentiment: The sentiment (positive, negative, or neutral) extracted from the API’s response.
    2. Sending Request to Azure API:
      • The text is first cleaned by trimming spaces and converting it to lowercase.
      • A POST request is sent to the Azure API with the cleaned text in JSON format.
      • The API processes the text and returns a JSON response containing the sentiment analysis.
    3. Extracting the Sentiment from the Response:
      • The function GetSentimentFromResponse extracts the sentiment value (positive, negative, or neutral) from the JSON response by searching for the « sentiment » key.
    4. Displaying the Result:
      • The sentiment value is placed in column B of the Excel sheet, corresponding to the text in column A.

    Prerequisites:

    1. Reference to Microsoft XML Library:
      • Open the VBA editor (Alt + F11).
      • Go to Tools > References.
      • Check the box for Microsoft XML, v6.0 (or similar) to enable the use of MSXML2.XMLHTTP object.
    2. Error Handling:
      • The code does not handle all potential errors. It’s a good idea to check if the API responds correctly and implement error handling for issues such as invalid API keys, API downtime, or network errors.

    How to Test:

    1. Put some text data in column A (e.g., customer reviews or feedback).
    2. Run the AnalyzeSentiment macro to analyze the sentiment of each text. The sentiment (positive, negative, or neutral) will be displayed in column B.

    Limitations:

    • API Quotas: Ensure you stay within the limits of your Azure API plan (e.g., the number of requests per month).
    • Language: The Azure Cognitive Services API supports multiple languages. Make sure the text you’re analyzing is supported by the API.

    This process allows you to automate sentiment analysis directly within Excel using VBA and external Azure services, which can be very powerful for analyzing large volumes of textual data.

     

  • Automating the retrieval of stock market data in Excel using VBA

    Automating the retrieval of stock market data in Excel using VBA can be extremely useful for investors and financial analysts. Below is a detailed guide and code to retrieve stock market data using an API (e.g., Alpha Vantage) and display it in an Excel spreadsheet.

    Step 1: Obtain an Alpha Vantage API Key

    1. Visit Alpha Vantage and create an account.
    2. Obtain your free API key.

    Step 2: Write VBA Code to Retrieve Stock Data

    Follow these steps to set up your VBA code.

    1. Open the VBA Editor
    • Press Alt + F11 to open the VBA editor.
    • Go to Insert > Module to add a new module.
    1. Add VBA Code to Retrieve Stock Data

    Here’s an example of VBA code to retrieve stock data from Alpha Vantage. This code fetches the closing price of a specific stock and displays it in an Excel sheet.

    Sub GetStockData()
        ' Declare variables
        Dim Symbol As String
        Dim APIKey As String
        Dim URL As String
        Dim httpRequest As Object
        Dim JSON As Object
        Dim ClosePrice As Double
        Dim LastDate As String   
        ' Enter the stock symbol and your API key
        Symbol = "AAPL" ' Example: Apple Inc. (change as needed)
        APIKey = "your_api_key" ' Replace with your Alpha Vantage API key   
        ' Alpha Vantage API URL (Daily Time Series)
        URL = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=" & Symbol & "&apikey=" & APIKey   
        ' Create an HTTP request to fetch the data
        Set httpRequest = CreateObject("MSXML2.XMLHTTP")
        httpRequest.Open "GET", URL, False
        httpRequest.Send   
        ' Check if the request was successful
        If httpRequest.Status = 200 Then
            ' Parse the JSON response
            Set JSON = JsonConverter.ParseJson(httpRequest.responseText)       
            ' Get the last date and the closing price
            LastDate = JSON("Time Series (Daily)").Keys(1)
            ClosePrice = JSON("Time Series (Daily)")(LastDate)("4. close")       
            ' Display the results in Excel cells
            Range("A1").Value = "Symbol"
            Range("B1").Value = Symbol
            Range("A2").Value = "Last Close Date"
            Range("B2").Value = LastDate
            Range("A3").Value = "Closing Price"
            Range("B3").Value = ClosePrice       
        Else
            MsgBox "Error retrieving data: " & httpRequest.Status
        End If   
    End Sub

    Detailed Explanation of the Code

    1. Variable Declarations:
      • Symbol: The stock symbol (e.g., « AAPL » for Apple).
      • APIKey: Your Alpha Vantage API key.
      • URL: The API URL to fetch daily time series data for the specified stock symbol.
      • httpRequest: An object to send an HTTP request to the API.
      • JSON: An object to parse the JSON response returned by the API.
      • ClosePrice and LastDate: Variables to store the closing price and the date of the last stock closing.
    2. Fetching Data from the API:
      • The code sends an HTTP GET request to the Alpha Vantage API to retrieve daily stock data.
      • If the request is successful (status = 200), it parses the JSON response and extracts the date and closing price of the most recent stock data.
    3. Displaying Data in Excel:
      • The stock symbol, last close date, and closing price are then displayed in cells A1, B1, A2, B2, etc.

    Step 3: Add a JSON Parser for VBA

    Alpha Vantage returns data in JSON format, but Excel VBA doesn’t natively understand JSON. To parse the response, you need a JSON parser like VBA-JSON.

    Here’s how to add it:

    1. Download the VBA-JSON library from GitHub.
    2. Copy the JsonConverter.bas file and import it into your VBA editor (via File > Import File).
    3. The code above uses this module to parse the JSON data.

    Step 4: Test and Run the Code

    1. Close the VBA editor.
    2. In Excel, press Alt + F8, select GetStockData, and click Run.
    3. You will see the stock symbol, last close date, and closing price displayed in the specified cells of your Excel sheet.

    Step 5: Customization

    • You can customize the stock symbol (e.g., « GOOGL » for Google) or even automate retrieving multiple stock symbols listed in your Excel sheet.
    • You can also extend the code to retrieve other financial data like open price, high, low, or volume.

    Note

    The free Alpha Vantage API allows a limited number of requests per minute (5 requests per minute for free accounts). If you need more frequent data retrieval, you can either upgrade to a paid plan or consider using another service or API that suits your needs.

    Troubleshooting

    • Ensure that your API key is valid and hasn’t expired.
    • Ensure that the API URL is correct and the symbol you’re using is supported.
  • Automating statistical analysis in Excel using VBA

    Automating statistical analysis in Excel using VBA can help perform complex calculations quickly and generate reports repetitively without having to manually enter formulas each time. Below is a detailed VBA code that performs basic statistical analysis such as mean, standard deviation, variance, quartiles, and generates an automated report. The code is structured to work with data in a specific range of cells.

    1. Objective

    The goal of this code is to automate the statistical analysis of the following metrics:

    • Mean
    • Standard Deviation
    • Variance
    • Median
    • Quartiles (Q1, Q2, Q3)
    • Min / Max

    The report will be generated in a new worksheet.

    1. VBA Code: Automate Statistical Analysis

    Step 1: Create a VBA Module

    1. Open Excel and press Alt + F11 to access the VBA editor.
    2. In the « Insert » menu, select « Module » to create a new module.
    3. Paste the following code into this module.
    Sub AutomateStatisticalAnalysis()
        ' Declare variables
        Dim wsData As Worksheet
        Dim wsReport As Worksheet
        Dim DataRange As Range
        Dim LastRow As Long   
        ' Assign the data sheet and create a new sheet for the report
        Set wsData = ThisWorkbook.Sheets("Data") ' Replace "Data" with the name of your data sheet
        Set wsReport = ThisWorkbook.Sheets.Add
        wsReport.Name = "Statistical_Report"   
        ' Determine the last row with data in column A
        LastRow = wsData.Cells(wsData.Rows.Count, 1).End(xlUp).Row   
        ' Define the data range for analysis (example: from A2 to A100)
        Set DataRange = wsData.Range("A2:A" & LastRow) ' Adjust range as needed   
        ' Add a header to the report
        wsReport.Cells(1, 1).Value = "Statistical Analysis Report"
        wsReport.Cells(2, 1).Value = "Metric"
        wsReport.Cells(2, 2).Value = "Value"   
        ' Perform the statistical calculations and insert them into the report
        wsReport.Cells(3, 1).Value = "Mean"
        wsReport.Cells(3, 2).Value = WorksheetFunction.Average(DataRange)   
        wsReport.Cells(4, 1).Value = "Standard Deviation"
        wsReport.Cells(4, 2).Value = WorksheetFunction.StDev(DataRange)   
        wsReport.Cells(5, 1).Value = "Variance"
        wsReport.Cells(5, 2).Value = WorksheetFunction.Var(DataRange)   
        wsReport.Cells(6, 1).Value = "Median"
        wsReport.Cells(6, 2).Value = WorksheetFunction.Median(DataRange)   
        wsReport.Cells(7, 1).Value = "Quartile 1 (Q1)"
        wsReport.Cells(7, 2).Value = WorksheetFunction.Quartile(DataRange, 1)   
        wsReport.Cells(8, 1).Value = "Quartile 2 (Q2)"
        wsReport.Cells(8, 2).Value = WorksheetFunction.Quartile(DataRange, 2)   
        wsReport.Cells(9, 1).Value = "Quartile 3 (Q3)"
        wsReport.Cells(9, 2).Value = WorksheetFunction.Quartile(DataRange, 3)   
        wsReport.Cells(10, 1).Value = "Min Value"
        wsReport.Cells(10, 2).Value = WorksheetFunction.Min(DataRange)   
        wsReport.Cells(11, 1).Value = "Max Value"
        wsReport.Cells(11, 2).Value = WorksheetFunction.Max(DataRange)   
        ' Format the report
        wsReport.Rows(1).Font.Bold = True
        wsReport.Rows(2).Font.Bold = True
        wsReport.Columns("A:B").AutoFit
        wsReport.Range("A1:B11").Borders(xlEdgeBottom).LineStyle = xlContinuous   
        ' Display a message
        MsgBox "Statistical analysis has been successfully generated in the sheet " & wsReport.Name, vbInformation
    End Sub
    1. Explanation of the Code

    Declaring Variables:

      • wsData: Refers to the worksheet that contains the data to be analyzed.
      • wsReport: Refers to the worksheet where the statistical results will be displayed.
      • DataRange: The range of cells that contains the data for statistical analysis.
      • LastRow: Used to determine the last row with data in column A (adjust if necessary).

    Assigning Worksheets:

      • The code refers to the « Data » sheet for the source data and creates a new « Statistical_Report » sheet to display the results.

    Determining the Data Range:

      • DataRange is defined as the range of cells containing the data (from A2 to the last row in column A).

    Performing Statistical Calculations:

      • The code uses the WorksheetFunction object to calculate the following statistics:
        • Mean with Average
        • Standard Deviation with StDev
        • Variance with Var
        • Median with Median
        • Quartiles with Quartile
        • Min and Max with Min and Max
    • Inserting Results into the Report:
      • Each statistic is inserted into the corresponding cells in the new sheet.
    • Formatting the Report:
      • The report is formatted with bold headers and auto-fitting columns for better readability.
      • Borders are added to the range for better structure.
    • Information Message:
      • Once the analysis is complete, a message box will appear to inform the user that the report has been generated.
    1. Using the Code

    Make sure your data is in the « Data » sheet, with the values you want to analyze in column A (or adjust the range in the code if needed).

    Go to the VBA editor (Alt + F11), create a module, and paste the code.

    Run the code by pressing F5 or using the « Run » button in the VBA editor.

    A new sheet will be created with the statistical analysis report.

    1. Conclusion

    This VBA code simplifies statistical analysis by automating calculations and quickly generating a clean report in a new worksheet. You can expand this code to include more complex analyses, charts, or additional statistical measures based on your needs.

     

  • Automate resource allocation processes in Excel with VBA

    The code allocates resources to tasks based on their availability and capacity.

    Scenario

    Let’s assume you have a worksheet containing:

    • Resources: employees, machines, etc., with information about their capacity (e.g., work hours per day) and available hours.
    • Tasks: each task has a required number of hours that need to be allocated from available resources.

    Goal

    We want to automate the allocation of resources to tasks based on resource capacity and task requirements.

    Excel Sheet Structure

    Resources Sheet:

    Resource Capacity per Hour Available Hours Total Capacity
    Employee A 5 20 100
    Employee B 3 30 90

    Tasks Sheet:

    Task Required Hours Assigned Resource
    Task 1 50
    Task 2 40

    VBA Code

    Sub AllocateResources()
        ' Variables
        Dim wsResources As Worksheet
        Dim wsTasks As Worksheet
        Dim i As Long, j As Long
        Dim resName As String
        Dim resCapacity As Double
        Dim resAvailable As Double
        Dim taskRequiredHours As Double
        Dim totalAllocated As Double
        Dim taskName As String
        Dim remainingHours As Double
        Dim allocation As Double   
        ' References to the sheets
        Set wsResources = ThisWorkbook.Sheets("Resources")
        Set wsTasks = ThisWorkbook.Sheets("Tasks")   
        ' Loop through each task
        For i = 2 To wsTasks.Cells(Rows.Count, 1).End(xlUp).Row       
            ' Get task name and required hours
            taskName = wsTasks.Cells(i, 1).Value
            taskRequiredHours = wsTasks.Cells(i, 2).Value
            remainingHours = taskRequiredHours       
            ' Allocate resources to the task
            For j = 2 To wsResources.Cells(Rows.Count, 1).End(xlUp).Row           
                ' Get resource info
                resName = wsResources.Cells(j, 1).Value
                resCapacity = wsResources.Cells(j, 2).Value
                resAvailable = wsResources.Cells(j, 3).Value           
                ' Check if resource is available
                If resAvailable > 0 Then
                    ' Calculate the possible allocation for this resource
                    allocation = WorksheetFunction.Min(remainingHours, resAvailable)
                    allocation = WorksheetFunction.Min(allocation, resCapacity * resAvailable)               
                    ' Update allocation in task sheet
                    wsTasks.Cells(i, 3).Value = wsTasks.Cells(i, 3).Value & resName & " (" & allocation & " hours) ; "
                    remainingHours = remainingHours - allocation
                    wsResources.Cells(j, 3).Value = resAvailable - allocation               
                    ' If task hours are fully allocated, move to the next task
                    If remainingHours <= 0 Then Exit For
                End If
            Next j
        Next i
        MsgBox "Resource allocation completed!", vbInformation
    End Sub

    Code Explanation

    1. Variable Definitions:
      • wsResources and wsTasks represent the worksheets for resources and tasks, respectively.
      • The other variables are used to keep track of resource and task information during the allocation process.
    2. Main Loop for Tasks:
      • The outer loop goes through each task in the « Tasks » sheet, retrieves the required hours, and tracks the remaining hours needed for allocation.
    3. Resource Allocation:
      • The inner loop iterates over each resource in the « Resources » sheet. For each resource, it checks if it is available (has remaining hours).
      • The allocation is calculated by considering the remaining required hours for the task and the available capacity of the resource.
      • The allocated resource and the hours assigned are updated in the « Tasks » sheet, and the available hours for that resource are updated.
    4. Updating the Sheets:
      • The allocated resources are displayed in the « Assigned Resource » column of the « Tasks » sheet.
      • The available hours for each resource are updated in the « Available Hours » column of the « Resources » sheet.
    5. End of Process:
      • After the process completes, a message box pops up indicating that the resource allocation is finished.

    Conclusion

    This VBA macro automates the process of allocating resources to tasks based on the resource capacities and the task requirements. You can modify the code to accommodate different scenarios, such as adding task priorities, resource types, or additional constraints for more complex allocations.

     

  • Automating Monte Carlo simulation reports in Excel with VBA

    Automating Monte Carlo simulation reports in Excel with VBA allows you to quickly generate multiple simulation results and produce analytical reports based on those results. Below is a detailed guide on how to create a Monte Carlo simulation for a project or investment, generate random results, and create a report using VBA in Excel.

    Steps in a Monte Carlo Simulation

    1. Define input variables (model parameters):
      • For example, if you are simulating a project, you might have variables such as initial cost, expected revenue, operational costs, growth rates, etc.
    2. Generate random numbers for the inputs:
      • Use appropriate statistical distributions to generate random values (e.g., normal distribution for returns).
    3. Run the simulation over many iterations:
      • For example, running 10,000 iterations to obtain a distribution of results.
    4. Analyze the results:
      • Calculate metrics such as the mean, median, percentiles, etc.
    5. Automate report generation:
      • Create a report in a new Excel sheet with charts, tables, and analytical metrics.

    VBA Code to Automate Monte Carlo Simulation

    Below is a detailed example of VBA code for a Monte Carlo simulation:

    1. Setup Inputs

    This code assumes a simple model with three variables:

    • Initial Cost (which follows a normal distribution),
    • Annual Revenue (which follows a uniform distribution),
    • Project Lifetime (in years).
    1. VBA Code for Simulation
    Sub MonteCarloSimulation()
        ' Define simulation paraeters
        Dim numIterations As Long
        numIterations = 10000 ' Number of iterations   
        Dim i As Lo
        Dim initialCost As Double
        Dim annualRevenue As Double
        Dim projectLifetime As Long
        Dim cashFlow As Double
        Dim finalResult As Double
        Dim totalResult As Double   
        ' Create an array to store results
        Dim results() As Double
        ReDim results(1 To numIterations)   
        ' Setup result sheet
        Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Monte Carlo Report"
        With Sheets("Monte Carlo Report")
            .Cells(1, 1).Value = "Iteration"
            .Cells(1, 2).Value = "Cash Flow"
        End With   
        ' Run Monte Carlo simulation
        For i = 1 To numIterations
            ' Generate random variables for each iteration
            initialCost = Application.WorksheetFunction.NormInv(Rnd(), 100000, 20000) ' Initial cost with normal distribution
            annualRevenue = Application.WorksheetFunction.RandBetween(5000, 20000) ' Annual revenue with uniform distribution
            projectLifetime = Application.WorksheetFunction.RandBetween(5, 15) ' Project lifetime between 5 and 15 years       
            ' Calculate cash flow (revenue - costs over the lifetime)
            cashFlow = annualRevenue * projectLifetime - initialCost       
            ' Store the result in the array
            results(i) = cashFlow       
            ' Record the results in the Excel sheet
            Sheets("Monte Carlo Report").Cells(i + 1, 1).Value = i
            Sheets("Monte Carlo Report").Cells(i + 1, 2).Value = cashFlow       
            ' Add to total result for calculating average later
            totalResult = totalResult + cashFlow
        Next i
        ' Calculate statistics for the results
        Dim mean As Double
        Dim stdDev As Double
        Dim minResult As Double
        Dim maxResult As Double   
        mean = totalResult / numIterations
        stdDev = Application.WorksheetFunction.StDev(results)
        minResult = Application.WorksheetFunction.Min(results)
        maxResult = Application.WorksheetFunction.Max(results)   
        ' Add simulation statistics to the report
        With Sheets("Monte Carlo Report")
            .Cells(numIterations + 3, 1).Value = "Mean"
            .Cells(numIterations + 3, 2).Value = mean
            .Cells(numIterations + 4, 1).Value = "Standard Deviation"
            .Cells(numIterations + 4, 2).Value = stdDev
            .Cells(numIterations + 5, 1).Value = "Min"
            .Cells(numIterations + 5, 2).Value = minResult
            .Cells(numIterations + 6, 1).Value = "Max"
            .Cells(numIterations + 6, 2).Value = maxResult
        End With   
        ' Create a chart to visualize the distribution of results
        Dim chartObj As ChartObject
        Set chartObj = Sheets("Monte Carlo Report").ChartObjects.Add(Left:=200, Width:=400, Top:=50, Height:=300)
        chartObj.Chart.ChartType = xlColumnClustered
        chartObj.Chart.SetSourceData Source:=Sheets("Monte Carlo Report").Range("B2:B" & numIterations + 1)
        chartObj.Chart.HasTitle = True
        chartObj.Chart.ChartTitle.Text = "Monte Carlo Simulation Results Distribution"  
        MsgBox "Monte Carlo Simulation Complete!", vbInformation
    End Sub

    Explanation of the Code

    1. Defining Parameters:
      • numIterations: Number of iterations for the simulation (default is 10,000).
      • initialCost: The initial cost generated using a normal distribution.
      • annualRevenue: The annual revenue generated using a uniform distribution.
      • projectLifetime: The project lifetime generated between 5 and 15 years with a uniform distribution.
    2. Simulation Loop:
      • The loop For i = 1 To numIterations generates random variables for each iteration, performs the cash flow calculation, and stores the results in an array.
    3. Calculating Statistics:
      • After all iterations are completed, the code calculates the mean, standard deviation, minimum, and maximum of the results.
    4. Report Generation:
      • The results of each iteration are recorded in a new sheet called « Monte Carlo Report ».
      • Statistical metrics are calculated and added to the sheet below the results.
    5. Chart Creation:
      • A bar chart is created to visualize the distribution of results.

    Expected Output in Excel

    • A new sheet named « Monte Carlo Report » is created, showing the simulation results.
    • Each iteration’s cash flow is listed.
    • At the bottom of the sheet, statistics such as the mean, standard deviation, minimum, and maximum are displayed.
    • A chart showing the distribution of results is added to the sheet.

    Customization

    • Variable Distributions: You can adjust the distribution types for each parameter as needed (e.g., using triangular, log-normal distributions, etc.).
    • Model: You can replace the simple cash flow model with more complex calculations depending on your project.
    • Report: The report format can be customized further (e.g., adding colors, annotations, or additional metrics).