I have one excel sheet column followed by SLNo, acno, name,date, monthly investment,total months, remaining months, total invested,status, and month 1 to month 72. I want generate a report button for monthly by selecting months if click generate report it should make seperate sheet and give report excluding column of monthly investment,total months, remaining months, status and months should be current month only.
Assistant
To create a "Generate Report" button in Excel that generates a separate report sheet based on the current month selection, you can use VBA (Visual Basic for Applications). Below are detailed steps to achieve this functionality:
1. Organize Your Data Properly
Ensure your Excel sheet (let's call it DataSheet) has the following columns in order:
SLNo
AcNo
Name
Date
Monthly Investment
Total Months
Remaining Months
Total Invested
Status
Month 1 to Month 72
2. Enable the Developer Tab
If the Developer tab is not visible in your Excel ribbon:
Excel 2010 and Later:
Go to File > Options.
Select Customize Ribbon.
In the right pane, check the Developer box.
Click OK.
3. Insert a Button
Go to the Developer tab.
Click on Insert in the Controls group.
Choose the Button (Form Control) and draw it on your sheet.
After drawing, the Assign Macro dialog box will appear. Click New to create a new macro.
4. Write the VBA Macro
The following VBA code accomplishes the task:
vba
Sub GenerateMonthlyReport()
Dim wsData As Worksheet
Dim wsReport As Worksheet
Dim lastRow As Long
Dim lastCol As Long
Dim monthNumber As Integer
Dim monthCol As Long
Dim reportName As String
Dim headerCols As Variant
Dim i As Integer
Dim copyRange As Range
Dim currentDate As Date
Dim investmentMonth As Date
' Set your data worksheet here
Set wsData = ThisWorkbook.Sheets("DataSheet") ' Change "DataSheet" to your actual data sheet name
' Determine the current month relative to the investment start date
currentDate = Date
' Assuming 'Date' column (4) is the investment start date
' and 'Total Months' column (6) specifies duration
' You might need to adjust the logic based on your exact requirement
' Prompt user to enter the current month number for the report
monthNumber = InputBox("Enter the current month number for the report (1 to 72):", "Select Month", 1)
If monthNumber < 1 Or monthNumber > 72 Then
MsgBox "Please enter a valid month number between 1 and 72.", vbExclamation
Exit Sub
End If
' Check if the report sheet already exists
reportName = "Report_Month_" & monthNumber
On Error Resume Next
Set wsReport = ThisWorkbook.Sheets(reportName)
On Error GoTo 0
If Not wsReport Is Nothing Then
MsgBox "Report for Month " & monthNumber & " already exists.", vbInformation
Exit Sub
End If
' Add a new sheet for the report
Set wsReport = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
wsReport.Name = reportName
' Define the headers to include in the report
headerCols = Array("SLNo", "acno", "name", "date", "total invested")
' Find the column numbers for the headers
Dim colNumbers() As Long
ReDim colNumbers(0 To UBound(headerCols))
For i = 0 To UBound(headerCols)
colNumbers(i) = Application.Match(headerCols(i), wsData.Rows(1), 0)
If IsError(colNumbers(i)) Then
MsgBox "Header '" & headerCols(i) & "' not found in data sheet.", vbCritical
Exit Sub
End If
Next i
' Add the selected month column
colNumbers = ResizeArray(colNumbers, UBound(colNumbers) + 2)
colNumbers(UBound(colNumbers) - 1) = 9 + monthNumber ' Assuming Month 1 starts at column 10 (J)
' Copy headers to report sheet
For i = 0 To UBound(headerCols)
wsReport.Cells(1, i + 1).Value = headerCols(i)
Next i
wsReport.Cells(1, UBound(headerCols) + 1).Value = "Month " & monthNumber
' Determine the last row with data
lastRow = wsData.Cells(wsData.Rows.Count, "A").End(xlUp).Row
' Determine the month column
monthCol = 9 + monthNumber ' Adjust if your Month 1 is in a different column
' Copy data row by row
Dim reportRow As Long
reportRow = 2
For i = 2 To lastRow
' Example condition: You can add specific conditions if needed
' For instance, only include active status
' If wsData.Cells(i, "I").Value = "Active" Then
wsReport.Cells(reportRow, 1).Value = wsData.Cells(i, "A").Value ' SLNo
wsReport.Cells(reportRow, 2).Value = wsData.Cells(i, "B").Value ' AcNo
wsReport.Cells(reportRow, 3).Value = wsData.Cells(i, "C").Value ' Name
wsReport.Cells(reportRow, 4).Value = wsData.Cells(i, "D").Value ' Date
wsReport.Cells(reportRow, 5).Value = wsData.Cells(i, "H").Value ' Total Invested
wsReport.Cells(reportRow, 6).Value = wsData.Cells(i, monthCol).Value ' Selected Month
reportRow = reportRow + 1
' End If
Next i
' Auto-fit columns for better readability
wsReport.Columns.AutoFit
MsgBox "Report for Month " & monthNumber & " has been generated successfully.", vbInformation
End Sub
' Helper function to resize array
Function ResizeArray(arr As Variant, size As Long) As Variant
Dim i As Long
ReDim Preserve arr(0 To size - 1)
ResizeArray = arr
End Function
5. Understanding the VBA Code
Prompt for Month Number: The macro prompts the user to enter the desired month number (1 to 72).
Validate Input: It checks if the entered month number is within the valid range.
Check for Existing Report: If a report for the selected month already exists, it notifies the user and exits.
Create a New Sheet: If not, it creates a new sheet named Report_Month_X where X is the month number.
Select Columns: It copies only the necessary columns:
SLNo
acno
name
date
total invested
The selected month column (e.g., Month 1)
Copy Data: It iterates through each row of the data sheet, copying relevant data to the new report sheet.
Auto-Fit Columns: Adjusts column widths for better readability.
Completion Message: Notifies the user upon successful report generation.
6. Assign the Macro to the Button
After pasting the VBA code, close the VBA editor.
Right-click the button you inserted earlier and select Assign Macro.
Choose GenerateMonthlyReport from the list and click OK.
7. Test the Button
Click the Generate Report button.
Enter a valid month number (1-72) when prompted.
The macro will generate a new sheet with the selected month's report.
8. Customize as Needed
Adjust Column References: Ensure that the column indices in the VBA code match your actual data layout. The code assumes:
SLNo is in column A (1)
acno is in column B (2)
name is in column C (3)
date is in column D (4)
total invested is in column H (8)
Month 1 starts at column J (10). Adjust monthCol = 9 + monthNumber if your months start in a different column.
Add Filters: If you want to include only certain rows based on criteria (e.g., Status is "Active"), uncomment and modify the condition in the loop:
vba
If wsData.Cells(i, "I").Value = "Active" Then
' Copy data
End If
Dynamic Month Columns: If your month columns aren't sequential or start from a different column, adjust the logic to find the correct month column.
9. Save Your Workbook as Macro-Enabled
Ensure you save your workbook with macros enabled:
Click File > Save As.
Choose Excel Macro-Enabled Workbook (*.xlsm) from the dropdown.
Save your file.
10. Security Settings
If your Excel security settings prevent macros from running:
Go to File > Options.
Select Trust Center > Trust Center Settings.
Click on Macro Settings.
Choose Enable all macros or Disable all macros with notification based on your preference.
Click OK to apply changes.
Note: Enabling macros can pose security risks if you're not sure about the source of the code. Always ensure your macros are from trusted sources.
By following these steps, you can efficiently generate monthly reports in separate sheets, tailored to your specific data structure and requirements.