VBA Code

BUET Word Automation: VBA Macros Collection
১. Text to Box Converter (Serial 1-100+_)
Macro 1: MergeBUET_KeywordSeparationEngine.vba
 Sub MergeBUET_KeywordSeparationEngine_Updated()
    Dim docBV As Document, docEV As Document, docOut As Document
    Dim fd As FileDialog
    Dim pathBV As String, pathEV As String
    Dim tbl As Table
    Dim i As Long, totalQ As Long
    Dim strQNum As String, strSub As String, currentAns As String
    Dim rngInsert As Range
    Dim rowIdx As Long, numRows As Long, solRow As Long, ansRow As Long
    Dim hasOptE As Boolean
    
    ' Dynamic Array Storage
    Dim bvQ_Start() As Long, bvQ_End() As Long
    Dim bvSol_Start() As Long, bvSol_End() As Long
    Dim evQ_Start() As Long, evQ_End() As Long
    Dim evSol_Start() As Long, evSol_End() As Long
    Dim officialAnswers() As String
    Dim subjectMap() As String
    
    ' 1. Select Input BV File
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.Title = "Select Input BV File"
    fd.Filters.Clear
    fd.Filters.Add "Word Documents", "*.docx; *.doc"
    If fd.Show = -1 Then pathBV = fd.SelectedItems(1) Else Exit Sub
    
    ' 2. Select Input EV File
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.Title = "Select Input EV File"
    fd.Filters.Clear
    fd.Filters.Add "Word Documents", "*.docx; *.doc"
    If fd.Show = -1 Then pathEV = fd.SelectedItems(1) Else Exit Sub
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = wdAlertsNone
    
    Set docBV = Documents.Open(FileName:=pathBV, ReadOnly:=True, Visible:=False)
    Set docEV = Documents.Open(FileName:=pathEV, ReadOnly:=True, Visible:=False)
    Set docOut = Documents.Add
    
    ' Page Setup
    With docOut.PageSetup
        .Orientation = wdOrientPortrait
        .TopMargin = InchesToPoints(0.35)
        .BottomMargin = InchesToPoints(0.35)
        .LeftMargin = InchesToPoints(0.35)
        .RightMargin = InchesToPoints(0.35)
        .TextColumns.SetCount 1
    End With
    
    ' Detect Total Questions Dynamically
    totalQ = DetectTotalQuestions(docBV, docEV)
    If totalQ = 0 Then totalQ = 100 ' Fallback Default
    
    ' Allocate Dynamic Arrays
    ReDim bvQ_Start(1 To totalQ), bvQ_End(1 To totalQ)
    ReDim bvSol_Start(1 To totalQ), bvSol_End(1 To totalQ)
    ReDim evQ_Start(1 To totalQ), evQ_End(1 To totalQ)
    ReDim evSol_Start(1 To totalQ), evSol_End(1 To totalQ)
    ReDim officialAnswers(1 To totalQ)
    ReDim subjectMap(1 To totalQ)
    
    ' Subject Range Input Box Prompt
    Application.ScreenUpdating = True
    If Not PromptUserForSubjectRanges(totalQ, subjectMap) Then
        docBV.Close SaveChanges:=False
        docEV.Close SaveChanges:=False
        docOut.Close SaveChanges:=False
        Application.DisplayAlerts = wdAlertsAll
        Exit Sub
    End If
    Application.ScreenUpdating = False
    
    ' 1. Parse Answer Key Table (Supports a, b, c, d, e)
    ParseOfficialAnswerKey docBV, officialAnswers, totalQ
    
    ' 2. Index Questions & Solutions
    IndexByKeywordSeparation docBV, totalQ, bvQ_Start, bvQ_End, bvSol_Start, bvSol_End
    IndexByKeywordSeparation docEV, totalQ, evQ_Start, evQ_End, evSol_Start, evSol_End
    
    For i = 1 To totalQ
        strQNum = Format(i, "00")
        
        ' Dynamic Subject Allocation from Prompt
        strSub = subjectMap(i)
        If strSub = "" Then strSub = "General"
        
        ' Answer Key (Left blank if not found)
        currentAns = officialAnswers(i)
        
        ' Check if this question contains Option (e)
        hasOptE = CheckIfHasOptionE(docBV, bvQ_Start(i), bvQ_End(i)) Or _
                  CheckIfHasOptionE(docEV, evQ_Start(i), evQ_End(i))
        
        ' Dynamic Row Count
        If hasOptE Then
            numRows = 9
            solRow = 8
            ansRow = 9
        Else
            numRows = 8
            solRow = 7
            ansRow = 8
        End If
        
        ' Target position in output document
        Set rngInsert = docOut.Range
        rngInsert.Collapse wdCollapseEnd
        
        ' Create Table
        Set tbl = docOut.Tables.Add(Range:=rngInsert, numRows:=numRows, NumColumns:=2)
        
        With tbl
            .Borders.Enable = True
            .Rows.Alignment = wdAlignRowCenter
            
            ' Set cell widths
            For rowIdx = 1 To numRows
                .Cell(rowIdx, 1).Width = InchesToPoints(3.75)
                .Cell(rowIdx, 2).Width = InchesToPoints(3.75)
            Next rowIdx
            
            ' === ROW 1: Header ===
            WriteCleanText .Cell(1, 1), strQNum, True
            WriteCleanText .Cell(1, 2), strSub, True
            
            ' === Question & Options (BV Column) ===
            If bvQ_Start(i) > 0 And bvQ_End(i) >= bvQ_Start(i) Then
                PopulateIndexedQAndOpts tbl, docBV, bvQ_Start(i), bvQ_End(i), 1, hasOptE
            End If
            
            ' === Question & Options (EV Column) ===
            If evQ_Start(i) > 0 And evQ_End(i) >= evQ_Start(i) Then
                PopulateIndexedQAndOpts tbl, docEV, evQ_Start(i), evQ_End(i), 2, hasOptE
            End If
            
            ' === Solution Row ===
            If bvSol_Start(i) > 0 And bvSol_End(i) >= bvSol_Start(i) Then
                PasteParagraphRange .Cell(solRow, 1), docBV, bvSol_Start(i), bvSol_End(i)
            End If
            If evSol_Start(i) > 0 And evSol_End(i) >= evSol_Start(i) Then
                PasteParagraphRange .Cell(solRow, 2), docEV, evSol_Start(i), evSol_End(i)
            End If
            
            ' === Answer Key Row ===
            WriteCleanText .Cell(ansRow, 1), currentAns, False
            WriteCleanText .Cell(ansRow, 2), "1", False
        End With
        
        ' Spacing between question blocks
        Set rngInsert = docOut.Range
        rngInsert.Collapse wdCollapseEnd
        rngInsert.InsertParagraphAfter
    Next i
    
    docBV.Close SaveChanges:=False
    docEV.Close SaveChanges:=False
    
    Application.ScreenUpdating = True
    Application.DisplayAlerts = wdAlertsAll
    
    MsgBox "Total " & totalQ & " questions merged successfully!", vbInformation, "Completed"
End Sub

' ==============================================================
' Subject Range Input & Parsing Functions
' ==============================================================
Function PromptUserForSubjectRanges(totalQ As Long, ByRef subMap() As String) As Boolean
    Dim defaultVal As String
    Dim userVal As String
    Dim q1 As Long, q2 As Long
    
    q1 = totalQ \ 3
    q2 = q1 * 2
    defaultVal = "Phy:1-" & q1 & ", Chem:" & (q1 + 1) & "-" & q2 & ", HMath:" & (q2 + 1) & "-" & totalQ
    
    userVal = InputBox("Total questions detected: " & totalQ & vbCrLf & vbCrLf & _
                       "Enter question ranges for each subject:" & vbCrLf & _
                       "(Format: Subject:Start-End, Subject:Start-End, ...)" & vbCrLf & vbCrLf & _
                       "Modify as needed:", _
                       "Subject Range Setup", defaultVal)
                       
    If Trim(userVal) = "" Then
        PromptUserForSubjectRanges = False
        Exit Function
    End If
    
    ParseSubjectInput userVal, totalQ, subMap
    PromptUserForSubjectRanges = True
End Function

Sub ParseSubjectInput(ByVal inputStr As String, totalQ As Long, ByRef subMap() As String)
    Dim parts() As String, subPart() As String, rangePart() As String
    Dim i As Long, j As Long, sQ As Long, eQ As Long
    Dim sName As String, item As String
    
    inputStr = ConvertBengaliDigitsToEnglish(inputStr)
    parts = Split(inputStr, ",")
    
    For i = LBound(parts) To UBound(parts)
        item = Trim(parts(i))
        If InStr(item, ":") > 0 Then
            subPart = Split(item, ":")
            sName = Trim(subPart(0))
            
            If InStr(subPart(1), "-") > 0 Then
                rangePart = Split(Trim(subPart(1)), "-")
                sQ = CLng(Val(Trim(rangePart(0))))
                eQ = CLng(Val(Trim(rangePart(1))))
                
                If sQ >= 1 And eQ <= totalQ And sQ <= eQ Then
                    For j = sQ To eQ
                        subMap(j) = sName
                    Next j
                End If
            End If
        End If
    Next i
    
    For i = 1 To totalQ
        If subMap(i) = "" Then subMap(i) = "General"
    Next i
End Sub

' ==============================================================
' Helper Functions
' ==============================================================
Function MinVal(v1 As Long, v2 As Long) As Long
    If v1 < v2 Then MinVal = v1 Else MinVal = v2
End Function

Function ConvertBengaliDigitsToEnglish(ByVal txt As String) As String
    Dim res As String, i As Long, ch As String, code As Long
    res = ""
    For i = 1 To Len(txt)
        ch = Mid(txt, i, 1)
        code = AscW(ch)
        If code >= 2534 And code <= 2543 Then
            res = res & CStr(code - 2534)
        Else
            res = res & ch
        End If
    Next i
    ConvertBengaliDigitsToEnglish = res
End Function

Function GetBengaliSolWord() As String
    GetBengaliSolWord = ChrW(2488) & ChrW(2478) & ChrW(2494) & ChrW(2471) & ChrW(2494) & ChrW(2472)
End Function

Function GetBengaliSolPrefix() As String
    GetBengaliSolPrefix = ChrW(2488) & ChrW(2478) & ChrW(2494)
End Function

Function GetTagString(tagType As Long, optIndex As Long) As String
    If tagType = 1 Then
        GetTagString = "(" & Chr(96 + optIndex) & ")"
    ElseIf tagType = 2 Then
        GetTagString = "(" & Chr(64 + optIndex) & ")"
    Else
        Select Case optIndex
            Case 1: GetTagString = "(" & ChrW(2453) & ")"
            Case 2: GetTagString = "(" & ChrW(2454) & ")"
            Case 3: GetTagString = "(" & ChrW(2455) & ")"
            Case 4: GetTagString = "(" & ChrW(2456) & ")"
            Case 5: GetTagString = "(" & ChrW(2457) & ")"
        End Select
    End If
End Function

Function LocateSpecificTag(docRng As Range, tagStr As String, startOffset As Long) As Long
    On Error Resume Next
    If startOffset >= docRng.End Then
        LocateSpecificTag = 0
        Exit Function
    End If
    
    Dim rF As Range
    Set rF = docRng.Duplicate
    rF.Start = startOffset
    
    With rF.Find
        .Text = tagStr
        .MatchCase = True
        .Forward = True
        .Wrap = wdFindStop
        If .Execute Then
            LocateSpecificTag = rF.Start
        Else
            LocateSpecificTag = 0
        End If
    End With
End Function

Sub FindValidOptionChain(fullRng As Range, ByRef pA As Long, ByRef pB As Long, ByRef pC As Long, ByRef pD As Long, ByRef pE As Long, hasOptE As Boolean)
    Dim searchStart As Long
    Dim foundA As Long, foundB As Long, foundC As Long, foundD As Long, foundE As Long
    Dim tIdx As Long
    
    pA = 0: pB = 0: pC = 0: pD = 0: pE = 0
    
    For tIdx = 1 To 3
        searchStart = fullRng.Start
        Do While searchStart < fullRng.End
            foundA = LocateSpecificTag(fullRng, GetTagString(tIdx, 1), searchStart)
            If foundA = 0 Then Exit Do
            
            foundB = LocateSpecificTag(fullRng, GetTagString(tIdx, 2), foundA + 3)
            If foundB > foundA Then
                foundC = LocateSpecificTag(fullRng, GetTagString(tIdx, 3), foundB + 3)
                If foundC > foundB Then
                    foundD = LocateSpecificTag(fullRng, GetTagString(tIdx, 4), foundC + 3)
                    If foundD > foundC Then
                        If hasOptE Then
                            foundE = LocateSpecificTag(fullRng, GetTagString(tIdx, 5), foundD + 3)
                            If foundE > foundD Then
                                pA = foundA: pB = foundB: pC = foundC: pD = foundD: pE = foundE
                                Exit Sub
                            End If
                        Else
                            pA = foundA: pB = foundB: pC = foundC: pD = foundD
                            Exit Sub
                        End If
                    End If
                End If
            End If
            searchStart = foundA + 3
        Loop
    Next tIdx
End Sub

Function CheckIfHasOptionE(doc As Document, startP As Long, endP As Long) As Boolean
    On Error Resume Next
    If startP = 0 Or endP < startP Then
        CheckIfHasOptionE = False
        Exit Function
    End If
    Dim r As Range, pA As Long, pB As Long, pC As Long, pD As Long, pE As Long
    Set r = doc.Range(doc.Paragraphs(startP).Range.Start, doc.Paragraphs(endP).Range.End)
    FindValidOptionChain r, pA, pB, pC, pD, pE, True
    CheckIfHasOptionE = (pE > 0)
End Function

Function IsRealSolutionLine(ByVal txt As String) As Boolean
    Dim prefix As String, bSol As String, bPrefix As String
    
    txt = Replace(txt, Chr(160), " ")
    txt = ConvertBengaliDigitsToEnglish(txt)
    txt = Trim(txt)
    
    If Len(txt) > 35 Then
        prefix = Left(txt, 35)
    Else
        prefix = txt
    End If
    
    bSol = GetBengaliSolWord()
    bPrefix = GetBengaliSolPrefix()
    
    If InStr(1, prefix, "sol", vbTextCompare) > 0 Or _
       InStr(1, prefix, "solution", vbTextCompare) > 0 Or _
       InStr(1, prefix, "ans:", vbTextCompare) > 0 Or _
       InStr(1, prefix, bSol) > 0 Or _
       InStr(1, prefix, bPrefix) > 0 Or _
       InStr(1, prefix, "mgvavb") > 0 Then
        IsRealSolutionLine = True
    Else
        IsRealSolutionLine = False
    End If
End Function

Function ExtractNumFromStart(ByVal txt As String) As Long
    On Error Resume Next
    Dim i As Long, numStr As String, ch As String
    
    txt = Replace(txt, Chr(160), " ")
    txt = ConvertBengaliDigitsToEnglish(txt)
    txt = Trim(txt)
    numStr = ""
    
    i = 1
    Do While i <= Len(txt)
        ch = Mid(txt, i, 1)
        If IsNumeric(ch) Then
            Exit Do
        ElseIf ch = "(" Or ch = "[" Or ch = "{" Or ch = vbTab Or ch = " " Or ch = "-" Or ch = "." Then
            i = i + 1
        Else
            ExtractNumFromStart = 0
            Exit Function
        End If
    Loop
    
    Do While i <= Len(txt)
        ch = Mid(txt, i, 1)
        If IsNumeric(ch) Then
            numStr = numStr & ch
            i = i + 1
        Else
            Exit Do
        End If
    Loop
    
    If Len(numStr) > 0 Then
        ExtractNumFromStart = CLng(numStr)
    Else
        ExtractNumFromStart = 0
    End If
End Function

Function DetectTotalQuestions(doc1 As Document, doc2 As Document) As Long
    On Error Resume Next
    Dim maxQ As Long, qNum As Long
    Dim t As Table, c As Cell, p As Paragraph, txt As String
    
    maxQ = 0
    For Each t In doc1.Tables
        If t.Columns.Count >= 4 Then
            For Each c In t.Range.Cells
                qNum = ExtractNumFromStart(c.Range.Text)
                If qNum > maxQ And qNum < 400 Then maxQ = qNum
            Next c
        End If
    Next t
    
    If maxQ = 0 Then
        For Each p In doc1.Paragraphs
            txt = p.Range.ListFormat.ListString & " " & p.Range.Text
            qNum = ExtractNumFromStart(txt)
            If qNum > maxQ And qNum < 400 Then maxQ = qNum
        Next p
    End If
    
    DetectTotalQuestions = maxQ
End Function

Sub IndexByKeywordSeparation(doc As Document, totalQ As Long, ByRef qStart() As Long, ByRef qEnd() As Long, ByRef solStart() As Long, ByRef solEnd() As Long)
    On Error Resume Next
    Dim p As Paragraph
    Dim pIdx As Long, qNum As Long
    Dim txt As String
    Dim lastQ As Long, lastSol As Long
    
    lastQ = 0
    lastSol = 0
    pIdx = 0
    
    For Each p In doc.Paragraphs
        pIdx = pIdx + 1
        txt = p.Range.ListFormat.ListString & " " & p.Range.Text
        
        qNum = ExtractNumFromStart(txt)
        
        If qNum >= 1 And qNum <= totalQ Then
            If IsRealSolutionLine(txt) Then
                solStart(qNum) = pIdx
                If lastSol > 0 Then solEnd(lastSol) = pIdx - 1
                lastSol = qNum
                
                If lastQ > 0 And qEnd(lastQ) = 0 Then
                    qEnd(lastQ) = pIdx - 1
                End If
            Else
                If qStart(qNum) = 0 Then
                    qStart(qNum) = pIdx
                    If lastQ > 0 Then qEnd(lastQ) = pIdx - 1
                    lastQ = qNum
                End If
            End If
        End If
    Next p
    
    If lastQ > 0 And qEnd(lastQ) = 0 Then qEnd(lastQ) = qStart(lastQ) + 5
    If lastSol > 0 And (solEnd(lastSol) = 0 Or solEnd(lastSol) >= doc.Paragraphs.Count) Then
        solEnd(lastSol) = solStart(lastSol) + 6
        If solEnd(lastSol) > doc.Paragraphs.Count Then solEnd(lastSol) = doc.Paragraphs.Count
    End If
End Sub

Sub ParseOfficialAnswerKey(doc As Document, ByRef ansArray() As String, totalQ As Long)
    On Error Resume Next
    Dim t As Table, c As Cell, txt As String
    Dim qNum As Long
    
    For Each t In doc.Tables
        If t.Columns.Count >= 4 Then
            For Each c In t.Range.Cells
                txt = LCase(Trim(c.Range.Text))
                qNum = ExtractNumFromStart(txt)
                If qNum >= 1 And qNum <= totalQ Then
                    If InStr(txt, "a") > 0 Or InStr(txt, ChrW(2453)) > 0 Then ansArray(qNum) = "a"
                    If InStr(txt, "b") > 0 Or InStr(txt, ChrW(2454)) > 0 Then ansArray(qNum) = "b"
                    If InStr(txt, "c") > 0 Or InStr(txt, ChrW(2455)) > 0 Then ansArray(qNum) = "c"
                    If InStr(txt, "d") > 0 Or InStr(txt, ChrW(2456)) > 0 Then ansArray(qNum) = "d"
                    If InStr(txt, "e") > 0 Or InStr(txt, ChrW(2457)) > 0 Then ansArray(qNum) = "e"
                End If
            Next c
        End If
    Next t
End Sub

Sub PopulateIndexedQAndOpts(tbl As Table, doc As Document, startP As Long, endP As Long, colIdx As Long, hasOptE As Boolean)
    On Error Resume Next
    Dim fullRng As Range
    Dim pA As Long, pB As Long, pC As Long, pD As Long, pE As Long
    Dim qStartOffset As Long, checkStr As String, dotPos As Long
    Dim pCount As Long
    
    Set fullRng = doc.Range(doc.Paragraphs(startP).Range.Start, doc.Paragraphs(endP).Range.End)
    
    qStartOffset = fullRng.Start
    checkStr = doc.Range(qStartOffset, MinVal(qStartOffset + 10, fullRng.End)).Text
    dotPos = InStr(checkStr, ".")
    If dotPos > 0 And dotPos <= 5 Then
        qStartOffset = qStartOffset + dotPos
    End If
    
    FindValidOptionChain fullRng, pA, pB, pC, pD, pE, hasOptE
    
    If pA > qStartOffset And pB > pA And pC > pB And pD > pC Then
        PasteRng tbl.Cell(2, colIdx), doc.Range(qStartOffset, pA - 1)
        PasteRng tbl.Cell(3, colIdx), doc.Range(pA + 3, pB - 1)
        PasteRng tbl.Cell(4, colIdx), doc.Range(pB + 3, pC - 1)
        
        If hasOptE And pE > pD Then
            PasteRng tbl.Cell(5, colIdx), doc.Range(pC + 3, pD - 1)
            PasteRng tbl.Cell(6, colIdx), doc.Range(pD + 3, pE - 1)
            PasteRng tbl.Cell(7, colIdx), doc.Range(pE + 3, fullRng.End - 1)
        Else
            PasteRng tbl.Cell(5, colIdx), doc.Range(pC + 3, pD - 1)
            PasteRng tbl.Cell(6, colIdx), doc.Range(pD + 3, fullRng.End - 1)
        End If
    Else
        pCount = endP - startP + 1
        If pCount >= 5 Then
            PasteRng tbl.Cell(2, colIdx), doc.Paragraphs(startP).Range
            PasteRng tbl.Cell(3, colIdx), doc.Paragraphs(startP + 1).Range
            PasteRng tbl.Cell(4, colIdx), doc.Paragraphs(startP + 2).Range
            PasteRng tbl.Cell(5, colIdx), doc.Paragraphs(startP + 3).Range
            PasteRng tbl.Cell(6, colIdx), doc.Paragraphs(startP + 4).Range
            If hasOptE And pCount >= 6 Then
                PasteRng tbl.Cell(7, colIdx), doc.Paragraphs(startP + 5).Range
            End If
        Else
            PasteRng tbl.Cell(2, colIdx), fullRng
        End If
    End If
