Visual Basic 6 function "ini_value_get"

Go back

Below you'll find the source for the Visual Basic 6 function ini_value_get.

Attribute VB_Name = "modIniValueGet"
' This function is downloaded from:
' You may freely distribute this file but please leave all comments, including this one, in it.
' @Author Stefan Thoolen <>

Option Explicit

' Returns a value from a specific key in a specific chapter
' @param    string  inidata         The INI contents (could be file_get_contents(filename))
' @param    string  chapter         The chapter name
' @param    string  key             The key name
' @param    boolean case_sensitive  When false, all chapters and keys are lower case, otherwise case remains
' @param    boolean as_array        When true, multiple values can be returned as array
' @return   string or array         The key's value(s)
' @author   Stefan Thoolen <>
Public Function ini_value_get(ByVal inidata As String, ByVal chapter As String, ByVal key As String, Optional ByVal case_sensitive As Boolean = False, Optional ByVal as_array As Boolean = False) As Variant
    Dim line As Variant, in_chapter As Boolean, p() As String
    Dim ret() As String, ret_cnt As Integer
    ReDim ret(0 To 0)
    For Each line In Split(inidata, vbLf)
        ' Removes a Cariage Return if exists
        If Right(line, 1) = vbCr Then line = Left(line, Len(line) - 1)
        ' Removes additional whitespace around the line
        line = Trim(line)
        ' Checks if this is a chapter
        If Left(line, 1) = "[" And Right(line, 1) = "]" Then
            ' We are not in the right chapter
            in_chapter = False
            ' Except if we are in the right chapter
            If case_sensitive And Trim(Mid(line, 2, Len(line) - 2)) = chapter Then
                in_chapter = True
            ElseIf Trim(LCase(Mid(line, 2, Len(line) - 2))) = LCase(chapter) Then
                in_chapter = True
            End If
        ElseIf Left(line, 1) <> ";" And line <> "" And in_chapter Then
            ' Key found
            p = Split(line, "=", 2)
            If (case_sensitive And Trim(p(LBound(p))) = key) _
            Or (Not case_sensitive And Trim(LCase(p(LBound(p)))) = LCase(key)) Then
                ReDim Preserve ret(0 To ret_cnt)
                ret(ret_cnt) = Trim(p(UBound(p)))
                ret_cnt = ret_cnt + 1
            End If
        End If
    If as_array Then ini_value_get = ret Else ini_value_get = ret(0)
End Function