Skip to content

Instantly share code, notes, and snippets.

@tzkmx
Created September 24, 2025 18:53
Show Gist options
  • Save tzkmx/5d1b903c3b9eb37334eaa41a3ece3f8e to your computer and use it in GitHub Desktop.
Save tzkmx/5d1b903c3b9eb37334eaa41a3ece3f8e to your computer and use it in GitHub Desktop.
Minimal utilities not longer allowed to write in macros
[CmdletBinding()]
param()
#--------------------------------------------------------------------------------
# UTILITY: ConvertTo-SpanishLongDate
# PURPOSE: Finds all cells in all tables containing only a date in dd/MM/yyyy
# format and converts it to a long Spanish date string.
# - Years before 2000 use "de" (e.g., 12 DE FEBRERO de 1989).
# - Years 2000 and after use "del" (e.g., 24 DE SEPTIEMBRE del 2025).
#--------------------------------------------------------------------------------
function ConvertTo-SpanishLongDate {
Write-Host "Iniciando conversión a formato de fecha largo (español)..."
$culture = [cultureinfo]::GetCultureInfo('es-ES')
$dateRegex = "^\d{2}/\d{2}/\d{4}$"
$cellsProcessed = 0
foreach ($table in $doc.Tables) {
foreach ($cell in $table.Range.Cells) {
# Trim whitespace and the invisible end-of-cell character
$cellText = $cell.Range.Text.Trim("`r`a").Trim()
if ($cellText -match $dateRegex) {
try {
$date = [datetime]::ParseExact($cellText, 'dd/MM/yyyy', $null)
$year = $date.Year
$monthName = $culture.DateTimeFormat.GetMonthName($date.Month).ToUpper()
$day = $date.Day
$preposition = if ($year -lt 2000) { "DE" } else { "DEL" }
$newDateString = "$day DE $monthName $preposition $year"
# Replace the cell content
$cell.Range.Text = $newDateString
$cellsProcessed++
}
catch {
Write-Warning "No se pudo procesar la fecha '$cellText' en una celda. Error: $_"
}
}
}
}
Write-Host "Operación completada. Celdas procesadas: $cellsProcessed" -ForegroundColor Green
}
#--------------------------------------------------------------------------------
# UTILITY: ConvertTo-ShortDate
# PURPOSE: Finds all cells in all tables containing a long Spanish date and
# converts it back to dd/MM/yyyy format.
#--------------------------------------------------------------------------------
function ConvertTo-ShortDate {
Write-Host "Iniciando conversión a formato de fecha corto (dd/MM/yyyy)..."
# Regex captures day, month name, and year. Works with "de" or "del".
$longDateRegex = "^(\d{1,2}) DE ([A-ZÑ]+) (?:de|del) (\d{4})$"
$cellsProcessed = 0
$monthMap = @{
"ENERO" = "01"; "FEBRERO" = "02"; "MARZO" = "03"; "ABRIL" = "04";
"MAYO" = "05"; "JUNIO" = "06"; "JULIO" = "07"; "AGOSTO" = "08";
"SEPTIEMBRE" = "09"; "OCTUBRE" = "10"; "NOVIEMBRE" = "11"; "DICIEMBRE" = "12"
}
foreach ($table in $doc.Tables) {
foreach ($cell in $table.Range.Cells) {
$cellText = $cell.Range.Text.Trim("`r`a").Trim()
if ($cellText -match $longDateRegex) {
# $matches is automatically populated by the -match operator
$day = $matches[1].PadLeft(2, '0')
$monthName = $matches[2]
$year = $matches[3]
if ($monthMap.ContainsKey($monthName)) {
$monthNumber = $monthMap[$monthName]
$newDateString = "$day/$monthNumber/$year"
$cell.Range.Text = $newDateString
$cellsProcessed++
}
else {
Write-Warning "Mes no reconocido '$monthName' en la celda con texto '$cellText'."
}
}
}
}
Write-Host "Operación completada. Celdas procesadas: $cellsProcessed" -ForegroundColor Green
}
# --- SCRIPT ENTRY POINT ---
try {
$word = [Runtime.Interopservices.Marshal]::GetActiveObject("Word.Application")
$doc = $word.ActiveDocument
Write-Host "Conectado al documento activo: $($doc.Name)" -ForegroundColor Cyan
}
catch {
Write-Host "Error: No se pudo conectar a una instancia de Word en ejecución." -ForegroundColor Red
Write-Host "Por favor, asegúrese de que Word esté abierto con un documento." -ForegroundColor Red
# Pause for 5 seconds before exiting to allow user to read the message
Start-Sleep -Seconds 5
exit 1
}
# Define the list of available utilities for the user to choose from
$utilities = @(
[pscustomobject]@{
Name = "Convertir Fechas a Formato Largo (ES)"
Description = "Busca 'DD/MM/YYYY' y lo convierte a 'D DE MES de/del AÑO'."
},
[pscustomobject]@{
Name = "Convertir Fechas a Formato Corto (DD/MM/YYYY)"
Description = "Busca 'D DE MES de/del AÑO' y lo convierte a 'DD/MM/YYYY'."
}
)
# Display the GridView and wait for user selection
$selection = $utilities | Out-GridView -Title "Utilidades de Word para Fechas en Tablas" -PassThru
# If a selection was made, invoke the associated action
if ($selection) {
Write-Host "Ejecutando la utilidad seleccionada: $($selection.Name)"
switch ($selection.Name) {
"Convertir Fechas a Formato Largo (ES)" { ConvertTo-SpanishLongDate }
"Convertir Fechas a Formato Corto (DD/MM/YYYY)" { ConvertTo-ShortDate }
}
}
else {
Write-Host "Ninguna operación seleccionada. El script ha finalizado."
}
# Pause at the end if run from outside a console
if ($Host.Name -eq "ConsoleHost") {
Write-Host "Presione Enter para salir..."
Read-Host
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment