top of page

Macro VBA excel a Json

Este código no se relaciona con C# sin embargo es util para cuando queremos convertir una tabla de excel en una cadena de texto tipo Json, es una macro hecha con visual basic para aplicaciones en excel.

​

Dada la clase Persona

​

Function AddQuotesIfString(dato As String)
    If IsNumeric(dato) Then
        AddQuotesIfString = dato
    Else
        AddQuotesIfString = """" & dato & """"
    End If
        

End Function
Sub ExcelToJsonManual()
    Dim excelRange As Range
    Dim i As Integer
    Dim j As Integer
    Dim json As String
    Dim comillas As String
      
    comillas = """"
    Set excelRange = Cells(1, 1).CurrentRegion
  
    j = 1
    json = "["
    For i = 2 To excelRange.Rows.Count
        json = json & "{" + vbLf
        Do While Cells(1, j) <> ""
            json = json & comillas & Cells(1, j) & comillas & ": " & AddQuotesIfString(Cells(i, j)) & "," + vbLf
            j = j + 1
        Loop
        j = 1
        json = Left(json, Len(json) - 2) + vbLf
        json = json & "}," + vbLf
        
    Next i
    json = Left(json, Len(json) - 2) + "]"
    
    Cells(i + 1, 1) = json

End Sub

bottom of page