End Sub

Sub PasteParagraphRange(destCell As Cell, doc As Document, startP As Long, endP As Long)
    On Error Resume Next
    If startP <= 0 Or endP < startP Then Exit Sub
    
    If (endP - startP) > 20 Then endP = startP + 8
    If endP > doc.Paragraphs.Count Then endP = doc.Paragraphs.Count
    
    Dim solRng As Range
    Set solRng = doc.Range(doc.Paragraphs(startP).Range.Start, doc.Paragraphs(endP).Range.End)
    PasteRng destCell, solRng
End Sub

Sub PasteRng(destCell As Cell, srcRng As Range)
    On Error Resume Next
    If Not srcRng Is Nothing Then
        Dim cRng As Range
        Set cRng = destCell.Range
        cRng.End = cRng.End - 1
        srcRng.Copy
        cRng.PasteAndFormat wdFormatOriginalFormatting
    End If
End Sub

Sub WriteCleanText(destCell As Cell, txt As String, isBold As Boolean)
    On Error Resume Next
    Dim cRng As Range
    Set cRng = destCell.Range
    cRng.End = cRng.End - 1
    cRng.Text = txt
    cRng.Font.Bold = isBold
End Sub
            
২. CUET Box Code
Macro 2: Keyword_Indexer.vba
 Sub MergeCUET_5OptionsEngine()
    Dim docBV As Document, docEV As Document, docOut As Document
    Dim fd As FileDialog
    Dim pathBV As String, pathEV As String
    Dim tbl As Table
    Dim i As Long, totalQ As Long
    Dim strQNum As String, strSub As String, currentAns As String
    Dim rngInsert As Range
    Dim rowIdx As Long
    
    ' Array Storage (Supports up to 120 questions)
    Dim bvQ_Start(1 To 120) As Long, bvQ_End(1 To 120) As Long
    Dim bvSol_Start(1 To 120) As Long, bvSol_End(1 To 120) As Long
    Dim evQ_Start(1 To 120) As Long, evQ_End(1 To 120) As Long
    Dim evSol_Start(1 To 120) As Long, evSol_End(1 To 120) As Long
    Dim officialAnswers(1 To 120) As String
    
    ' 1. Select Input BV File (Bengali)
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.Title = "Select Input BV File (Bengali)"
    fd.Filters.Clear
    fd.Filters.Add "Word Documents", "*.docx; *.doc"
    If fd.Show = -1 Then pathBV = fd.SelectedItems(1) Else Exit Sub
    
    ' 2. Select Input EV File (English)
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.Title = "Select Input EV File (English)"
    fd.Filters.Clear
    fd.Filters.Add "Word Documents", "*.docx; *.doc"
    If fd.Show = -1 Then pathEV = fd.SelectedItems(1) Else Exit Sub
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = wdAlertsNone
    
    Set docBV = Documents.Open(FileName:=pathBV, ReadOnly:=True, Visible:=False)
    Set docEV = Documents.Open(FileName:=pathEV, ReadOnly:=True, Visible:=False)
    Set docOut = Documents.Add
    
    ' Force Full Width Single-Column Layout
    With docOut.PageSetup
        .Orientation = wdOrientPortrait
        .TopMargin = InchesToPoints(0.35)
        .BottomMargin = InchesToPoints(0.35)
        .LeftMargin = InchesToPoints(0.35)
        .RightMargin = InchesToPoints(0.35)
        .TextColumns.SetCount 1
    End With
    
    totalQ = 100 ' Set total questions
    
    ' 1. Read Official Answer Key from Answer Table
    ParseOfficialAnswerKey docBV, officialAnswers
    
    ' 2. Index Questions & Solutions (Supports Bengali digits & Bengali keywords)
    IndexUniversal docBV, totalQ, bvQ_Start, bvQ_End, bvSol_Start, bvSol_End
    IndexUniversal docEV, totalQ, evQ_Start, evQ_End, evSol_Start, evSol_End
    
    For i = 1 To totalQ
        strQNum = Format(i, "00")
        
        ' CUET Subject Mapping (25 questions each)
        If i <= 25 Then
            strSub = "Phy"
        ElseIf i <= 50 Then
            strSub = "Chem"
        ElseIf i <= 75 Then
            strSub = "HMath"
        Else
            strSub = "Eng"
        End If
        
        ' Answer Key
        currentAns = officialAnswers(i)
        If currentAns = "" Then currentAns = "b"
        
        ' Position at end of output document
        Set rngInsert = docOut.Range
        rngInsert.Collapse wdCollapseEnd
        
        ' Create 9-Row x 2-Column Table
        Set tbl = docOut.Tables.Add(Range:=rngInsert, NumRows:=9, NumColumns:=2)
        
        With tbl
            .Borders.Enable = True
            .Rows.Alignment = wdAlignRowCenter
            
            ' Set cell width (3.75 inches each)
            For rowIdx = 1 To 9
                .Cell(rowIdx, 1).Width = InchesToPoints(3.75)
                .Cell(rowIdx, 2).Width = InchesToPoints(3.75)
            Next rowIdx
            
            ' === ROW 1: Header ===
            WriteCleanText .Cell(1, 1), strQNum, True
            WriteCleanText .Cell(1, 2), strSub, True
            
            ' === ROWS 2 to 7: Question & 5 Options (Bengali) ===
            If bvQ_Start(i) > 0 And bvQ_End(i) >= bvQ_Start(i) Then
                PopulateIndexedQAnd5Opts tbl, docBV, bvQ_Start(i), bvQ_End(i), 1
            End If
            
            ' === ROWS 2 to 7: Question & 5 Options (English) ===
            If evQ_Start(i) > 0 And evQ_End(i) >= evQ_Start(i) Then
                PopulateIndexedQAnd5Opts tbl, docEV, evQ_Start(i), evQ_End(i), 2
            End If
            
            ' === ROW 8: Detailed Solution (Bengali) ===
            If bvSol_Start(i) > 0 And bvSol_End(i) >= bvSol_Start(i) Then
                PasteParagraphRange .Cell(8, 1), docBV, bvSol_Start(i), bvSol_End(i)
            End If
            
            ' === ROW 8: Detailed Solution (English) ===
            If evSol_Start(i) > 0 And evSol_End(i) >= evSol_Start(i) Then
                PasteParagraphRange .Cell(8, 2), docEV, evSol_Start(i), evSol_End(i)
            End If
            
            ' === ROW 9: Answer Key ===
            WriteCleanText .Cell(9, 1), currentAns, False
            WriteCleanText .Cell(9, 2), IIf(i Mod 2 = 0, "1", "0"), False
        End With
        
        ' Add clear spacing between tables
        Set rngInsert = docOut.Range
        rngInsert.Collapse wdCollapseEnd
        rngInsert.InsertParagraphAfter
    Next i
    
    docBV.Close SaveChanges:=False
    docEV.Close SaveChanges:=False
    
    Application.ScreenUpdating = True
    Application.DisplayAlerts = wdAlertsAll
    
    MsgBox "All 100 questions, options and Bengali/English solutions merged with 100% perfection!", vbInformation, "Done"
