2.5 KiB

Código de VBA para convertir una tabla de excel a un formato markdown

' activar la referencia de Microsoft Forms 2.0 Object Library (solo la primera vez)

Option Explicit

Sub rangeToMarkDown()

    Dim cell As Range
    Dim selectedRange As Range
    Set selectedRange = Application.Selection

    If selectedRange Is Nothing Then
        MsgBox "Selecciona un rango antes de ejecutar la macro.", vbExclamation
        Exit Sub
    End If

    Dim rowCounter As Integer
    Dim columnCounter As Integer
    Dim totalColumns As Integer
    Dim currentColumnWidth As Integer

    totalColumns = selectedRange.Columns.Count

    Dim columnWidth(1 To 50) As Integer ' Máximo 50 columnas
    Dim markdown As String
    Dim i As Integer, j As Integer, k As Integer
    Dim extraSpaces As Integer
    Dim currentLine As String

    ' Inicializa anchos de columna
    For i = 1 To totalColumns
        columnWidth(i) = 0
    Next i

    ' Calcular el ancho máximo de cada columna
    For Each Row In selectedRange.Rows
        columnCounter = 1
        For Each cell In Row.Cells
            currentColumnWidth = Len(CStr(cell.Text))
            If currentColumnWidth > columnWidth(columnCounter) Then
                columnWidth(columnCounter) = currentColumnWidth
            End If
            columnCounter = columnCounter + 1
        Next cell
    Next Row

    ' Construir tabla Markdown
    rowCounter = 0
    For Each Row In selectedRange.Rows
        columnCounter = 1
        currentLine = "|"
        For Each cell In Row.Cells
            currentColumnWidth = columnWidth(columnCounter)
            currentLine = currentLine & " " & cell.Text & _
                          Space(currentColumnWidth - Len(CStr(cell.Text))) & " |"
            columnCounter = columnCounter + 1
        Next cell
        markdown = markdown & currentLine & vbCrLf

        ' Agrega línea separadora después del encabezado
        If rowCounter = 0 Then
            currentLine = "|"
            For j = 1 To totalColumns
                currentLine = currentLine & " " & String(columnWidth(j), "-") & " |"
            Next j
            markdown = markdown & currentLine & vbCrLf
        End If

        rowCounter = rowCounter + 1
    Next Row

    ' Copiar al portapapeles
    Dim clipboard As New DataObject
    clipboard.SetText markdown
    clipboard.PutInClipboard

    MsgBox "? Tabla Markdown copiada al portapapeles.", vbInformation

End Sub