0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ExcelマクロでINIファイルからKEY-VALUEを変換する

0
Last updated at Posted at 2023-06-09

1. はじめに

  • Excelのセルの値をKEYにVALUEに変換したい

2. 開発環境

  • Excel
  • Excel VBA

3. Exclマクロ

' WSHオブジェクト
Dim WSH_OBJECT As Object
Set WSH_OBJECT = CreateObject("WScript.Shell")

' MyDocumentパス
Dim MYDOCUMENT_PATH As String
MYDOCUMENT_PATH = WSH_OBJECT.SpecialFolders("MyDocuments")
MYDOCUMENT_PATH = WSH_OBJECT.SpecialFolders(16)

' INIファイル取得
Dim KEY_VALUE As New Scripting.Dictionary
Set KEY_VALUE = GetMapFromIniFile(MYDOCUMENT_PATH & "\key-value.ini")

' KEY-VALUE変換
Public Sub KEY-VALUE変換()

    Dim startGyo As Long, endGyo As Long, startRetu As Long, endRetu As Long, Gyo As Long
    Dim wkMember As String, wkMeisyo As String
    
    If TypeName(Selection) = "Range" Then
        startGyo = Selection(1).Row
        endGyo = Selection(Selection.Count).Row
        startRetu = Selection(1).Column
        endRetu = Selection(Selection.Count).Column

        For Gyo = startGyo To endGyo
            DoEvents
            If Cells(Gyo, startRetu) <> "" Then
                wkMember = Trim(Cells(Gyo, startRetu))
                wkMeisyo = TABLE_DB.Item(wkMember)
                If wkMeisyo <> "NONE" Then
                    Cells(Gyo, startRetu + 1) = wkMeisyo
                End If
            End If
        Next Gyo
    End If
    
End Sub

' INIファイルからディクショナリを作成する
Public Function GetMapFromIniFile(iniPath As String) As Scripting.Dictionary

    Dim Map As New Scripting.Dictionary
    Dim GetMapFromIni As New Scripting.Dictionary
    Dim fso As Object, file As Object
    Set fso = New Scripting.FileSystemObject
    Set file = fso.OpenTextFile(iniPath, 1)
    
    Map.CompareMode = vbTextCompare
    
    Dim line As String, key As String, Value As String, arr
    Do Until file.AtEndOfStream
        line = file.ReadLine
        If InStr(line, "=") > 0 Then
            arr = Split(line, "=")
            key = arr(0)
            Value = arr(1)
            If Not Map.Exists(key) Then
                Map.Add key, Value
            End If
        End If
    Loop
    
    file.Close
    Set file = Nothing
    Set fso = Nothing
    
    Set GetMapFromIniFile = Map
    
End Function

4. 参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?