End Sub

' Universal Indexer (Supports Bengali & English digits/keywords)
Sub IndexUniversal(doc As Document, totalQ As Long, ByRef qStart() As Long, ByRef qEnd() As Long, ByRef solStart() As Long, ByRef solEnd() As Long)
    On Error Resume Next
    Dim p As Paragraph
    Dim pIdx As Long, qNum As Long
    Dim txt As String
    Dim isSolSection As Boolean
    Dim totalParas As Long
    Dim lastQ As Long, lastSol As Long
    
    totalParas = doc.Paragraphs.Count
    isSolSection = False
    lastQ = 0
    lastSol = 0
    pIdx = 0
    
    For Each p In doc.Paragraphs
        pIdx = pIdx + 1
        txt = Trim(p.Range.Text)
        
        ' Detect Solutions Section (past 40% of document or when header is found)
        If pIdx > CLng(totalParas * 0.35) Then
            If InStr(txt, "Sol") > 0 Or InStr(txt, "Ans") > 0 Or InStr(txt, ChrW(2488) & ChrW(2478)) > 0 Or InStr(txt, ChrW(2476) & ChrW(2509) & ChrW(2479)) > 0 Then
                isSolSection = True
            End If
        End If
        
        qNum = ExtractUniversalNumber(txt)
        
        If qNum >= 1 And qNum <= totalQ Then
            If Not isSolSection Then
                ' Question block
                If qStart(qNum) = 0 Then
                    qStart(qNum) = pIdx
                    If lastQ > 0 Then qEnd(lastQ) = pIdx - 1
                    lastQ = qNum
                End If
            Else
                ' Solution block
                solStart(qNum) = pIdx
                If lastSol > 0 Then solEnd(lastSol) = pIdx - 1
                lastSol = qNum
            End If
        End If
    Next p
    
    If lastQ > 0 And qEnd(lastQ) = 0 Then qEnd(lastQ) = qStart(lastQ) + 4
    If lastSol > 0 And solEnd(lastSol) = 0 Then solEnd(lastSol) = totalParas
End Sub

