Advanced Excel Tricks and Tips
Simple macro code for collate data
Advanced Macro for data collate
Code here
Sub ConsolidateDataFromDifferentBooksInAFolder()
Dim ReportBook As Workbook, DataBook As Workbook
Dim ReportSheet As Worksheet, DataSheet As Worksheet
Dim ReferPath As String, ReferFileName As String
Dim Lr As Long, Lc As Long, RLr As Long
Dim i As Long
Dim FileType As String
Application.ScreenUpdating = False
Application.CutCopyMode = False
ReferPath = ThisWorkbook.Path & "\EX20.00 - Data\" ' Path to the folder with data files
Set ReportBook = ThisWorkbook
Set ReportSheet = ReportBook.Worksheets("Sheet1")
' Get the first file in the folder
ReferFileName = Dir(ReferPath & "*.*")
' Initialize the row counter for the report sheet
RLr = ReportSheet.Cells(ReportSheet.Rows.Count, "B").End(xlUp).Row
Do Until ReferFileName = ""
' Get the file extension
FileType = LCase(Right(ReferFileName, Len(ReferFileName) - InStrRev(ReferFileName, ".")))
' Open Excel files (.xls, .xlsx, etc.)
If FileType Like "xls*" Then
Set DataBook = Workbooks.Open(ReferPath & ReferFileName)
Set DataSheet = DataBook.Worksheets(1) ' Assuming data is in the first sheet
' Get the last row and column of the data sheet
Lr = DataSheet.Cells(DataSheet.Rows.Count, "A").End(xlUp).Row
Lc = DataSheet.Cells(1, DataSheet.Columns.Count).End(xlToLeft).Column
If Lr > 1 Then ' If there's data to copy
i = i + 1
' Copy and paste the data into the report sheet
If i = 1 Then
' Copy the entire range including headers
DataSheet.Range("A1").Resize(Lr, Lc).Copy
ReportSheet.Cells(RLr + 1, "B").PasteSpecial Paste:=xlPasteValues
Else
' Skip the header for subsequent files
DataSheet.Range("A2").Resize(Lr - 1, Lc).Copy
ReportSheet.Cells(RLr + 1, "B").PasteSpecial Paste:=xlPasteValues
End If
' Insert the file name in column A
ReportSheet.Cells(RLr + 1, "A").Resize(Lr).Value = ReferFileName
' Update the row counter
RLr = ReportSheet.Cells(ReportSheet.Rows.Count, "B").End(xlUp).Row
' Clear clipboard to avoid extra memory usage
Application.CutCopyMode = False
End If
' Close the data workbook without saving
DataBook.Close False
' Handle CSV files (.csv)
ElseIf FileType = "csv" Then
' Import CSV data into the Report Sheet directly
With ReportSheet.QueryTables.Add(Connection:="TEXT;" & ReferPath & ReferFileName, Destination:=ReportSheet.Cells(RLr + 1, "B"))
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1) ' Assuming 3 columns of data (adjust based on actual data)
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileParseType = xlDelimited
.Refresh BackgroundQuery:=False
End With
' Update the row counter after importing CSV
RLr = ReportSheet.Cells(ReportSheet.Rows.Count, "B").End(xlUp).Row
' Insert the file name in column A for the imported rows
ReportSheet.Cells(RLr - Lr + 1, "A").Resize(Lr).Value = ReferFileName
' Handle TXT files (.txt)
ElseIf FileType = "txt" Then
' Open the .txt file for reading line-by-line
Dim FileNum As Integer
Dim LineContent As String
FileNum = FreeFile
Open ReferPath & ReferFileName For Input As FileNum
' Read each line and copy it to the report sheet
While Not EOF(FileNum)
Line Input #FileNum, LineContent
' Split the line into columns assuming tab-delimited or comma-delimited
DataArray = Split(LineContent, vbTab) ' Change delimiter if needed (use "," for CSV, vbTab for tab, etc.)
' Add each line to the report sheet
For i = 0 To UBound(DataArray)
ReportSheet.Cells(RLr + 1, "B").Offset(0, i).Value = DataArray(i)
Next i
' Insert the file name in column A
ReportSheet.Cells(RLr + 1, "A").Value = ReferFileName
RLr = RLr + 1 ' Increment the row counter
Wend
Close FileNum
End If
' Get the next file
ReferFileName = Dir
Loop
' Optional: Clear any existing content in column A (except header)
ReportSheet.Range("A:A").Replace ".*", ""
' Set the header for the file name column
ReportSheet.Range("A1").Value = "File Name"
' Save the report workbook
ReportBook.Save
Application.ScreenUpdating = True
MsgBox "Data Consolidated Successfully", vbInformation
End Sub
Specific Buttonwise Collation
Merge multiple sheets into one
Select multiple column in VBA mode (Macro)
31 Important Excel Functions
FREQUENCY |
INDEX & MATCH |
LOOKUP |
VLOOKUP |
HLOOKUP |
SUMIF |
SUMIFS |
COUNTIF |
COUNTIFS |
COUNTA & COUNTBLANK |
AVERAGEIF & AVERAGE IFS |
SUBTOTAL |
SUMPRODUCT |
IF FORMULA |
NESTED IF |
LEFT, MID, RIGHT & FIND |
REPEAT |
SUBSTITUTE |
PMT,IPMT, PPMT, PV, FV |
|
31 important excel formulas with their practical example.
Excel Combo (Tips & Tricks)
=TRIM(CLEAN(PROPER(E2)))
=IF(P2>80,"Execlent",IF(P2>=80,"Good",IF(P2<80,"Poor")))
=IF(P15>0,MAX(O14:O14)+1,"")
=IF(AND(C5>=18,D5>=18,E5>=18,F5>=18,G5>=18),"Pass","Fail")
=IF(M6>0,L5+1,"")
=IF(H5<=24,"Poor",IF(H5<=54,"Need
Improvement",IF(H5<=74,"Good",IF(H5<=100,"Excellent"))))
=IF(H5<=24,"D",IF(H5<=54,"C",IF(H5<=74,"B",IF(H5<=100,"A"))))
=COUNTIF(C5:G5,">=30")
=IF(COUNTIF(D5:H5,">=30")=5,"Pass","Fail")
=IFERROR(K14,"Invalid
number")
=FIND("@",J2,1)
=RIGHT(J2,LEN(J2)-K2)
=LEFT(J2,L2-1)
=TEXT(WEEKDAY(B2,1),"DDDD")
Example in N2
There is a bee in a house above the wall
Total "e" count
=LEN(N2) - LEN(SUBSTITUTE(N2, "e", ""))
Total words in a sentence
=LEN(TRIM(N2)) - LEN(SUBSTITUTE(TRIM(N2), " ", "")) + 1
Prevent Duplicate Entry in Cells
***********************************************************************************
Vlookup on Duplicate values
Unique IDs using COUNTIF
Let’s say we want to lookup the second score for Student ID = 2021-A in this dataset:
First, we will create unique IDs in column B by joining the original student ID (column C) with a COUNTIF Function:
=C3&"-"&COUNTIF($C$3:C3,C3)
The COUNTIF Function counts the number of each Student ID. By locking one cell reference in the COUNTIF Function, but not the other, we identify each instance of a duplicate Student ID with a unique number:
=COUNTIF($C$3:C3,C3)
Then we simply use the & operate to concatenate everything together as in the previous formula.
Vlookup Cheat Sheet
Randomization
Random Number 100 - 500 : =RANDBETWEEN(100,500)
Random Number Decimal 1 - 50 : =RANDBETWEEN(1*10,50*10)/10
Random Dates 1-Jul-2021 to 31-Jul-2021 : =RANDBETWEEN(DATEVALUE("1-July-2021"),DATEVALUE("31-July-2021"))
Random time between 9:00 AM to 6:30 PM : =TIME(9,0,0)+RAND()*TIME(18,30,0)-TIME(9,0,0) Random Alphabet between A to Z : =CHAR(RANDBETWEEN(CODE("A"),CODE("Z")))
Random text string/ password : =RANDBETWEEN(0,9)&CHAR(RANDBETWEEN(65,90))&CHAR(RANDBETWEEN(97,122))&CHAR(RANDBETWEEN(33,47))
Random Names : =CHOOSE(RANDBETWEEN(1,9),$A$26,$A$27,$A$28,$A$29,$A$30,$A$31,$A$32,$A$33,$A$34)
VBA for Macro(Professional)
Brouws File
Private Sub CommandButton1_Click() Dim files Dim FildialogueOpen As Office.FileDialog Set FildialogueOpen = Application.FileDialog(msoFileDialogOpen) FildialogueOpen.Show files = FildialogueOpen.SelectedItems(1) If files = "" Then MsgBox "File not selected!" Exit Sub Else Workbooks.Open (files) End If End Sub
Code for Userform
Just copy this code and paste in your
Dashboard user form, You can design and follow the step as per the video.
Dim LblEvent(11) As New Class1
Private Sub UserForm_Initialize()
Application.Visible = False
Dim Pivt As PivotTable
Dim Slicer As SlicerCache
'Refresh Pivot Table
For Each Pivt In Sheet2.PivotTables
Pivt.PivotCache.Refresh
Next
'Reset Slicer
For Each Slicer In ActiveWorkbook.SlicerCaches
Slicer.ClearManualFilter
Next
For ChNo = 1 To 3
FilePath =
Environ$("Temp") & "\Chart" & ChNo &
".jpg"
Sheet2.Activate
Sheet2.Shapes("Chart" & ChNo).Select
ActiveChart.Export FilePath
Me("Img" &
ChNo).Picture = LoadPicture(FilePath)
Kill FilePath
Next ChNo
Me.TotSale = Format(Sheet2.Range("B1"), "STandard")
'Add Event
For AddEvent = 0 To 11
Set LblEvent(AddEvent).LblBtn
= Me("Label" & AddEvent + 1)
Next AddEvent
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
Application.Visible = True
End Sub
Insert a Class Module and paste the
following code
Public WithEvents LblBtn As MSForms.Label
Private Sub LblBtn_Click()
Dim Slicer As SlicerCache
BtnNo = Replace(LblBtn.Name, "Label", "")
If UserForm1.Controls("Image" & BtnNo).Visible = True Then
UserForm1.Controls("ImageSec" & BtnNo).Visible = True
UserForm1.Controls("Image" & BtnNo).Visible = False
Else
UserForm1.Controls("ImageSec" & BtnNo).Visible = False
UserForm1.Controls("Image" & BtnNo).Visible = True
End If
For Each Slicer In ActiveWorkbook.SlicerCaches
If
UserForm1.Controls("ImageSec" & BtnNo).Visible = True Then
Slicer.SlicerItems(Left(LblBtn.Caption, 3)).Selected = False
Else
Slicer.SlicerItems(Left(LblBtn.Caption, 3)).Selected = True
End If
Next
UserForm1.TotSale = Format(Sheet2.Range("B1"),
"STandard")
For ChNo = 1 To 3
FilePath =
Environ$("Temp") & "\Chart" & ChNo &
".jpg"
Sheet2.Activate
Sheet2.Shapes("Chart" & ChNo).Select
ActiveChart.Export FilePath
UserForm1.Controls("Img" & ChNo).Picture =
LoadPicture(FilePath)
Kill FilePath
Next ChNo
End Sub
***********************************************************************************
Private Sub Workbook_Open()
UserForm1.WindowState = xlMaximized
UserForm1.Show
End Sub
Private Sub UserForm_Initialize()
Dim Pivt As PivotTable
'Refresh Pivot Table
For Each Pivt In Sheet2.PivotTables
Pivt.PivotCache.Refresh
Next
For ChNo = 1 To 2
FilePath = VBA.Environ$("Temp") & "\Chart" & ChNo & ".jpg"
Sheet2.Activate
Sheet2.Shapes("Chart" & ChNo).Select
ActiveChart.Export FilePath
Me("Img" & ChNo).Picture = LoadPicture(FilePath)
Kill FilePath
Next ChNo
End Sub
Private Sub ComboBox1_Change()
' Determine the selected chart from ComboBox1 or ComboBox2
If ComboBox1.Text = "Option 1" Then
For ChNo = 1 To 2
FilePath = VBA.Environ$("Temp") & "\Chart" & ChNo & ".jpg"
Sheet2.Activate
Sheet2.Shapes("Chart" & ChNo).Select
ActiveChart.Export FilePath
Me("Img" & ChNo).Picture = LoadPicture(FilePath)
Kill FilePath
Next ChNo
ElseIf ComboBox1.Text = "Option 2" Then
For ChNo = 1 To 2
FilePath = VBA.Environ$("Temp") & "\Chart" & ChNo + 1 & ".jpg"
Sheet2.Activate
Sheet2.Shapes("Chart" & ChNo + 1).Select
ActiveChart.Export FilePath
Me("Img" & ChNo + 1).Picture = LoadPicture(FilePath)
Kill FilePath
Next ChNo
Else
Exit Sub ' No chart selected
End If
End Sub
Private Sub UserForm_Initialize()
' Populate ComboBox with options
ComboBox1.List = Array("Option 1", "Option 2")
'ComboBox2.List = Array("Option 3", "Option 4")
Dim Pivt As PivotTable
'Refresh Pivot Table
For Each Pivt In Sheet2.PivotTables
Pivt.PivotCache.Refresh
Next
End Sub
Sub NavigateAndClickLinks()
Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
' Open IE and make it visible
IE.Visible = True
' Navigate to the first page
IE.Navigate "https://zee-yan.blogspot.com/"
' Wait until the first page is fully loaded
Do While IE.Busy Or IE.ReadyState <> 4
DoEvents
Loop
' Now, navigate to the Tips n Tricks page
IE.Navigate "https://zee-yan.blogspot.com/p/tips-n-tricks.html"
' Wait until the page is fully loaded
Do While IE.Busy Or IE.ReadyState <> 4
DoEvents
Loop
' Now, find and click the link with text "Download file" (Google Drive link)
Dim link As Object
Set link = Nothing
' Search for the link with the text "Download file"
For Each link In IE.document.getElementsByTagName("a")
If link.innerText = "Download file" Then
link.Click
Exit For
End If
Next link
' Wait for Google Drive link to open
Do While IE.Busy Or IE.ReadyState <> 4
DoEvents
Loop
' Notify user that the process is complete
MsgBox "Download page opened!"
' Clean up
Set IE = Nothing
End Sub
No comments:
Post a Comment