1
1

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 5 years have passed since last update.

Excelマクロで暗号を解読

Last updated at Posted at 2012-08-06

君ならどう書く Online 問題文

標準モジュールに以下のコードを追加する。
シートのとある列に入力文字列を張り付け、先頭セルを選択してマクロからDecryptプロシージャを実行する。
その結果、入力セルの右隣のセルに(4つおきに)解読された文字が現れる。

コード自体はまっとうですよ。面白みといえば、セル参照を埋め込んでいるので、Excelのワークシート上で入力文字列を変更したらそれに追従することぐらいか。リアクティブプログラミング!

Module1.BAS
Sub Decrypt()
    Set rAll = Range(ActiveCell, ActiveCell.End(xlDown))
    For i = 1 To rAll.Count Step 4
        rAll.Item(i).Offset(0, 1).FormulaR1C1 = "=GetChar(RC[-1]:R[3]C[-1])"
    Next
End Sub

Function GetChar(ByVal r As Range) As String
    If r.Count <> 4 Then
        Exit Function
    End If
    For i = 1 To 4
        a = (a * 4) + Encode(r.Item(i).Value)
    Next
    GetChar = ChrW(a)
End Function

Function Encode(ByVal str As String) As Integer
    Set regex = CreateObject("VBScript.RegExp")
    If IsMAC(str, regex) Then
        Encode = 0
    ElseIf IsIPv4(str, regex) Then
        Encode = 1
    ElseIf IsIPv6(str, regex) Then
        Encode = 2
    Else
        Encode = 3
    End If
End Function

Function IsMAC(ByVal str As String, ByVal regex As Object) As Boolean
    pt = "^[0-9a-f]{2}([:-])[0-9a-f]{2}\1[0-9a-f]{2}\1[0-9a-f]{2}\1[0-9a-f]{2}\1[0-9a-f]{2}$"
    regex.Pattern = pt
    regex.IgnoreCase = True
    IsMAC = regex.Test(str)
End Function

Function IsIPv4(ByVal str As String, ByVal regex As Object) As Boolean
    str = "." & str
    regex.Pattern = "\.(0|[1-9]\d{0,2})"
    regex.Global = True
    Set mc = regex.Execute(str)
    If mc.Count <> 4 Then
        Exit Function
    End If
    If (mc(0).Value & mc(1).Value & mc(2).Value & mc(3).Value) <> str Then
        Exit Function
    End If
    For Each m In mc
        d = CInt(Mid(m.Value, 2))
        If d < 0 Or d > 255 Then
            Exit Function
        End If
    Next
    IsIPv4 = True
End Function

Function IsIPv6(ByVal str As String, ByVal regex As Object) As Boolean
    w = "[1-9a-f][0-9a-f]{0,3}"
    cw = ":" & w
    pt = "^" & w & cw & cw & cw & cw & cw & cw & cw & "$"
    regex.Pattern = pt
    regex.IgnoreCase = True
    IsIPV6 = regex.Test(str)
End Function
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?