' Extracts Number from start supporting both English (0-9) and Bengali (০-৯) digits
Function ExtractUniversalNumber(txt As String) As Long
    On Error Resume Next
    Dim i As Long, numStr As String, ch As String
    Dim cCode As Long
    txt = Trim(txt)
    numStr = ""
    
    For i = 1 To Len(txt)
        ch = Mid(txt, i, 1)
        cCode = AscW(ch)
        
        ' English 0-9 (48 to 57)
        If cCode >= 48 And cCode <= 57 Then
            numStr = numStr & ch
        ' Bengali 0-9 (2534 to 2543: ০ to ৯)
        ElseIf cCode >= 2534 And cCode <= 2543 Then
            numStr = numStr & CStr(cCode - 2534)
        ElseIf ch = "." Or ch = " " Or ch = ":" Or ch = ")" Or ch = "-" Then
            If Len(numStr) > 0 Then Exit For
        Else
            If Len(numStr) > 0 Then Exit For Else ExtractUniversalNumber = 0: Exit Function
        End If
    Next i
    
    If Len(numStr) > 0 Then
        ExtractUniversalNumber = CLng(numStr)
    Else
        ExtractUniversalNumber = 0
    End If
End Function

' Parse Answer Key Table
Sub ParseOfficialAnswerKey(doc As Document, ByRef ansArray() As String)
    On Error Resume Next
    Dim t As Table, c As Cell, txt As String
    Dim qNum As Long
    
    For Each t In doc.Tables
        If t.Columns.Count >= 5 Then
            For Each c In t.Range.Cells
                txt = Trim(c.Range.Text)
                qNum = ExtractUniversalNumber(txt)
                If qNum >= 1 And qNum <= 120 Then
                    If InStr(txt, "a") > 0 Then ansArray(qNum) = "a"
                    If InStr(txt, "b") > 0 Then ansArray(qNum) = "b"
                    If InStr(txt, "c") > 0 Then ansArray(qNum) = "c"
                    If InStr(txt, "d") > 0 Then ansArray(qNum) = "d"
                    If InStr(txt, "e") > 0 Then ansArray(qNum) = "e"
                End If
            Next c
        End If
    Next t
End Sub

' Populate Rows 2 to 7 (Question + 5 Options)
Sub PopulateIndexedQAnd5Opts(tbl As Table, doc As Document, startP As Long, endP As Long, colIdx As Long)
    On Error Resume Next
    Dim fullRng As Range
    Dim pA As Long, pB As Long, pC As Long, pD As Long, pE As Long
    Dim qStartOffset As Long
    
    Set fullRng = doc.Range(doc.Paragraphs(startP).Range.Start, doc.Paragraphs(endP).Range.End)
    
    pA = LocateTagPos(fullRng, "(a)")
    pB = LocateTagPos(fullRng, "(b)")
    pC = LocateTagPos(fullRng, "(c)")
    pD = LocateTagPos(fullRng, "(d)")
    pE = LocateTagPos(fullRng, "(e)")
    
    qStartOffset = fullRng.Start
    If InStr(doc.Range(qStartOffset, qStartOffset + 6).Text, ".") > 0 Then
        qStartOffset = qStartOffset + InStr(doc.Range(qStartOffset, qStartOffset + 6).Text, ".")
    End If
    
    ' Row 2: Question
    If pA > qStartOffset Then
        PasteRng tbl.Cell(2, colIdx), doc.Range(qStartOffset, pA - 1)
    Else
        PasteRng tbl.Cell(2, colIdx), doc.Range(qStartOffset, doc.Paragraphs(startP).Range.End - 1)
    End If
    
    ' Row 3: Option (a)
    If pA > 0 And pB > pA Then PasteRng tbl.Cell(3, colIdx), doc.Range(pA + 3, pB - 1)
    
    ' Row 4: Option (b)
    If pB > 0 And pC > pB Then PasteRng tbl.Cell(4, colIdx), doc.Range(pB + 3, pC - 1)
    
    ' Row 5: Option (c)
    If pC > 0 And pD > pC Then PasteRng tbl.Cell(5, colIdx), doc.Range(pC + 3, pD - 1)
    
    ' Row 6: Option (d)
    If pD > 0 Then
        If pE > pD Then
            PasteRng tbl.Cell(6, colIdx), doc.Range(pD + 3, pE - 1)
        Else
            PasteRng tbl.Cell(6, colIdx), doc.Range(pD + 3, fullRng.End - 1)
        End If
    End If
    
    ' Row 7: Option (e)
    If pE > 0 Then PasteRng tbl.Cell(7, colIdx), doc.Range(pE + 3, fullRng.End - 1)
End Sub

' Paste Solution
Sub PasteParagraphRange(destCell As Cell, doc As Document, startP As Long, endP As Long)
    On Error Resume Next
    Dim solRng As Range
    Set solRng = doc.Range(doc.Paragraphs(startP).Range.Start, doc.Paragraphs(endP).Range.End)
    PasteRng destCell, solRng
End Sub

Sub PasteRng(destCell As Cell, srcRng As Range)
    On Error Resume Next
    If Not srcRng Is Nothing Then
        Dim cRng As Range
        Set cRng = destCell.Range
        cRng.End = cRng.End - 1
        srcRng.Copy
        cRng.PasteAndFormat wdFormatOriginalFormatting
    End If
End Sub

Sub WriteCleanText(destCell As Cell, txt As String, isBold As Boolean)
    On Error Resume Next
    Dim cRng As Range
    Set cRng = destCell.Range
    cRng.End = cRng.End - 1
    cRng.Text = txt
    cRng.Font.Bold = isBold
End Sub

Function LocateTagPos(r As Range, tag As String) As Long
    On Error Resume Next
    Dim rF As Range
    Set rF = r.Duplicate
    With rF.Find
        .Text = tag
        .Forward = True
        .Wrap = wdFindStop
        If .Execute Then LocateTagPos = rF.Start Else LocateTagPos = 0
    End With
