从包含特定单词后的字符串的单元格中提取值

时间:2018-03-30 08:03:37

标签: excel vba excel-vba excel-formula

我有一个很大的excel文件,在一列中它包含Json,如下所示:

""wrtieSeg"": {
    ""ValueName"": ""Type1"",
    ""Div"": ""45"",
    ""Date"": ""08/06/2017"",
    ""fig"": ""0-100""
  },
  ""readSeg"": {
    ""ValueName"": ""Type2"",
    ""Div"": ""45"",
    ""Date"": ""08/06/2017"",
    ""fig"": ""980""
  }

现在我的Excel工作表中有两列(Type1Type2),我希望fig列中的0-100值(例如Type1) ,fig列中的980值(例如Type2)。

2 个答案:

答案 0 :(得分:0)

由于您的JSON非常基本,因此小辅助函数和主函数应足以解析它。请注意,您的示例中没有有效的JSON,因为它缺少结束括号}。我在我的例子中添加了它(并且还编辑了你的问题是正确的)。

您必须在Module reference how to call VBA functions from sheet cells)的VBAProject中定义此代码。现在,如果您的JSON位于A1单元格中,并且您想要提取Type1的值,那么您必须使用以下公式:=ExtractFromJson(A1, "Type1")

Option Explicit
Public Function ExtractFromJson(json As String, valueName As String)
    'declare variables needed
    Dim elementStartIndex As Long, elementEndIndex As Long, element As String
    'loop through json, extracting elements
    Do While InStr(elementStartIndex + 1, json, "{") > 0
        'locate element by searching { and }
        elementStartIndex = InStr(elementStartIndex + 1, json, "{")
        elementEndIndex = InStr(elementStartIndex + 1, json, "}")
        'extract element and pass it to function
        element = Mid(json, elementStartIndex, elementEndIndex -  elementStartIndex + 1)
        ExtractFromJson = ParseElement(element, valueName)

        If ExtractFromJson <> "" Then
            Exit Function
        End If
    Loop
End Function

Function ParseElement(element As String, valueName As String) As String
    Dim valueNameIndex As Long
    'locate variable with specified name and take its value
    valueNameIndex = InStr(1, element, """""ValueName"""":") + 14
    If valueName = Trim(Replace(Mid(element, valueNameIndex, InStr(valueNameIndex, element, ",") - valueNameIndex), """", "")) Then
        valueNameIndex = InStr(1, element, """""fig"""":") + 8
        ParseElement = Trim(Replace(Mid(element, valueNameIndex, InStr(valueNameIndex, element, "}") - valueNameIndex), """", ""))
        Exit Function
    End If
End Function

答案 1 :(得分:0)

你可以使用:

Function ParseElement(myType As String, A1 As Variant)
    Dim v As Variant

    v = Split(Mid(A1, InStr(A1, myType)), """")

    ParseElement = v(Application.Match("fig", v, 0) + 3)
End Function

如果用户传递错误的myType参数或者Json单元格不包含它,您可以添加一些错误处理