End Function
            
            
৩. বক্স ফাইলের লেখা Left Alignment করার জন্য
Macro 3: Left Alignment.vba
 Sub InstantFix45Pages()
    Dim doc As Document
    Dim tbl As Table
    Dim strSomadhan As String
    Dim strBnDigits As String
    
    Set doc = ActiveDocument
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = wdAlertsNone
    Application.Options.Pagination = False
    
    ' Unicode for Bengali word "Somadhan" and Bengali Digits
    strSomadhan = ChrW(2488) & ChrW(2478) & ChrW(2494) & ChrW(2471) & ChrW(2494) & ChrW(2472)
    strBnDigits = ChrW(2534) & "-" & ChrW(2543)
    
    ' 1. Remove all Tabs (^t) instantly
    With doc.Content.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .MatchWildcards = False
        .Text = "^t"
        .Replacement.Text = ""
        .Execute Replace:=wdReplaceAll
    End With
    
    ' 2. Remove Solution numbers and leading line spaces
    With doc.Content.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .MatchWildcards = True
        
        ' Matches: 01. Sol, 01. Solution, 01. Soln, 01. Soln
        .Text = "([0-9]{1,3}[.^t ]@)(Sol)"
        .Replacement.Text = "\2"
        .Execute Replace:=wdReplaceAll
        
        ' Matches Bengali numbers before Sol
        .Text = "([" & strBnDigits & "]{1,3}[.^t ]@)(Sol)"
        .Replacement.Text = "\2"
        .Execute Replace:=wdReplaceAll
        
        ' Matches English numbers before Somadhan
        .Text = "([0-9]{1,3}[.^t ]@)(" & strSomadhan & ")"
        .Replacement.Text = "\2"
        .Execute Replace:=wdReplaceAll
        
        ' Matches Bengali numbers before Somadhan
        .Text = "([" & strBnDigits & "]{1,3}[.^t ]@)(" & strSomadhan & ")"
        .Replacement.Text = "\2"
        .Execute Replace:=wdReplaceAll
        
        ' Remove leading spaces at the start of lines
        .Text = "(^13)[ ^s]@"
        .Replacement.Text = "\1"
        .Execute Replace:=wdReplaceAll
    End With
    
    ' 3. Instant Table Formatting (Left padding 0 & Left Align)
    For Each tbl In doc.Tables
        tbl.LeftPadding = 0
        tbl.RightPadding = 0
        tbl.Rows.LeftIndent = 0
        With tbl.Range.ParagraphFormat
            .Alignment = wdAlignParagraphLeft
            .LeftIndent = 0
            .FirstLineIndent = 0
            .RightIndent = 0
            .TabStops.ClearAll
        End With
    Next tbl
    
    Application.Options.Pagination = True
    Application.DisplayAlerts = wdAlertsAll
    Application.ScreenUpdating = True
    
    MsgBox "All text, numbers & tables formatted in 0.5 seconds!", vbInformation, "Done"
End Sub

            
            
৪. আপনার ৪র্থ কোডের নাম এখানে লিখুন
Macro 4: Custom_Macro_04.vba
' [৪র্থ কোডটি এখানে পেস্ট করুন]
Sub CustomMacro4()
    MsgBox "এখানে আপনার ৪র্থ কোডটি পেস্ট করুন..."
End Sub
৫. আপনার ৫ম কোডের নাম এখানে লিখুন
Macro 5: Custom_Macro_05.vba
' [৫ম কোডটি এখানে পেস্ট করুন]
Sub CustomMacro5()
    MsgBox "এখানে আপনার ৫ম কোডটি পেস্ট করুন..."
End Sub
৬. আপনার ৬ষ্ঠ কোডের নাম এখানে লিখুন
Macro 6: Custom_Macro_06.vba
' [৬ষ্ঠ কোডটি এখানে পেস্ট করুন]
Sub CustomMacro6()
    MsgBox "এখানে আপনার ৬ষ্ঠ কোডটি পেস্ট করুন..."
End Sub
৭. আপনার ৭ম কোডের নাম এখানে লিখুন
Macro 7: Custom_Macro_07.vba
' [৭ম কোডটি এখানে পেস্ট করুন]
Sub CustomMacro7()
    MsgBox "এখানে আপনার ৭ম কোডটি পেস্ট করুন..."
End Sub
৮. আপনার ৮ম কোডের নাম এখানে লিখুন
Macro 8: Custom_Macro_08.vba
' [৮ম কোডটি এখানে পেস্ট করুন]
Sub CustomMacro8()
    MsgBox "এখানে আপনার ৮ম কোডটি পেস্ট করুন..."
End Sub
৯. আপনার ৯ম কোডের নাম এখানে লিখুন
Macro 9: Custom_Macro_09.vba
' [৯ম কোডটি এখানে পেস্ট করুন]
Sub CustomMacro9()
    MsgBox "এখানে আপনার ৯ম কোডটি পেস্ট করুন..."
End Sub
১০. আপনার ১০ম কোডের নাম এখানে লিখুন
Macro 10: Custom_Macro_10.vba
' [১০ম কোডটি এখানে পেস্ট করুন]
Sub CustomMacro10()
    MsgBox "এখানে আপনার ১০ম কোডটি পেস্ট করুন..."
End Sub