How to execute formal validation of TextBox on user form with EXCEL VBA?

In this article, I’d like to describe how to execute formal validation of TextBox on user form. Data type of TextBox is datetime, numeric and such string as zip code, phone number or mail address, etc. Until Excel 2003, you could divert calendar control of Access®, but after 2007, you couldn’t. You might have to type keyboard, design custom calendar or use Add-In calendar.

validation

As shown in figure above, set TextBoxes on user form, from TextBox1 to TextBox5. And set CommandButton.

Formal validation

Validation means formal validation and semantic validation. In this article, I’d like to describe about formal validation. Formal validation has verification of data type and not entered controls. You could verify not entered controls at last, it might be executed in a batch, when CommandButton for registration was clicked. However, because data type of each controls are different from each other, it might be appropriate to verify data type each time when input is entered.

Semantic validation

Although I would not describe about semantic validation in this article, it’s needed not only verifying input of one control, but also comparing input of multiple controls each other and compareing input with record in database. In the situation, it’s needed to execute validation when registration button was clicked, not to hook individual events of each controls.

Event type

Then, which event should you use? When user have entered incorrect input, you would not confirm input and would not move focus to the next control. Therefore it’s appropriate to use event with cancel. Typical event of TextBox is bellow.

  • BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
  • Change()
  • Exit(ByVal Cancel As MSForms.ReturnBoolean)
  • KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
  • KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
  • KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)

Events with cancel process are BeforeUpdate and Exit. With such other events as Change, you would have to design custom code to stop process. BeforeUpdate event is usually used.

Option Explicit

Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)

End Sub

Private Sub TextBox2_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)

End Sub

Private Sub TextBox3_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)

End Sub

Private Sub TextBox4_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)

End Sub

Private Sub TextBox5_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)

End Sub

Specified criteria for validation

It’s important that BeforeUpdate event executes cancel process when criteria you described in event procedure has been satisfied. It’s needed to deny criteria expression with Not that allows to input. When criteria has been satisfied, cancel process would be executed.

Validation of data type

Data type of each TextBoxes are datetime, numeric and string. String has mobile phone number, mail address and URL, respectively. After cancel process, following code set focus and select whole input string. In TextBox1, following code verifies whether data type of input is datetime, in textBox2, the code verifies whether data type of input is numeric, respectively. In textBox2, non-negative number would be accepted.

Validation with regular expression

After TextBox3, following code doesn’t verify data type. It’s not needed to verify data type when you deal input as string. Therefore, you would have to verify string itself. In TextBox3, it is allowed to input eleven digit number. In TextBox4, it’s allowed to input string by matching with regular expression as shown in 44 line. It’s so difficult to match e-mail address that following code is incomplete. In TextBox5, it matches with URL. As well as e-mail, it’s incomplete.

Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
    With TextBox1
        If Not IsDate(.Text) Then
            Cancel = True
            .SetFocus
            .SelStart = 0
            .SelLength = Len(.Text)
        End If
    End With
End Sub

Private Sub TextBox2_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
    With TextBox2
        If Not (IsNumeric(.Text) And .Text >= 0) Then
            Cancel = True
            .SetFocus
            .SelStart = 0
            .SelLength = Len(.Text)
        End If
    End With
End Sub

Private Sub TextBox3_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
    Dim myReg       As Object
    Set myReg = CreateObject("VBScript.RegExp")
    With myReg
        .Pattern = "^[0-9]{11}$"
        .IgnoreCase = True
        .Global = True
    End With
    With TextBox3
        If Not myReg.Test(.Text) Then
            Cancel = True
            .SetFocus
            .SelStart = 0
            .SelLength = Len(.Text)
        End If
    End With
End Sub

Private Sub TextBox4_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
    Dim myReg       As Object
    Dim Pattern     As String
    Pattern = "^[-a-z0-9]+(\.[-a-z0-9]+)*\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z0-9]{2,6}$"
    Set myReg = CreateObject("VBScript.RegExp")
    With myReg
        .Pattern = Pattern
        .IgnoreCase = True
        .Global = True
    End With
    With TextBox4
        If Not myReg.Test(.Text) Then
            Cancel = True
            .SetFocus
            .SelStart = 0
            .SelLength = Len(.Text)
        End If
    End With
End Sub

Private Sub TextBox5_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
    Dim myReg       As Object
    Dim Pattern     As String
    Set myReg = CreateObject("VBScript.RegExp")
    Pattern = "^https?://[a-z0-9][-a-z0-9]{0,62}(\.[a-z0-9][-a-z0-9]{0,62})*\.[a-z0-9][a-z0-9]{0,62}$"
    With myReg
        .Pattern = Pattern
        .IgnoreCase = True
        .Global = True
    End With
    With TextBox5
        If Not myReg.Test(.Text) Then
            Cancel = True
            .SetFocus
            .SelStart = 0
            .SelLength = Len(.Text)
        End If
    End With
End Sub

Refferences:
DOD INTERNET HOST TABLE SPECIFICATION
Requirements for Internet Hosts — Application and Support
Hostname (Wikipedia)
Userform of Excel VBA as user interface

Excel VBAでユーザーフォームのテキストボックスの値の形式的検証を行う

 ユーザーフォーム上のテキストボックスの値を検証します.テキストボックスに入力する値のデータ型としては日付型,数値型,郵便番号や電話番号・メールアドレスなどの文字列型が主体です.日付型に関しては Excel 2003 までは Access® のカレンダーコントロールを流用できたのですが,最近のバージョンではそれもできなくなりました.キーボードからタイプするか,カレンダーを自作するか,関数アドインを利用するしかありません.

validation

 上図のようにフォーム上にテキストボックスを配置します.それぞれ TextBox1, TextBox2, TextBox3, TextBox4, TextBox5 としましょう.またコマンドボタンを配置し,Caption を OK に変更します.

形式的検証

 検証には形式的検証と意味的検証とがあります.まず形式的検証についてです.未入力のチェックとデータ型のチェックが主体となります.両者のチェックのタイミングは別の方がよいでしょう.タイミングが異なるため,異なるイベントにすべきです.未入力のチェックは値が空白であるか否かだけを確認すれば良いため,一括して検証可能でしょう.となると個々のコントロールのイベントで都度チェックするのではなく,最後に登録するコマンドボタンが押された時点でよいということになります.逆にデータ型はコントロールごとに異なります.ですので個々のテキストボックスに入力が発生した時点で都度検証するのがよいでしょう.

意味的検証

 意味的検証についてここでは詳述しませんが,単独のコントロールの入力値を検証するだけでなく,複数のコントロールの入力値同士を比較して検証する必要があったり,データベースに既に登録されたレコードの値と比較したりといった検証が必要になる場合もあります.そのような場合には個々のコントロールのイベントをフックするのではなく,最後に登録するボタンが押された時点で検証するのが妥当だと思います.そういったチェックは Access® の場合ですとテーブルに対するイベントとして登録する必要があります.

イベントの種類

 話をイベントに戻します.では次にどのイベントを用いるべきでしょうか.意図しない入力が発生した場合は入力を確定させず,次のコントロールにフォーカスを移動させたくないのですから,Cancel 処理が入っているイベントが適切です.テキストボックスのイベントで代表的なものは下記のとおりです.

  • BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
  • Change()
  • Exit(ByVal Cancel As MSForms.ReturnBoolean)
  • KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
  • KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
  • KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)

 Cancel 処理を持つのは BeforeUpdate と Exit です.Change イベントを始め他のイベントでは処理を止めるために自前でコーディングする必要があるでしょう.BeforeUpdate と Exit とでいずれが適切かは個々の要件によりますが,通常は BeforeUpdate でよいでしょう.それぞれのコントロールで BeforeUpdate イベントを選択した状態は下記のようになります.

Option Explicit

Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)

End Sub

Private Sub TextBox2_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)

End Sub

Private Sub TextBox3_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)

End Sub

Private Sub TextBox4_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)

End Sub

Private Sub TextBox5_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)

End Sub

検証の条件指定

 次にデータ型をそれぞれ検証します.ここで強調したいのは,キャンセルする際の条件を満たした場合にキャンセル処理を行うコードを記述することです.その条件には,逆に入力を許可する条件式を指定しておき,最後に Not で条件式全体を否定するというちょっと複雑な処理が必要です.If … Then … ElseIf … と条件分岐を連ねていく方法もありますが,その都度キャンセル処理を書き連ねていく必要があります.ここは好みの問題かもしれませんが,ド・モルガンの法則からすると,And で条件を絞り込み,最後に Not で式全体を否定するのがスマートかと思います.そして Cancel = True としてキャンセル処理を実行します.では逆に入力を満たす条件をそのまま記述し,Cancel = False とすればどうなるでしょうか.これは宿題にしておきましょう.

データ型の検証

 さて,話を戻します.各テキストボックスのデータ型は順に日付型,数値型,電話番号・メールアドレスおよび URL の文字列型です.TextBox1 から TextBox5 までいずれもキャンセル処理後フォーカスを残し,かつ入力した値全体を選択して即座にタイプできるようにしています.TextBox2 では非負の数値のみを受け付けます.

正規表現による文字列の検証

 TextBox3 以降ではデータ型の検証をしていません.文字列型として扱う場合はデータ型を検証する必要がないからです.したがって入力された文字列そのものを検証する必要があります.TextBox3 では 11 桁の半角数値以外の入力を許可していません.TextBox4 においては正規表現を使って 44 行目のようにパターンにマッチさせる文字列を指定します.メールアドレスの正規表現によるマッチングはかなり複雑らしく,例文では不十分です.TextBox5 では URL にマッチさせます.メールアドレス同様,例文の検証法も不十分です.

Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
    With TextBox1
        If Not IsDate(.Text) Then
            Cancel = True
            .SetFocus
            .SelStart = 0
            .SelLength = Len(.Text)
        End If
    End With
End Sub

Private Sub TextBox2_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
    With TextBox2
        If Not (IsNumeric(.Text) And .Text >= 0) Then
            Cancel = True
            .SetFocus
            .SelStart = 0
            .SelLength = Len(.Text)
        End If
    End With
End Sub

Private Sub TextBox3_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
    Dim myReg       As Object
    Set myReg = CreateObject("VBScript.RegExp")
    With myReg
        .Pattern = "^[0-9]{11}$"
        .IgnoreCase = True
        .Global = True
    End With
    With TextBox3
        If Not myReg.Test(.Text) Then
            Cancel = True
            .SetFocus
            .SelStart = 0
            .SelLength = Len(.Text)
        End If
    End With
End Sub

Private Sub TextBox4_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
    Dim myReg       As Object
    Dim Pattern     As String
    Pattern = "^[-a-z0-9]+(\.[-a-z0-9]+)*\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z0-9]{2,6}$"
    Set myReg = CreateObject("VBScript.RegExp")
    With myReg
        .Pattern = Pattern
        .IgnoreCase = True
        .Global = True
    End With
    With TextBox4
        If Not myReg.Test(.Text) Then
            Cancel = True
            .SetFocus
            .SelStart = 0
            .SelLength = Len(.Text)
        End If
    End With
End Sub

Private Sub TextBox5_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
    Dim myReg       As Object
    Dim Pattern     As String
    Set myReg = CreateObject("VBScript.RegExp")
    Pattern = "^https?://[a-z0-9][-a-z0-9]{0,62}(\.[a-z0-9][-a-z0-9]{0,62})*\.[a-z0-9][a-z0-9]{0,62}$"
    With myReg
        .Pattern = Pattern
        .IgnoreCase = True
        .Global = True
    End With
    With TextBox5
        If Not myReg.Test(.Text) Then
            Cancel = True
            .SetFocus
            .SelStart = 0
            .SelLength = Len(.Text)
        End If
    End With
End Sub

参照:
サイト URL、フォルダ名、ファイル名に使用できない文字 (Microsoft®)
Active Directory 内のコンピューター、ドメイン、サイト、および Ou の名前付け規則 (Microsoft®)
ホスト名 (Wikipedia)
インターフェースとしてのEXCEL VBAによるユーザーフォーム

Userform of Excel VBA as user interface

I’d like to describe about coding of userform in EXCEL VBA as user interface of database. You could set controls for entering data, selecting from choices, and coding procedure, etc. I would be happy with your help if you could understand the characteristics of controls and design a convenient and robust system.

  1. OptionButton, CheckBox, ListBox and ComboBox as a choice
  2. TextBox
  3. CommandButton
  4. Password

1. OptionButton, CheckBox, ListBox and ComboBox as a choice

ExampleForm

1.1 Restriction which control should you select.

You might had to decide which control should you set on userform depending on the situation. First, number of choice is most important. Can you only choose one option? Or are you permitted multiple choices? Next, is there enough area to present the choices? Last, does user have to enter additional choice? Or does administrator have to define the choices?

1.2 Can you select only one? Or are you allowed to select multiple choice?

If choice was one, you could set OptionButtons in Frame or ComboBox. If you need multiple choices, you could set CheckBoxes in Frame or ListBox. I’d like to draw your attention here that multiple selection doesn’t mean unique value and doesn’t become candidate key to identify record in database. It isn’t first normal form because it is array rather than atomic value.

1.3 Enough area for setting control?

If you could have enough area on UserForm to present all choice, you would set OptionButtons or CheckBoxes in Frame. If you could not have enough area, you could set ComboBox  or ListBox. Or you would have to adjust balance each other or expand UserForm area.

1.4 Is it possible that items may increase after system has been launched?

It’s a serious problem in management of database to force users to add items. It inserts items into transaction table, that isn’t exist in master table. It violates referential integrity constraints. I think that user should not be allowed to add items with ComboBox and new items should be added to master table on the other form.

Control Multiple choice One choose Area restriction Required item added
OptionButton      
CheckBox      
ListBox
ComboBox  

2. TextBox

You can enter various data into TextBox, so it’s difficult control to master. It’s typical value list as below.

  • Last name and first name
  • Birthday
  • Gender
  • Organization, department
  • Zip code
  • Address
  • With or without of an attribute

These input values are classified as following data type:

2.1 String

Text data, for example, name of human, organization, department, zip code or address. Zip code should not be treated as numeric. Phone number should not be, so. Although these data have number, they should be treated as string and should be checked length of string or number of characters in validation.

2.2 Datetime

Date time data type, for example, birthday or entry date. Excel can treat date type after January 1, 1900. To tell the truth, Excel has bug in DATEDIFF function, it would not be so big problem for most purposes.

2.3 Numeric

Numeric required calculation such as finance or salary, measurement of experiment and physical quantity such as length or mass. For further classification, integer, decimal and currency. You would need to select appropriate decimal type depend on required accuracy.

2.4 Boolean

You would describe with boolean that you could tell with ‘yes’ or ‘no’, such as a disease status, smoking status or drinking status. But I think you should use Boolean not in TextBox but in CheckBox.

3. CommandButton

On CommandButton you could describe the procedure that is activated by click, such as selecting records from database, updating records in database, inserting records into database or deleting records from database.

  • Select record
  • Update record
  • Insert record
  • Validation
  • Delete record

3.1 Select record

To select and present records from database, you would need to specify search criteria. With such criteria as name, birthday, age or gender entered into TextBox or ListBox, searching with Auto Filter or Find method and presenting result records, you set the code on CommandButton to activate by click. ListBox might be most appropriate control, because obtained records would be more than one. It’s available to use whole match, forward match, backward match and intermediate match in search method, you could choose depend on situation. An error would occur if you couldn’t get records, so you should catch error and display alerts.

3.2 Update record

To update records in database, the data obtained by described as above have to be replicated to such controls that you can edit as TextBox, OptionButton or ListBox. You would set CommandButton to replicate data. You need to set CommandButton, code the procedure writing back the data you had fixed, that is activated by click.

3.3 Insert record

When there isn’t search result, it means that you should insert record into database. When you enter items into controls, system would be required to verify data. When entered data have passed validation, they would be allowed to be registered. If they didn’t pass validation, system should display alert to user.

3.4 Validation

There are formal and semantic validation. Formal validation verifies whether there is control without input, whether data type is appropriate. Semantic validation verifies that magnitude relation of number or context of date are appropriate. If incorrect data have been inserted into database, it’s hard to find it. It’s standard rule to validate data on user form. If you need, you could use regular expression. It’s one of the most important process in order to design robust system.

How to execute formal validation of TextBox on user form with EXCEL VBA?
How to validate empty value in controls on user form of Excel VBA?

3.5 Delete record

It may be required to remove record from database in some situation. When you operate worksheet as database, the record identified by Auto Filter or Find method should be removed by Delete method. “Delete” button should be set far from other buttons because of fail safe and when it’s clicked, system should ask user whether user really wishes to delete the record by message box.

4. Password

EnterPassword

It’s standard that system requires password when you open system as administrator. In order to enter password, you can use Input method or custom form. I’d like to recommend custom form.

Because Input method is easy to implement that Excel has already equipped function, you could trace user’s behavior with setting Variant type as return value. But it’s only and fatal defect that Input method couldn’t mask input value.

It’s true that custom form requires coding effort but it would be much more your benefit that you can mask password by modifying properties of TextBox.

How to validate password with regular expression which requires single-byte alphanumeric characters and symbols?

インターフェースとしてのEXCEL VBAによるユーザーフォーム

 Excel のユーザーフォームをデータベースのインターフェースとして使用する際の注意点などを述べます.ユーザーフォームにはデータを入力するためのコントロール,選択肢から選択させるためのコントロール,動作を記述するためのコントロールなどを配置します.それぞれの特徴を把握し,ユーザーにとって使いやすくかつ堅牢なシステムを構築する手助けとなれば幸いです.

  1. 選択肢としてのオプションボタン,チェックボックス,リストボックスおよびコンボボックス
  2. テキストボックス
  3. コマンドボタン
  4. パスワード入力

1. 選択肢としてのオプションボタン,チェックボックス,リストボックス及びコンボボックス

ExampleForm

1.1 コントロールを決める際の制約条件

 ユーザーフォーム上に選択肢を示す場合にどのコントロールを用いるかは状況に応じて決める必要があります.選択肢が一択なのか複数選択なのかが最も重要な制約条件です.次に選択肢を提示する面積が確保されているか否か,最後に選択肢をユーザー自身が追加する必要があるか否か,逆に言えば管理者が選択肢を定義しておく必要があるか否かでどのコントロールを用いるかが決まります.

1.2 選択肢は一択か複数か

 選択肢が一択である場合はオプションボタンをフレーム内に配置するか,コンボボックスを配置するかします.複数選択が必要であればチェックボックスをフレーム内に配置するか,リストボックスを配置するかします.ここで注意が必要ですが,複数選択を許可するということは値が一意に決まらないということであり,データベースのレコードを特定するためのキーの候補とはなり得ないということでもあります.もっと言えば,原子値ではなく配列ですので第一正規形を満たしません.EXCEL でそこまで考慮する必要があるかは分かりませんが,一応知っておく必要はあると思います.

1.3 配置するための面積は十分か

 選択肢を全て提示するのに必要な面積が十分に確保されていればフレーム内にオプションボタンを配置するか,チェックボックスを配置します.逆に面積が十分に確保できない場合はリストボックスまたはコンボボックスを配置します.複数選択が必要なのに十分な面積が確保できない場合は,他のコントロールとの配置のバランスを変更するか,ユーザーフォームの面積を拡張する必要があります.

1.4 選択項目は運用中に増加するか

 選択項目をユーザー自身に追加させる必要があるというのは,データベースの管理上問題があります.それはマスターテーブルにない項目をトランザクションテーブルに追加することに他ならず,参照整合性制約に違反します.少なくとも別のフォームでマスターテーブルに項目を追加する仕様とし,コンボボックスから新たに項目を追加するのを禁じた方がよいと思います.とはいえ実装ではなかなかそうも行かないのが現状です.

コントロール 複数選択 一択 面積に制約 アイテム追加必要
オプションボタン      
チェックボックス      
リストボックス
コンボボックス  

ドロップダウンリストとコンボボックス

2. テキストボックス

 テキストボックスには様々なデータを入力できます.自由であるかゆえに最も扱いの難しいコントロールでもあります.考えられる入力値として代表的なものは以下の様なものではないでしょうか.

  • 人名
  • 生年月日
  • 性別
  • 組織名・部署名
  • 郵便番号
  • 住所
  • ある属性の有無

 これらの入力値はデータ型として以下のように分類できます.

2.1 文字列型

 人名,組織名・部署名,郵便番号,住所などのテキストデータ.郵便番号を数値型に含めるのは間違いです.先頭に 0 があった場合,数値型では削られてしまいます.同様に電話番号も数値型としてはいけません.これらは数値を使ってはいますが,文字列型として扱うべきであり,また文字数が決まっているため入力値のチェックの際には必ず文字数をチェックすべきです.

2.2 日付型

 生年月日や入社年月日などの日付のデータ.Excel では 1900 年 1 月 1 日以降の日付型を扱えます.DATEDIFF 関数などに多少のバグはあるのですが,通常の使用で問題になることはあまりないでしょう.

2.3 数値型

 数値型として扱うのは給与や財務など計算の必要なデータ,実験の測定値,長さや質量などの物理量などです.さらに細かく分類すると整数型や小数型,通貨型などいろいろあります.特に小数型は必要な精度に応じて適切なデータ型を選択する必要があります.

2.4 ブール型

 ある疾病の有無や既往の有無,喫煙や飲酒の有無など Yes か No で答えられるものについてはブール型で記述します.しかしブール型はテキストボックスよりもチェックボックスで使用した方が良いように思います.

3. コマンドボタン

 コマンドボタンにはクリックイベントにより意図する動作をプロシージャとして記述します.意図する動作とはデータベースからレコードを検索して表示すること,データベースに存在するレコードを修正すること,データベースにないレコードを新規に登録すること,データベースのレコードを削除することです.それぞれ SELECT, UPDATE, INSERT, DELETE に該当します.

  • レコードを検索する
  • レコードを修正する
  • レコードを登録する
  • 入力値のチェック
  • レコードを削除する

3.1 レコードを検索する

 データベースに存在するレコードを検索して表示するには検索条件を指定する必要があります.名前,生年月日,年齢,性別など検索に必要な条件をテキストボックスなりリストボックスなりに入力させ,オートフィルターや Find メソッドを使用して検索し,得られた結果を表示するコードを記述し,コマンドボタンのクリックイベントに登録します.結果を表示するコントロールはリストボックスが良いでしょう.おそらく複数の結果が得られる筈ですから.検索方法には全文一致,前方一致,後方一致,中間一致があり,状況に応じて選択します.結果が得られない場合はエラーが発生するため,エラーをキャッチして適切なアラートを表示させたほうが良いでしょう.

3.2 レコードを修正する

 データベースに存在するレコードを修正するには,前述の方法で得られたレコードをテキストボックスやオプションボタン,リストボックスなど編集可能なコントロールに移す必要があります.そのためのコマンドボタンを用意したほうが良いでしょう.必要な項目を訂正したらレコードをデータベースに書き戻す処理が必要になります.修正ボタンを配置し,コードを記述してクリックイベントに登録します.

3.3 レコードを登録する

 検索結果が存在しない場合とは,レコードを新規に登録する必要があるということです.ID, 名前など所定の項目をコントロールに入力させ,データベースに登録するコードを記述しますが,この際様々なチェックが必要になります.そのチェックに合格した場合にのみレコードを登録するコードを記述し,登録ボタンのクリックイベントに登録します.チェックに引っかかった部分をユーザーにフィードバックする機能があれば尚親切かもしれません.

3.4 入力値のチェック

 チェックの具体的な内容として,入力漏れがないか,適切なデータ型かなどの形式的なチェックと,さらに日付の前後関係や数値の大小関係といったセマンティックな要素も可能な限りチェックを行います.一旦誤ったデータがデータベースに登録されると簡単には見つけられません.ユーザーフォーム上で入力値のチェックを行うのが鉄則です.必要なら正規表現を使用して下さい.この部分の作り込みが使いやすいシステムになるか否かの分岐点になります.よく考えてコーディングして下さい.よくあるのが計算の必要な項目に全角数字を入力してしまったというものです.テキストボックスに半角数値のみの入力を受け付けるよう指定し,さらに入力モードを半角英数字に指定しておくなどの措置をプログラム上で行なっておけば済んだ話です.

Excel VBAでユーザーフォームのテキストボックスの値の形式的検証を行う
EXCEL VBA でユーザーフォーム上のコントロールの未入力を検証する

3.5 レコードを削除する

 データベースからレコードを削除する必要がある場合もあります.Excel のワークシートをデータベースにしている場合はフィルターを使ってレコードを指定し,Delete メソッドを使用して削除するコードをコマンドボタンに記述するのがよいでしょう.先述のレコードを検索して表示されたリストボックスから削除するレコードを選択させるのが安全な方法でしょう.削除ボタンは他のボタンと距離を離し,押し間違いを防ぐために一旦メッセージボックスで確認をとるなどの安全策を講じたほうが良いでしょう.

4. パスワード入力

EnterPassword

 メンテナンスのために管理者としてアプリケーションを開く必要がある場合,パスワードを要求するのが普通です.パスワードの入力には Input メソッドを使用する方法とパスワード入力用のユーザーフォームを自作する方法があります.それぞれメリットとデメリットがありますが,個人的には自作する方をお勧めします.

 Input メソッドは Excel で既に用意された機能ですので実装が容易です.戻り値に Variant 型を指定しておけばユーザーの行動を完全に把握出来ます.しかし唯一かつ致命的な欠点は入力値をマスクできないことです.この点で自作フォームをお勧めします.

 自作フォームではコーディングの手間がかかるデメリットがありますが,入力値をマスクできるメリットのほうが大きいと思います.ユーザーフォームにテキストボックスとコマンドボタンを配置し,テキストボックスのプロパティを設定するだけで入力値をマスク出来ます.

VBScriptの正規表現でパスワードに半角英数字と半角記号が使用されているか検証する

How to add direction into Excel custom lists?

When you’d like to sort with direction, you could not sort because Excel dose not have ‘Direction’ list. So in this article, I’d like to add ‘Direction’ into custom list. First, enter 16 direction from ‘North’ to ‘North-northwest’.

Custom list of direction
16 direction from North to North-northwest.

Next, select ‘File’ tab, ‘option’ and ‘Advanced settings’. After scroll down, press ‘Edit custom lists…’ button.

Edit custom list.
Edit custom list.

Click button on the right column of ‘Range of source list’.

Press button to select range.
Press button to select range.

Drag to select the range you entered ago, press button. Cell range would be entered into the column. Press ‘Import’ button.

Press "Import" button.
Press “Import” button.

OK, ‘Direction’ list has been added to custom lists. Press ‘OK’ to close window.

Custom list has been imported.
Custom list has been imported.

Excel2010のユーザー設定リストに方角を追加する

 Excel のソートの規定のリストには方角がありません.そこで方角のユーザー設定リストを追加します.新規にブックを開き,下図のように 16 の方角を入力しておきます.

Custom list of direction
16 direction from North to North-northwest.

 次に『ファイル』タブの『オプション』から『詳細設定』を選択します.スクロールしていくと下の方に『ユーザー設定リストの編集…』のボタンがあるのでクリックします.

Edit custom list.
Edit custom list.

 ユーザー設定リストパネルが開きます.『追加』ボタンを押して手入力することも可能ですが,先ほど入力しておいたリストを取り込むことにします.『リストの取込元範囲』にあるセル範囲指定ボタンをクリックします.

Press button to select range.
Press button to select range.

 先ほど入力したセル範囲をドラッグして選択し,ボタンをクリックすると『リストの取り込み範囲』にセル範囲が入力されます.『インポート』ボタンをクリックします.

Press "Import" button.
Press “Import” button.

 新たに方角リストが追加されました.『OK』をクリックして設定画面を抜けます.

Custom list has been imported.
Custom list has been imported.

How to export Excel worksheets to database with SQL statement file.

When you’d like to register Excel worksheets in database, you could ‘BULK INSERT’ txt file into database. In this article, I’d like to explain VBA code that exports Excel worksheets to sql file. It’s assumed that worksheet name is same as table name and first column order is same as table attribute order.

Option Explicit

Sub EXPORT_SQL()
    Dim mySht   As Worksheet
    Dim myAr    As Variant
    Dim i       As Long
    Dim j       As Long
    Dim mySQL   As String
    Dim SQLAr() As String
    Dim myFSO   As Object
    Dim myTS    As Object
    Dim myPath  As String
    Dim n       As Long
    myPath = ThisWorkbook.Path
    For Each mySht In Worksheets
        myAr = mySht.UsedRange.Resize(mySht.UsedRange.Rows.Count - 1).Offset(1)
        ReDim SQLAr(LBound(myAr) To UBound(myAr))
        For i = LBound(myAr) To UBound(myAr)
            For j = LBound(myAr, 2) To UBound(myAr, 2)
                If myAr(i, j) = Empty Then
                    mySQL = mySQL & "NULL, "
                Else
                    mySQL = mySQL & "'" & myAr(i, j) & "', "
                End If
            Next j
            mySQL = "INSERT INTO " & mySht.Name & " VALUES (" & Left(mySQL, Len(mySQL) - 2) & ")"
            SQLAr(i) = mySQL
            mySQL = ""
        Next i
        Set myFSO = CreateObject("Scripting.FileSystemObject")
        Set myTS = myFSO.CreateTextFile(Filename:=myPath & "\" & mySht.Name & ".sql", Overwrite:=True)
        For n = LBound(SQLAr) To UBound(SQLAr)
            myTS.writeline SQLAr(n)
        Next n
        myTS.Close
        Set myFSO = Nothing
        Set myTS = Nothing
    Next mySht
End Sub

EXCELのワークシートをテーブルに挿入するSQLステートメントファイルを作成するVBAコード

 Excel のワークシートをデータベースに登録するにはいくつかの方法があります.txt ファイルを BULK INSERT する方法もありますが,今回はワークシートのセル内容を INSERT するクエリを sql ファイルに書き出す VBA コードを説明します.ワークシート名はテーブル名と同じになっており,ワークシートの1行目はテーブルの属性名と同一の順番になっているとの前提で話を進めます.Excel のファイルと同一場所に sql ファイルがシートの数だけ作成されます.

Option Explicit

Sub EXPORT_SQL()
    Dim mySht   As Worksheet
    Dim myAr    As Variant
    Dim i       As Long
    Dim j       As Long
    Dim mySQL   As String
    Dim SQLAr() As String
    Dim myFSO   As Object
    Dim myTS    As Object
    Dim myPath  As String
    Dim n       As Long
    myPath = ThisWorkbook.Path
    For Each mySht In Worksheets
        myAr = mySht.UsedRange.Resize(mySht.UsedRange.Rows.Count - 1).Offset(1)
        ReDim SQLAr(LBound(myAr) To UBound(myAr))
        For i = LBound(myAr) To UBound(myAr)
            For j = LBound(myAr, 2) To UBound(myAr, 2)
                If myAr(i, j) = Empty Then
                    mySQL = mySQL & "NULL, "
                Else
                    mySQL = mySQL & "'" & myAr(i, j) & "', "
                End If
            Next j
            mySQL = "INSERT INTO " & mySht.Name & " VALUES (" & Left(mySQL, Len(mySQL) - 2) & ")"
            SQLAr(i) = mySQL
            mySQL = ""
        Next i
        Set myFSO = CreateObject("Scripting.FileSystemObject")
        Set myTS = myFSO.CreateTextFile(Filename:=myPath & "\" & mySht.Name & ".sql", Overwrite:=True)
        For n = LBound(SQLAr) To UBound(SQLAr)
            myTS.writeline SQLAr(n)
        Next n
        myTS.Close
        Set myFSO = Nothing
        Set myTS = Nothing
    Next mySht
End Sub

The text file revised edition of “METs table of Physical Activities”

I have asked National Institute of Health and Nutrition if I could publish the text file revised edition of “METs table of Physical Activities” on this blog on July 3rd, 2012. I have received e-mail from staff on July 12, 2012, they consent that I publish the text file.

The file has 4 columns and 826 rows. First row shows data structure. First column shows code, second column METS value, third column major heading, and fourth column specific activities. I couldn’t separate English from Japanese.

METS2011

The source is this PDF file. Although you don’t have to contact National Institute of Health and Nutrition when you would like to use for yourself, you would be asked to contact National Institute of Health and Nutrition when you would like to publish the file or create a web service with the file.

改訂版『身体活動のメッツ表』のテキストファイル

2012年7月3日の記事で国立健康・栄養研究所に『身体活動メッツ表』から抽出したテキストファイルを公開して良いか問い合わせていましたが,7月12日回答があり,公開を許可して頂けましたので公開いたします.

下記ファイルのデータ構造は4列826行となっています.1行目はデータ構造を示しており,2行目以降がデータです.1列目はコード,2列目はMETs,3列目は大分類,4列目は個別活動となっています.日本語と英語の切り分けはできていません.

METS2011

当ファイルは国立健康・栄養研究所の改訂版『身体活動メッツ表』を元に 作成したものです.個人利用においては特に連絡の必要はございませんが,ウェブサービス等,第三者が利用するサービスに当ファイルを使用する場合には国立健康・栄養研究所に確認のご連絡をお願いします.

 2014 年 11 月 7 日,指摘を受け METS2011.csv ファイルを訂正しました.



Extract from text revised edition of “METs table of Physical Activities”

National Institute of Health and Nutrition has revised ‘METs table of Physical Activities’ 2011 edition. Because it’s difficult to use as PDF file, I have extracted text data from it. I have asked if I could publish the file on this blog on July 3rd, 2012.

1. Open the file and copy all text.

2. Create new EXCEL book and paste with ‘Text File Wizard’. In the second tab, you have to remove all check mark of delimiters. In the third tab, select ‘String’ data type of column.

3. Press ‘Alt’ key and ‘F11’ key to launch VBE, insert module, and run the following code.

Option Explicit
Sub METS()
Dim mySht   As Worksheet
Dim myRng   As Range
Dim myAr    As Variant
Dim i       As Long
Dim j       As Long
Dim myReg   As Object
Dim myMatches   As Object
Dim myMatch     As Object
Const strReg    As String = "^[0-9]{5}$"
Dim CODE()  As String
Dim METS()  As Single
Dim MajorHeading()  As String
Dim SpecificActivities()    As String
Dim myArray()   As Variant
Set myReg = CreateObject("VBScript.RegExp")
With myReg
    .Pattern = strReg
    .IgnoreCase = True
    .Global = True
End With

Set mySht = ActiveSheet
Set myRng = mySht.UsedRange
myAr = myRng
j = 0
For i = LBound(myAr) To UBound(myAr)
    If myReg.Test(myAr(i, 1)) Then
        Set myMatches = myReg.Execute(myAr(i, 1))
        ReDim Preserve CODE(j)
        ReDim Preserve METS(j)
        ReDim Preserve MajorHeading(j)
        ReDim Preserve SpecificActivities(j)
        CODE(j) = myAr(i, 1)
        METS(j) = myAr(i + 1, 1)
        MajorHeading(j) = myAr(i + 2, 1)
        SpecificActivities(j) = myAr(i + 3, 1)
        j = j + 1
    End If
Next i
ReDim myArray(j, 3)
For j = LBound(myArray) To UBound(myArray) - 1
    myArray(j, 0) = CODE(j)
    myArray(j, 1) = METS(j)
    myArray(j, 2) = MajorHeading(j)
    myArray(j, 3) = SpecificActivities(j)
Next j
Set mySht = Worksheets.Add
mySht.Range("A1").Value = "CODE"
mySht.Range("B1").Value = "METS"
mySht.Range("C1").Value = "MajorHeading"
mySht.Range("D1").Value = "SpecificActivities"
mySht.Range("A2:D827") = myArray
End Sub

改訂版『身体活動のメッツ表』からテキストを抽出する



 国立健康・栄養研究所が2011年版『身体活動のメッツ表』を改訂しました.下記リンクはPDFファイルですが,そのままでは使いにくいためEXCELでテキスト情報を抽出しました.2012年7月3日,国立健康・栄養研究所に抽出したテキストファイルを公開して良いか問い合わせました.

身体活動のメッツ表



1. PDFファイルを開き,全てを選択してコピーします.

2. EXCELの新規ブックを作成し,テキストファイルウィザードを使用して貼り付けます.この際,テキストファイルウィザードの2番目のタブで区切り文字の全てのチェックを外して下さい.3番目のタブでは列のデータ形式を『文字列』に変更して下さい.

3. ‘Alt’ キーと ‘F11’ キーを押下して VBE を起動し,標準モジュールを挿入して下記コードを実行して下さい.

Option Explicit
Sub METS()
Dim mySht   As Worksheet
Dim myRng   As Range
Dim myAr    As Variant
Dim i       As Long
Dim j       As Long
Dim myReg   As Object
Dim myMatches   As Object
Dim myMatch     As Object
Const strReg    As String = "^[0-9]{5}$"
Dim CODE()  As String
Dim METS()  As Single
Dim MajorHeading()  As String
Dim SpecificActivities()    As String
Dim myArray()   As Variant
Set myReg = CreateObject("VBScript.RegExp")
With myReg
    .Pattern = strReg
    .IgnoreCase = True
    .Global = True
End With

Set mySht = ActiveSheet
Set myRng = mySht.UsedRange
myAr = myRng
j = 0
For i = LBound(myAr) To UBound(myAr)
    If myReg.Test(myAr(i, 1)) Then
        Set myMatches = myReg.Execute(myAr(i, 1))
        ReDim Preserve CODE(j)
        ReDim Preserve METS(j)
        ReDim Preserve MajorHeading(j)
        ReDim Preserve SpecificActivities(j)
        CODE(j) = myAr(i, 1)
        METS(j) = myAr(i + 1, 1)
        MajorHeading(j) = myAr(i + 2, 1)
        SpecificActivities(j) = myAr(i + 3, 1)
        j = j + 1
    End If
Next i
ReDim myArray(j, 3)
For j = LBound(myArray) To UBound(myArray) - 1
    myArray(j, 0) = CODE(j)
    myArray(j, 1) = METS(j)
    myArray(j, 2) = MajorHeading(j)
    myArray(j, 3) = SpecificActivities(j)
Next j
Set mySht = Worksheets.Add
mySht.Range("A1").Value = "CODE"
mySht.Range("B1").Value = "METS"
mySht.Range("C1").Value = "MajorHeading"
mySht.Range("D1").Value = "SpecificActivities"
mySht.Range("A2:D827") = myArray
End Sub

Classify the Item_Number of the ‘Standard Tables of Food Composition in Japan 2010′, Part 2

According to the article, download the PDF files ‘1299012_1.pdf’ to ‘1299012_18.pdf’. Corresponding to each PDF file in PDF files, copy all text from one file and option paste to one worksheet. As a result, you would make 18 worksheets in a book. In the first tab of ‘Text File Wizard’, select option ‘The data field separated by delimiters such as comma or tab’. Go to the last tab without any change in second tab. In the last tab, change option data type of the first column to ‘String’. Mainly in column A of all worksheets, you have to fix cell value by yourself. Save the book as ‘Category.xlsm’. Furthermore, download the EXCEL book from this site, copy worksheet from it to ‘Category.xlsm’ which you previously prepared, and change the sheet name to ‘Sheet0’.

Copy or move the worksheet, which you made at Classify the Item_Number of the ‘Standard Tables of Food Composition in Japan 2010′, Part 1, to ‘Category.xlsm’. As a result, ‘Category.xlsm’ book has 20 worksheets. Press ‘Alt’ key and ‘F11’ key to launch VBE, insert module and run the code below. The code makes ‘M_CATEGORY’ sheet.

Option Explicit
Sub Select_Class()
Dim tmpSht              As Worksheet
Dim tmpRng              As Range
Dim tmpArray            As Variant
Dim workArray           As Variant
Dim h                   As Long
Dim i                   As Long
Dim j                   As Long
Dim k                   As Long
Dim l                   As Long
Dim m                   As Long
Dim n                   As Long
Dim p                   As Long
Dim q                   As Long
Dim r                   As Long
Dim RegExp_Japanese     As Object
Dim RegExp_English      As Object
Dim RegExp_ItemNum      As Object
Const PtnJPN            As String = "[^A-Za-z0-9'\.\-\*]{2,}"
Const PtnENG            As String = "^[A-Za-z0-9'\,\.\-\%]+$"
Const PtnItemNum        As String = "^[0-9]{5}$"
Dim Item_Number()       As String
Dim JapaneseItem()      As String
Dim EnglishItem()       As String
Dim EnglishString       As String
Dim JapaneseClass()     As String
Dim English_Class()     As String
Dim ClassStringEN       As String
Dim ItemNumArray()      As String
Dim ItemENGArray()      As String
Dim ClassArrayJP()      As String
Dim ClassArrayEN()      As String
Dim RegExp_AngleBracket As Object
Dim RegExp_RoundStartJP As Object
Dim RegExp_RoundStartEN As Object
Dim RegExp_RoundExitEN  As Object
Const Ptn_Round_Start   As String = "^(\(|()"
Const Ptn_Round_Exit    As String = "(\)|))$"
Dim StringRoundEnglish  As String
Dim SubClassJapanese()  As String
Dim SubClass_English()  As String
Dim RegExp_Square_Start As Object
Dim RegExp_SquareExitEN As Object
Const Ptn_Angle_Start   As String = "^[<<]"
Const Ptn_SquareStart   As String = "^\["
Const Ptn_Square_Exit   As String = "\]$"
Dim MidleClassJP()      As String
Dim MidleClassEN()      As String
Dim StrMidClassENG      As String
Dim SubClass_JPN()      As String
Dim SubClass_ENG()      As String
Dim mySht               As Worksheet
Dim myRng               As Range
Dim myAr                As Variant
Dim workArray2()        As String
Dim workArray3()        As String
Dim mySht2              As Worksheet
Dim myRng2              As Range
Dim myAr2               As Variant
Dim CEREALS             As Long
Dim POTATOES            As Long
Dim SUGARS              As Long
Dim PULSES              As Long
Dim NUTS                As Long
Dim VEGETABLES          As Long
Dim FRUITS              As Long
Dim MUSHROOMS           As Long
Dim ALGAE               As Long
Dim FISHES              As Long
Dim MEATS               As Long
Dim EGGS                As Long
Dim MILK                As Long
Dim OIL                 As Long
Dim CONFECTIONERIES     As Long
Dim BEVERAGES           As Long
Dim SEASONINGS          As Long
Dim PREPARED            As Long
    Set RegExp_Japanese = CreateObject("VBScript.RegExp")
    With RegExp_Japanese
        .Pattern = PtnJPN
        .IgnoreCase = True
        .Global = True
    End With
    Set RegExp_English = CreateObject("VBScript.RegExp")
    With RegExp_English
        .Pattern = PtnENG
        .IgnoreCase = True
        .Global = True
    End With
    Set RegExp_ItemNum = CreateObject("VBScript.RegExp")
    With RegExp_ItemNum
        .Pattern = PtnItemNum
        .IgnoreCase = True
        .Global = True
    End With
    Set RegExp_Square_Start = CreateObject("VBScript.RegExp")
    With RegExp_Square_Start
        .Pattern = Ptn_SquareStart
        .IgnoreCase = True
        .Global = True
    End With
    Set RegExp_SquareExitEN = CreateObject("VBScript.RegExp")
    With RegExp_SquareExitEN
        .Pattern = "[A-Za-z0-9'\,\.\-\%]+" & Ptn_Square_Exit
        .IgnoreCase = True
        .Global = True
    End With
    Set RegExp_RoundStartJP = CreateObject("VBScript.RegExp")
    With RegExp_RoundStartJP
        .Pattern = Ptn_Round_Start & "[^A-Za-z0-9'\.\-\*]{2,}"
        .IgnoreCase = True
        .Global = True
    End With
    Set RegExp_RoundStartEN = CreateObject("VBScript.RegExp")
    With RegExp_RoundStartEN
        .Pattern = Ptn_Round_Start & "[A-Za-z'\,\.\-\%]+"
    End With
    Set RegExp_RoundExitEN = CreateObject("VBScript.RegExp")
    With RegExp_RoundExitEN
        .Pattern = "[A-Za-z0-9'\,\.\-\%]+" & Ptn_Round_Exit
        .IgnoreCase = True
        .Global = True
    End With
j = 0
k = 0
l = 0
m = 0
q = 0
For Each tmpSht In Worksheets
    If tmpSht.Name = "M_CATEGORY" Then
        MsgBox prompt:="This book already has M_CATEGORY sheet." & vbCrLf & _
                       "Exit procedure.", _
              Buttons:=vbOKOnly, _
                Title:="Internal Error"
        Exit Sub
    End If
    If tmpSht.Name <> "Sheet0" And _
       tmpSht.Name <> "Sheet00" And _
       tmpSht.Name <> "Result" Then
        Set tmpRng = tmpSht.UsedRange
        tmpArray = tmpRng
        workArray = NoCancelArray(tmpArray)
        For h = LBound(workArray) To UBound(workArray)
            For i = workArray(h, 0) To workArray(h, 1)
                On Error Resume Next
                If RegExp_ItemNum.Test(tmpArray(i, 1)) And _
                   tmpArray(i, 2) <> "(欠番)" Then
                    EnglishString = ""
                    ReDim Preserve Item_Number(j)
                    ReDim Preserve JapaneseItem(j)
                    ReDim Preserve EnglishItem(j)
                    For p = 1 To 6
                        If RegExp_English.Test(tmpArray(i + 1, p)) Then
                            EnglishString = EnglishString & " " & tmpArray(i + 1, p)
                            EnglishString = Trim(EnglishString)
                        Else
                            Exit For
                        End If
                    Next p
                    Item_Number(j) = tmpArray(i, 1)
                    JapaneseItem(j) = tmpArray(i, 2)
                    EnglishItem(j) = EnglishString
                    j = j + 1
                End If
                On Error GoTo 0
                If RegExp_Japanese.Test(tmpArray(i, 1)) And _
                   RegExp_English.Test(tmpArray(i + 1, 1)) Then
                    ClassStringEN = ""
                    ReDim Preserve JapaneseClass(k)
                    ReDim Preserve English_Class(k)
                    For p = 1 To 6
                        If RegExp_English.Test(tmpArray(i + 1, p)) Then
                            ClassStringEN = ClassStringEN & " " & tmpArray(i + 1, p)
                            ClassStringEN = Trim(ClassStringEN)
                        Else
                            Exit For
                        End If
                    Next p
                    JapaneseClass(k) = tmpArray(i, 1)
                    English_Class(k) = ClassStringEN
                    k = k + 1
                End If
                If RegExp_Square_Start.Test(tmpArray(i, 1)) And _
                   RegExp_Square_Start.Test(tmpArray(i + 1, 1)) Then
                    StrMidClassENG = ""
                    ReDim Preserve MidleClassJP(l)
                    ReDim Preserve MidleClassEN(l)
                    For p = 1 To 6
                        StrMidClassENG = StrMidClassENG + " " + tmpArray(i + 1, p)
                        StrMidClassENG = Trim(StrMidClassENG)
                        If RegExp_SquareExitEN.Test(tmpArray(i + 1, p)) Then Exit For
                    Next p
                    MidleClassJP(l) = tmpArray(i, 1)
                    MidleClassEN(l) = StrMidClassENG
                    l = l + 1
                End If
                If RegExp_RoundStartJP.Test(tmpArray(i, 1)) And _
                   RegExp_RoundStartEN.Test(tmpArray(i + 1, 1)) Then
                    StringRoundEnglish = ""
                    ReDim Preserve SubClassJapanese(m)
                    ReDim Preserve SubClass_English(m)
                    For p = 1 To 6
                        StringRoundEnglish = StringRoundEnglish & " " & tmpArray(i + 1, p)
                        StringRoundEnglish = Trim(StringRoundEnglish)
                        If RegExp_RoundExitEN.Test(tmpArray(i + 1, p)) Then Exit For
                    Next p
                    tmpArray(i, 1) = Replace(tmpArray(i, 1), "(", "(")
                    tmpArray(i, 1) = Replace(tmpArray(i, 1), ")", ")")
                    SubClassJapanese(m) = tmpArray(i, 1)
                    StringRoundEnglish = Replace(StringRoundEnglish, "(", "(")
                    StringRoundEnglish = Replace(StringRoundEnglish, ")", ")")
                    SubClass_English(m) = StringRoundEnglish
                    m = m + 1
                End If
            Next i
        Next h
        q = q + 1
    End If
Next tmpSht
Set mySht = Worksheets("Sheet0")
Set myRng = Intersect(mySht.Range("A:H"), mySht.UsedRange)
myAr = myRng
ReDim workArray2(UBound(myAr) - 1, 16)
For i = LBound(workArray2) To UBound(workArray2)
    workArray2(i, 0) = myAr(i + 1, 1)
    workArray2(i, 1) = myAr(i + 1, 2)
    workArray2(i, 2) = myAr(i + 1, 3)
    myAr(i + 1, 4) = Replace(myAr(i + 1, 4), "(", "(")
    myAr(i + 1, 4) = Replace(myAr(i + 1, 4), ")", ")")
    workArray2(i, 6) = myAr(i + 1, 4)
    workArray2(i, 8) = myAr(i + 1, 5)
    workArray2(i, 10) = myAr(i + 1, 6)
    workArray2(i, 12) = myAr(i + 1, 7)
    workArray2(i, 14) = myAr(i + 1, 8)
Next i
Set mySht2 = Worksheets("Result")
Set myRng2 = mySht2.UsedRange
myAr2 = myRng2
For i = LBound(workArray2) To UBound(workArray2)
    For k = LBound(JapaneseClass) To UBound(JapaneseClass)
        If workArray2(i, 2) = JapaneseClass(k) Then
           workArray2(i, 3) = English_Class(k)
        End If
        If workArray2(i, 4) = JapaneseClass(k) Then
           workArray2(i, 5) = English_Class(k)
        End If
        If workArray2(i, 8) = JapaneseClass(k) Then
           workArray2(i, 9) = English_Class(k)
        End If
        If workArray2(i, 12) = JapaneseClass(k) Then
           workArray2(i, 13) = English_Class(k)
        End If
    Next k
    For m = LBound(SubClassJapanese) To UBound(SubClassJapanese)
        If workArray2(i, 6) = SubClassJapanese(m) Then
           workArray2(i, 7) = SubClass_English(m)
        End If
    Next m
    For l = UBound(MidleClassJP) To LBound(MidleClassJP) Step -1
        If workArray2(i, 10) = MidleClassJP(l) Then
           workArray2(i, 11) = MidleClassEN(l)
        End If
    Next l
    For r = LBound(myAr2) To UBound(myAr2)
        If workArray2(i, 0) = myAr2(r, 1) Then
            workArray2(i, 4) = myAr2(r, 5)
            On Error Resume Next
            Select Case True
            Case workArray2(i, 0) >= "10001" And workArray2(i, 0) <= "10278"
                 workArray2(i, 4) = "<魚類>"
            Case workArray2(i, 0) >= "10319" And workArray2(i, 0) <= "10341"
                 workArray2(i, 4) = "<えび・かに類>"
            Case workArray2(i, 0) >= "10342" And workArray2(i, 0) <= "10362"
                 workArray2(i, 4) = "<いか・たこ類>"
            Case workArray2(i, 0) >= "10376" And workArray2(i, 0) <= "10388"
                 workArray2(i, 4) = "<水産練り製品>"
            Case workArray2(i, 0) >= "11205" And workArray2(i, 0) <= "11240"
                 workArray2(i, 4) = "<鳥肉類>"
            Case workArray2(i, 0) >= "11245" And workArray2(i, 0) <= "11246"
                 workArray2(i, 4) = "<獣肉類>"
            Case workArray2(i, 0) >= "11247" And workArray2(i, 0) <= "11247"
                 workArray2(i, 4) = "<鳥肉類>"
            Case workArray2(i, 0) >= "13001" And workArray2(i, 0) <= "13050"
                 workArray2(i, 4) = "<牛乳及び乳製品>"
            Case workArray2(i, 0) >= "15001" And workArray2(i, 0) <= "15040"
                 workArray2(i, 4) = "<和生菓子・和半生菓子類>"
            Case workArray2(i, 0) >= "15041" And workArray2(i, 0) <= "15068"
                 workArray2(i, 4) = "<和干菓子類>"
            Case workArray2(i, 0) >= "15069" And workArray2(i, 0) <= "15072"
                 workArray2(i, 4) = "<菓子パン類>"
            Case workArray2(i, 0) >= "15073" And workArray2(i, 0) <= "15085"
                 workArray2(i, 4) = "<ケーキ・ペストリー類>"
            Case workArray2(i, 0) >= "15086" And workArray2(i, 0) <= "15091"
                 workArray2(i, 4) = "<デザート菓子類>"
            Case workArray2(i, 0) >= "15092" And workArray2(i, 0) <= "15100"
                 workArray2(i, 4) = "<ビスケット類>"
            Case workArray2(i, 0) >= "15101" And workArray2(i, 0) <= "15104"
                 workArray2(i, 4) = "<スナック類>"
            Case workArray2(i, 0) >= "15105" And workArray2(i, 0) <= "15113"
                 workArray2(i, 4) = "<キャンデー類>"
            Case workArray2(i, 0) >= "15114" And workArray2(i, 0) <= "15116"
                 workArray2(i, 4) = "<チョコレート類>"
            Case workArray2(i, 0) >= "15117" And workArray2(i, 0) <= "15117"
                 workArray2(i, 4) = "<果実菓子類>"
            Case workArray2(i, 0) >= "15118" And workArray2(i, 0) <= "15120"
                 workArray2(i, 4) = "<チューインガム類>"
            Case workArray2(i, 0) >= "16001" And workArray2(i, 0) <= "16032"
                 workArray2(i, 4) = "<アルコール飲料類>"
            Case workArray2(i, 0) >= "16033" And workArray2(i, 0) <= "16044"
                 workArray2(i, 4) = "<茶類>"
            Case workArray2(i, 0) >= "16045" And workArray2(i, 0) <= "16049"
                 workArray2(i, 4) = "<コーヒー・ココア類>"
            Case workArray2(i, 0) >= "16050" And workArray2(i, 0) <= "16055"
                 workArray2(i, 4) = "<その他>"
            Case workArray2(i, 0) >= "17001" And workArray2(i, 0) <= "17054"
                 workArray2(i, 4) = "<調味料類>"
            Case workArray2(i, 0) >= "17055" And workArray2(i, 0) <= "17081"
                 workArray2(i, 4) = "<香辛料類>"
            Case workArray2(i, 0) >= "17082" And workArray2(i, 0) <= "17084"
                 workArray2(i, 4) = "<その他>"
            End Select
            On Error GoTo 0
            workArray2(i, 5) = myAr2(r, 6)
            On Error Resume Next
            Select Case True
            Case workArray2(i, 0) >= "10001" And workArray2(i, 0) <= "10278"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "10319" And workArray2(i, 0) <= "10341"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "10342" And workArray2(i, 0) <= "10362"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "10376" And workArray2(i, 0) <= "10388"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "11205" And workArray2(i, 0) <= "11240"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "11245" And workArray2(i, 0) <= "11246"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "11247" And workArray2(i, 0) <= "11247"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "13001" And workArray2(i, 0) <= "13050"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15001" And workArray2(i, 0) <= "15040"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15041" And workArray2(i, 0) <= "15068"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15069" And workArray2(i, 0) <= "15072"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15073" And workArray2(i, 0) <= "15085"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15086" And workArray2(i, 0) <= "15091"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15092" And workArray2(i, 0) <= "15100"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15101" And workArray2(i, 0) <= "15104"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15105" And workArray2(i, 0) <= "15113"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15114" And workArray2(i, 0) <= "15116"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15117" And workArray2(i, 0) <= "15117"
                 workArray2(i, 5) = "<CANDIED FRUITS>"
            Case workArray2(i, 0) >= "15118" And workArray2(i, 0) <= "15120"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "16001" And workArray2(i, 0) <= "16032"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "16033" And workArray2(i, 0) <= "16044"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "16045" And workArray2(i, 0) <= "16049"
                 workArray2(i, 5) = "COFFEES AND COCOAS>"
            Case workArray2(i, 0) >= "16050" And workArray2(i, 0) <= "16055"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "17001" And workArray2(i, 0) <= "17054"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "17055" And workArray2(i, 0) <= "17081"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "17082" And workArray2(i, 0) <= "17084"
                 workArray2(i, 5) = ""
            End Select
            On Error GoTo 0
            If workArray2(i, 6) <> "" And _
               workArray2(i, 7) = "" Then
                workArray2(i, 7) = myAr2(r, 8)
            End If
            If workArray2(i, 8) <> "" And _
               workArray2(i, 9) = "" Then
                If myAr2(r, 10) = "" Then
                    workArray2(i, 9) = myAr2(r, 15)
                Else
                    workArray2(i, 9) = myAr2(r, 10)
                End If
            End If
            If workArray2(i, 12) <> "" And _
               workArray2(i, 13) = "" Then
                workArray2(i, 13) = myAr2(r, 15)
            End If
            If workArray2(i, 14) <> "" Then
                workArray2(i, 15) = myAr2(r, 15)
            End If
            workArray2(i, 16) = myAr2(r, 11)
        End If
        Select Case True
            Case workArray2(i, 0) = "14004a"
                workArray2(i, 9) = "Safflower oil"
            Case workArray2(i, 0) = "14011a"
                workArray2(i, 9) = "Sunflower oil"
            Case workArray2(i, 0) = "14011b"
                workArray2(i, 9) = "Sunflower oil"
        End Select
    Next r
Next i
ReDim workArray3(UBound(workArray2), UBound(workArray2, 2))
For i = LBound(workArray3) To UBound(workArray3)
    workArray3(i, 0) = workArray2(i, 0)
    workArray3(i, 1) = workArray2(i, 1)
    workArray3(i, 2) = workArray2(i, 2)
    workArray3(i, 3) = workArray2(i, 4)
    workArray3(i, 4) = workArray2(i, 6)
    workArray3(i, 5) = workArray2(i, 8)
    workArray3(i, 6) = workArray2(i, 10)
    workArray3(i, 7) = workArray2(i, 12)
    workArray3(i, 8) = workArray2(i, 14)
    workArray3(i, 9) = workArray2(i, 3)
    workArray3(i, 10) = workArray2(i, 5)
    workArray3(i, 11) = workArray2(i, 7)
    workArray3(i, 12) = workArray2(i, 16)
    workArray3(i, 13) = workArray2(i, 9)
    workArray3(i, 14) = workArray2(i, 11)
    workArray3(i, 15) = workArray2(i, 13)
    workArray3(i, 16) = workArray2(i, 15)
Next i
Set mySht = Worksheets.Add
With mySht
    .Name = "M_CATEGORY"
    .Range("A1").Value = "ItemNumber"
    .Range("B1").Value = "FoodGroupNumber"
    .Range("C1").Value = "FoodGroupJP"
    .Range("D1").Value = "SubGroupJP"
    .Range("E1").Value = "SubCategoryJP"
    .Range("F1").Value = "MajorCategoryJP"
    .Range("G1").Value = "MediumCategoryJP"
    .Range("H1").Value = "MinorCategoryJP"
    .Range("I1").Value = "DetailsJP"
    .Range("J1").Value = "FoodGroupEN"
    .Range("K1").Value = "SubGroupEN"
    .Range("L1").Value = "SubCategoryEN"
    .Range("M1").Value = "AcademicName"
    .Range("N1").Value = "MajorCategoryEN"
    .Range("O1").Value = "MediumCategoryEN"
    .Range("P1").Value = "MinorCategoryEN"
    .Range("Q1").Value = "DetailsEN"
    .Range("A2:Q1892") = workArray3
End With
Set tmpSht = Nothing
Set tmpRng = Nothing
Set tmpArray = Nothing
Set workArray = Nothing
Set RegExp_Japanese = Nothing
Set RegExp_English = Nothing
Set RegExp_ItemNum = Nothing
Set RegExp_Square_Start = Nothing
Set RegExp_SquareExitEN = Nothing
Set RegExp_RoundStartJP = Nothing
Set RegExp_RoundStartEN = Nothing
Set RegExp_RoundExitEN = Nothing
Erase Item_Number()
Erase JapaneseItem()
Erase EnglishItem()
Erase JapaneseClass()
Erase English_Class()
Erase ItemNumArray()
Erase ItemENGArray()
Erase ClassArrayJP()
Erase ClassArrayEN()
Erase SubClassJapanese()
Erase SubClass_English()
Erase MidleClassJP()
Erase MidleClassEN()
Erase SubClass_JPN()
Erase SubClass_ENG()
Erase workArray2()
Erase workArray3()
Set mySht = Nothing
Set myRng = Nothing
Set myAr = Nothing
Set mySht2 = Nothing
Set myRng2 = Nothing
Set myAr2 = Nothing
End Sub

Function NoCancelArray(ByRef Sh As Variant) As Variant
Dim mySht           As Variant
Dim myRng           As Range
Dim tmpAr           As Variant
Dim i               As Long
Dim j               As Long
Dim RegExpCancel    As Object
Dim RegExp_Exit     As Object
Const StrCancel     As String = "^(1\)|residues)$"
Dim CancelItem()    As String
Dim CancelRow1()    As String
Dim CancelRow2()    As String
Dim myCancelAr()    As String
Dim Cancel_Array()  As String
    Set RegExpCancel = CreateObject("VBScript.RegExp")
    With RegExpCancel
        .Pattern = StrCancel
        .IgnoreCase = True
        .Global = True
    End With
tmpAr = Sh
j = 0
For i = LBound(tmpAr) To UBound(tmpAr)
    If RegExpCancel.Test(tmpAr(i, 1)) Then
        ReDim Preserve CancelItem(j)
        ReDim Preserve CancelRow1(i)
        CancelItem(j) = tmpAr(i, 1)
        CancelRow1(j) = i
        j = j + 1
    End If
Next i
ReDim myCancelAr(UBound(CancelItem), 1)
For j = LBound(myCancelAr) To UBound(myCancelAr)
    myCancelAr(j, 0) = CancelItem(j)
    myCancelAr(j, 1) = CancelRow1(j)
Next j
ReDim Preserve myCancelAr(UBound(myCancelAr), 2)
j = 0
For i = LBound(myCancelAr) To UBound(myCancelAr) - 1
    If myCancelAr(i, 0) = "1)" Then
        If UBound(myCancelAr) >= 2 Then
            If myCancelAr(i + 2, 0) = "residues" Then
                myCancelAr(i, 2) = myCancelAr(i + 2, 1)
            Else
                myCancelAr(i, 2) = myCancelAr(i + 1, 1)
            End If
        Else
            myCancelAr(i, 2) = myCancelAr(i + 1, 1)
        End If
        j = j + 1
    End If
Next i
Erase CancelRow1
j = 0
ReDim CancelRow1(j)
ReDim CancelRow2(j)
CancelRow1(j) = myCancelAr(j, 1)
CancelRow2(j) = myCancelAr(j, 2)
For i = LBound(myCancelAr) + 1 To UBound(myCancelAr)
    If myCancelAr(i, 0) = "1)" And _
       myCancelAr(i - 1, 0) <> "1)" Then
        j = j + 1
        ReDim Preserve CancelRow1(j)
        ReDim Preserve CancelRow2(j)
        CancelRow1(j) = myCancelAr(i, 1)
        CancelRow2(j) = myCancelAr(i, 2)
    End If
Next i
ReDim Cancel_Array(UBound(CancelRow1), 1)
j = 0
For j = LBound(Cancel_Array) To UBound(Cancel_Array)
    Cancel_Array(j, 0) = CancelRow1(j)
    Cancel_Array(j, 1) = CancelRow2(j)
Next j
j = 0
Cancel_Array(j, 0) = 1
Cancel_Array(j, 1) = CancelRow1(j)
For j = LBound(Cancel_Array) + 1 To UBound(Cancel_Array)
    Cancel_Array(j, 0) = CancelRow2(j - 1) + 1
    Cancel_Array(j, 1) = CancelRow1(j) - 1
Next j
NoCancelArray = Cancel_Array
End Function

I have counted number of modified cells. It was more than 2400. I could not write complete code without manual processing. It is the responsibility of the Ministry of Education, Culture, Sports, Science & Technology in Japan (MEXT).

References:
CSV file of the ‘Standard Tables of Food Composition in Japan 2010′
Classify the Item_Number of the ‘Standard Tables of Food Composition in Japan 2010′, Part 1

日本食品標準成分表2010の食品番号をカテゴリー分類する その2

日本食品標準成分表2010』のPDFを.txtファイルに変換するの記事を参考に,ファイル名 “1299012_1.pdf” から “1299012_18.pdf” までのファイルをダウンロードします.PDF1ファイルの全テキストをコピーしてワークシート1枚に貼り付けのオプションでペーストします.テキストファイルウィザード1/3では元のデータ形式で『カンマやタブなどの区切り文字によってフィールドごとに区切られたデータ』を選択します.テキストファイルウィザード2/3では特に変更なく次へ進みます.テキストファイルウィザード3/3では最初のカラムの列のデータ形式のみ『文字列』に変更して完了をクリックします.この作業をPDFファイル分繰り返します.主にA列に対して若干の修正を施します.さらに Webテク実験室 からダウンロードしたブック “成分表2010.xls” のワークシートをコピーし,シート名を “Sheet0” に変更します.このEXCELのブックに “Category.xlsm” と名前を付けて保存します.

日本食品標準成分表2010の食品番号をカテゴリー分類する その1で作成した ”Sample.xlsm” ブックから ”Result” シートを “Category.xlsm” ブックに移動又はコピーします.AltキーとF11キーを押下してVBEを起動します.標準モジュールを挿入し,下記コードを貼り付けて実行して下さい.結果として “M_CATEGORY” という名のシートが生成します.

Option Explicit
Sub Select_Class()
Dim tmpSht              As Worksheet
Dim tmpRng              As Range
Dim tmpArray            As Variant
Dim workArray           As Variant
Dim h                   As Long
Dim i                   As Long
Dim j                   As Long
Dim k                   As Long
Dim l                   As Long
Dim m                   As Long
Dim n                   As Long
Dim p                   As Long
Dim q                   As Long
Dim r                   As Long
Dim RegExp_Japanese     As Object
Dim RegExp_English      As Object
Dim RegExp_ItemNum      As Object
Const PtnJPN            As String = "[^A-Za-z0-9'\.\-\*]{2,}"
Const PtnENG            As String = "^[A-Za-z0-9'\,\.\-\%]+$"
Const PtnItemNum        As String = "^[0-9]{5}$"
Dim Item_Number()       As String
Dim JapaneseItem()      As String
Dim EnglishItem()       As String
Dim EnglishString       As String
Dim JapaneseClass()     As String
Dim English_Class()     As String
Dim ClassStringEN       As String
Dim ItemNumArray()      As String
Dim ItemENGArray()      As String
Dim ClassArrayJP()      As String
Dim ClassArrayEN()      As String
Dim RegExp_AngleBracket As Object
Dim RegExp_RoundStartJP As Object
Dim RegExp_RoundStartEN As Object
Dim RegExp_RoundExitEN  As Object
Const Ptn_Round_Start   As String = "^(\(|()"
Const Ptn_Round_Exit    As String = "(\)|))$"
Dim StringRoundEnglish  As String
Dim SubClassJapanese()  As String
Dim SubClass_English()  As String
Dim RegExp_Square_Start As Object
Dim RegExp_SquareExitEN As Object
Const Ptn_Angle_Start   As String = "^[<<]"
Const Ptn_SquareStart   As String = "^\["
Const Ptn_Square_Exit   As String = "\]$"
Dim MidleClassJP()      As String
Dim MidleClassEN()      As String
Dim StrMidClassENG      As String
Dim SubClass_JPN()      As String
Dim SubClass_ENG()      As String
Dim mySht               As Worksheet
Dim myRng               As Range
Dim myAr                As Variant
Dim workArray2()        As String
Dim workArray3()        As String
Dim mySht2              As Worksheet
Dim myRng2              As Range
Dim myAr2               As Variant
Dim CEREALS             As Long
Dim POTATOES            As Long
Dim SUGARS              As Long
Dim PULSES              As Long
Dim NUTS                As Long
Dim VEGETABLES          As Long
Dim FRUITS              As Long
Dim MUSHROOMS           As Long
Dim ALGAE               As Long
Dim FISHES              As Long
Dim MEATS               As Long
Dim EGGS                As Long
Dim MILK                As Long
Dim OIL                 As Long
Dim CONFECTIONERIES     As Long
Dim BEVERAGES           As Long
Dim SEASONINGS          As Long
Dim PREPARED            As Long
    Set RegExp_Japanese = CreateObject("VBScript.RegExp")
    With RegExp_Japanese
        .Pattern = PtnJPN
        .IgnoreCase = True
        .Global = True
    End With
    Set RegExp_English = CreateObject("VBScript.RegExp")
    With RegExp_English
        .Pattern = PtnENG
        .IgnoreCase = True
        .Global = True
    End With
    Set RegExp_ItemNum = CreateObject("VBScript.RegExp")
    With RegExp_ItemNum
        .Pattern = PtnItemNum
        .IgnoreCase = True
        .Global = True
    End With
    Set RegExp_Square_Start = CreateObject("VBScript.RegExp")
    With RegExp_Square_Start
        .Pattern = Ptn_SquareStart
        .IgnoreCase = True
        .Global = True
    End With
    Set RegExp_SquareExitEN = CreateObject("VBScript.RegExp")
    With RegExp_SquareExitEN
        .Pattern = "[A-Za-z0-9'\,\.\-\%]+" & Ptn_Square_Exit
        .IgnoreCase = True
        .Global = True
    End With
    Set RegExp_RoundStartJP = CreateObject("VBScript.RegExp")
    With RegExp_RoundStartJP
        .Pattern = Ptn_Round_Start & "[^A-Za-z0-9'\.\-\*]{2,}"
        .IgnoreCase = True
        .Global = True
    End With
    Set RegExp_RoundStartEN = CreateObject("VBScript.RegExp")
    With RegExp_RoundStartEN
        .Pattern = Ptn_Round_Start & "[A-Za-z'\,\.\-\%]+"
    End With
    Set RegExp_RoundExitEN = CreateObject("VBScript.RegExp")
    With RegExp_RoundExitEN
        .Pattern = "[A-Za-z0-9'\,\.\-\%]+" & Ptn_Round_Exit
        .IgnoreCase = True
        .Global = True
    End With
j = 0
k = 0
l = 0
m = 0
q = 0
For Each tmpSht In Worksheets
    If tmpSht.Name = "M_CATEGORY" Then
        MsgBox prompt:="M_CATEGORYと同名のシートがあります." & vbCrLf & _
                        "処理を終了します", _
              Buttons:=vbOKOnly, _
                Title:="内部エラー"
        Exit Sub
    End If
    If tmpSht.Name <> "Sheet0" And _
       tmpSht.Name <> "Sheet00" And _
       tmpSht.Name <> "Result" Then
        Set tmpRng = tmpSht.UsedRange
        tmpArray = tmpRng
        workArray = NoCancelArray(tmpArray)
        For h = LBound(workArray) To UBound(workArray)
            For i = workArray(h, 0) To workArray(h, 1)
                On Error Resume Next
                If RegExp_ItemNum.Test(tmpArray(i, 1)) And _
                   tmpArray(i, 2) <> "(欠番)" Then
                    EnglishString = ""
                    ReDim Preserve Item_Number(j)
                    ReDim Preserve JapaneseItem(j)
                    ReDim Preserve EnglishItem(j)
                    For p = 1 To 6
                        If RegExp_English.Test(tmpArray(i + 1, p)) Then
                            EnglishString = EnglishString & " " & tmpArray(i + 1, p)
                            EnglishString = Trim(EnglishString)
                        Else
                            Exit For
                        End If
                    Next p
                    Item_Number(j) = tmpArray(i, 1)
                    JapaneseItem(j) = tmpArray(i, 2)
                    EnglishItem(j) = EnglishString
                    j = j + 1
                End If
                On Error GoTo 0
                If RegExp_Japanese.Test(tmpArray(i, 1)) And _
                   RegExp_English.Test(tmpArray(i + 1, 1)) Then
                    ClassStringEN = ""
                    ReDim Preserve JapaneseClass(k)
                    ReDim Preserve English_Class(k)
                    For p = 1 To 6
                        If RegExp_English.Test(tmpArray(i + 1, p)) Then
                            ClassStringEN = ClassStringEN & " " & tmpArray(i + 1, p)
                            ClassStringEN = Trim(ClassStringEN)
                        Else
                            Exit For
                        End If
                    Next p
                    JapaneseClass(k) = tmpArray(i, 1)
                    English_Class(k) = ClassStringEN
                    k = k + 1
                End If
                If RegExp_Square_Start.Test(tmpArray(i, 1)) And _
                   RegExp_Square_Start.Test(tmpArray(i + 1, 1)) Then
                    StrMidClassENG = ""
                    ReDim Preserve MidleClassJP(l)
                    ReDim Preserve MidleClassEN(l)
                    For p = 1 To 6
                        StrMidClassENG = StrMidClassENG + " " + tmpArray(i + 1, p)
                        StrMidClassENG = Trim(StrMidClassENG)
                        If RegExp_SquareExitEN.Test(tmpArray(i + 1, p)) Then Exit For
                    Next p
                    MidleClassJP(l) = tmpArray(i, 1)
                    MidleClassEN(l) = StrMidClassENG
                    l = l + 1
                End If
                If RegExp_RoundStartJP.Test(tmpArray(i, 1)) And _
                   RegExp_RoundStartEN.Test(tmpArray(i + 1, 1)) Then
                    StringRoundEnglish = ""
                    ReDim Preserve SubClassJapanese(m)
                    ReDim Preserve SubClass_English(m)
                    For p = 1 To 6
                        StringRoundEnglish = StringRoundEnglish & " " & tmpArray(i + 1, p)
                        StringRoundEnglish = Trim(StringRoundEnglish)
                        If RegExp_RoundExitEN.Test(tmpArray(i + 1, p)) Then Exit For
                    Next p
                    tmpArray(i, 1) = Replace(tmpArray(i, 1), "(", "(")
                    tmpArray(i, 1) = Replace(tmpArray(i, 1), ")", ")")
                    SubClassJapanese(m) = tmpArray(i, 1)
                    StringRoundEnglish = Replace(StringRoundEnglish, "(", "(")
                    StringRoundEnglish = Replace(StringRoundEnglish, ")", ")")
                    SubClass_English(m) = StringRoundEnglish
                    m = m + 1
                End If
            Next i
        Next h
        q = q + 1
    End If
Next tmpSht
Set mySht = Worksheets("Sheet0")
Set myRng = Intersect(mySht.Range("A:H"), mySht.UsedRange)
myAr = myRng
ReDim workArray2(UBound(myAr) - 1, 16)
For i = LBound(workArray2) To UBound(workArray2)
    workArray2(i, 0) = myAr(i + 1, 1)
    workArray2(i, 1) = myAr(i + 1, 2)
    workArray2(i, 2) = myAr(i + 1, 3)
    myAr(i + 1, 4) = Replace(myAr(i + 1, 4), "(", "(")
    myAr(i + 1, 4) = Replace(myAr(i + 1, 4), ")", ")")
    workArray2(i, 6) = myAr(i + 1, 4)
    workArray2(i, 8) = myAr(i + 1, 5)
    workArray2(i, 10) = myAr(i + 1, 6)
    workArray2(i, 12) = myAr(i + 1, 7)
    workArray2(i, 14) = myAr(i + 1, 8)
Next i
Set mySht2 = Worksheets("Result")
Set myRng2 = mySht2.UsedRange
myAr2 = myRng2
For i = LBound(workArray2) To UBound(workArray2)
    For k = LBound(JapaneseClass) To UBound(JapaneseClass)
        If workArray2(i, 2) = JapaneseClass(k) Then
           workArray2(i, 3) = English_Class(k)
        End If
        If workArray2(i, 4) = JapaneseClass(k) Then
           workArray2(i, 5) = English_Class(k)
        End If
        If workArray2(i, 8) = JapaneseClass(k) Then
           workArray2(i, 9) = English_Class(k)
        End If
        If workArray2(i, 12) = JapaneseClass(k) Then
           workArray2(i, 13) = English_Class(k)
        End If
    Next k
    For m = LBound(SubClassJapanese) To UBound(SubClassJapanese)
        If workArray2(i, 6) = SubClassJapanese(m) Then
           workArray2(i, 7) = SubClass_English(m)
        End If
    Next m
    For l = UBound(MidleClassJP) To LBound(MidleClassJP) Step -1
        If workArray2(i, 10) = MidleClassJP(l) Then
           workArray2(i, 11) = MidleClassEN(l)
        End If
    Next l
    For r = LBound(myAr2) To UBound(myAr2)
        If workArray2(i, 0) = myAr2(r, 1) Then
            workArray2(i, 4) = myAr2(r, 5)
            On Error Resume Next
            Select Case True
            Case workArray2(i, 0) >= "10001" And workArray2(i, 0) <= "10278"
                 workArray2(i, 4) = "<魚類>"
            Case workArray2(i, 0) >= "10319" And workArray2(i, 0) <= "10341"
                 workArray2(i, 4) = "<えび・かに類>"
            Case workArray2(i, 0) >= "10342" And workArray2(i, 0) <= "10362"
                 workArray2(i, 4) = "<いか・たこ類>"
            Case workArray2(i, 0) >= "10376" And workArray2(i, 0) <= "10388"
                 workArray2(i, 4) = "<水産練り製品>"
            Case workArray2(i, 0) >= "11205" And workArray2(i, 0) <= "11240"
                 workArray2(i, 4) = "<鳥肉類>"
            Case workArray2(i, 0) >= "11245" And workArray2(i, 0) <= "11246"
                 workArray2(i, 4) = "<獣肉類>"
            Case workArray2(i, 0) >= "11247" And workArray2(i, 0) <= "11247"
                 workArray2(i, 4) = "<鳥肉類>"
            Case workArray2(i, 0) >= "13001" And workArray2(i, 0) <= "13050"
                 workArray2(i, 4) = "<牛乳及び乳製品>"
            Case workArray2(i, 0) >= "15001" And workArray2(i, 0) <= "15040"
                 workArray2(i, 4) = "<和生菓子・和半生菓子類>"
            Case workArray2(i, 0) >= "15041" And workArray2(i, 0) <= "15068"
                 workArray2(i, 4) = "<和干菓子類>"
            Case workArray2(i, 0) >= "15069" And workArray2(i, 0) <= "15072"
                 workArray2(i, 4) = "<菓子パン類>"
            Case workArray2(i, 0) >= "15073" And workArray2(i, 0) <= "15085"
                 workArray2(i, 4) = "<ケーキ・ペストリー類>"
            Case workArray2(i, 0) >= "15086" And workArray2(i, 0) <= "15091"
                 workArray2(i, 4) = "<デザート菓子類>"
            Case workArray2(i, 0) >= "15092" And workArray2(i, 0) <= "15100"
                 workArray2(i, 4) = "<ビスケット類>"
            Case workArray2(i, 0) >= "15101" And workArray2(i, 0) <= "15104"
                 workArray2(i, 4) = "<スナック類>"
            Case workArray2(i, 0) >= "15105" And workArray2(i, 0) <= "15113"
                 workArray2(i, 4) = "<キャンデー類>"
            Case workArray2(i, 0) >= "15114" And workArray2(i, 0) <= "15116"
                 workArray2(i, 4) = "<チョコレート類>"
            Case workArray2(i, 0) >= "15117" And workArray2(i, 0) <= "15117"
                 workArray2(i, 4) = "<果実菓子類>"
            Case workArray2(i, 0) >= "15118" And workArray2(i, 0) <= "15120"
                 workArray2(i, 4) = "<チューインガム類>"
            Case workArray2(i, 0) >= "16001" And workArray2(i, 0) <= "16032"
                 workArray2(i, 4) = "<アルコール飲料類>"
            Case workArray2(i, 0) >= "16033" And workArray2(i, 0) <= "16044"
                 workArray2(i, 4) = "<茶類>"
            Case workArray2(i, 0) >= "16045" And workArray2(i, 0) <= "16049"
                 workArray2(i, 4) = "<コーヒー・ココア類>"
            Case workArray2(i, 0) >= "16050" And workArray2(i, 0) <= "16055"
                 workArray2(i, 4) = "<その他>"
            Case workArray2(i, 0) >= "17001" And workArray2(i, 0) <= "17054"
                 workArray2(i, 4) = "<調味料類>"
            Case workArray2(i, 0) >= "17055" And workArray2(i, 0) <= "17081"
                 workArray2(i, 4) = "<香辛料類>"
            Case workArray2(i, 0) >= "17082" And workArray2(i, 0) <= "17084"
                 workArray2(i, 4) = "<その他>"
            End Select
            On Error GoTo 0
            workArray2(i, 5) = myAr2(r, 6)
            On Error Resume Next
            Select Case True
            Case workArray2(i, 0) >= "10001" And workArray2(i, 0) <= "10278"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "10319" And workArray2(i, 0) <= "10341"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "10342" And workArray2(i, 0) <= "10362"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "10376" And workArray2(i, 0) <= "10388"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "11205" And workArray2(i, 0) <= "11240"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "11245" And workArray2(i, 0) <= "11246"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "11247" And workArray2(i, 0) <= "11247"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "13001" And workArray2(i, 0) <= "13050"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15001" And workArray2(i, 0) <= "15040"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15041" And workArray2(i, 0) <= "15068"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15069" And workArray2(i, 0) <= "15072"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15073" And workArray2(i, 0) <= "15085"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15086" And workArray2(i, 0) <= "15091"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15092" And workArray2(i, 0) <= "15100"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15101" And workArray2(i, 0) <= "15104"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15105" And workArray2(i, 0) <= "15113"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15114" And workArray2(i, 0) <= "15116"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "15117" And workArray2(i, 0) <= "15117"
                 workArray2(i, 5) = "<CANDIED FRUITS>"
            Case workArray2(i, 0) >= "15118" And workArray2(i, 0) <= "15120"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "16001" And workArray2(i, 0) <= "16032"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "16033" And workArray2(i, 0) <= "16044"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "16045" And workArray2(i, 0) <= "16049"
                 workArray2(i, 5) = "COFFEES AND COCOAS>"
            Case workArray2(i, 0) >= "16050" And workArray2(i, 0) <= "16055"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "17001" And workArray2(i, 0) <= "17054"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "17055" And workArray2(i, 0) <= "17081"
                 workArray2(i, 5) = ""
            Case workArray2(i, 0) >= "17082" And workArray2(i, 0) <= "17084"
                 workArray2(i, 5) = ""
            End Select
            On Error GoTo 0
            If workArray2(i, 6) <> "" And _
               workArray2(i, 7) = "" Then
                workArray2(i, 7) = myAr2(r, 8)
            End If
            If workArray2(i, 8) <> "" And _
               workArray2(i, 9) = "" Then
                If myAr2(r, 10) = "" Then
                    workArray2(i, 9) = myAr2(r, 15)
                Else
                    workArray2(i, 9) = myAr2(r, 10)
                End If
            End If
            If workArray2(i, 12) <> "" And _
               workArray2(i, 13) = "" Then
                workArray2(i, 13) = myAr2(r, 15)
            End If
            If workArray2(i, 14) <> "" Then
                workArray2(i, 15) = myAr2(r, 15)
            End If
            workArray2(i, 16) = myAr2(r, 11)
        End If
        Select Case True
            Case workArray2(i, 0) = "14004a"
                workArray2(i, 9) = "Safflower oil"
            Case workArray2(i, 0) = "14011a"
                workArray2(i, 9) = "Sunflower oil"
            Case workArray2(i, 0) = "14011b"
                workArray2(i, 9) = "Sunflower oil"
        End Select
    Next r
Next i
ReDim workArray3(UBound(workArray2), UBound(workArray2, 2))
For i = LBound(workArray3) To UBound(workArray3)
    workArray3(i, 0) = workArray2(i, 0)
    workArray3(i, 1) = workArray2(i, 1)
    workArray3(i, 2) = workArray2(i, 2)
    workArray3(i, 3) = workArray2(i, 4)
    workArray3(i, 4) = workArray2(i, 6)
    workArray3(i, 5) = workArray2(i, 8)
    workArray3(i, 6) = workArray2(i, 10)
    workArray3(i, 7) = workArray2(i, 12)
    workArray3(i, 8) = workArray2(i, 14)
    workArray3(i, 9) = workArray2(i, 3)
    workArray3(i, 10) = workArray2(i, 5)
    workArray3(i, 11) = workArray2(i, 7)
    workArray3(i, 12) = workArray2(i, 16)
    workArray3(i, 13) = workArray2(i, 9)
    workArray3(i, 14) = workArray2(i, 11)
    workArray3(i, 15) = workArray2(i, 13)
    workArray3(i, 16) = workArray2(i, 15)
Next i
Set mySht = Worksheets.Add
With mySht
    .Name = "M_CATEGORY"
    .Range("A1").Value = "ItemNumber"
    .Range("B1").Value = "FoodGroupNumber"
    .Range("C1").Value = "FoodGroupJP"
    .Range("D1").Value = "SubGroupJP"
    .Range("E1").Value = "SubCategoryJP"
    .Range("F1").Value = "MajorCategoryJP"
    .Range("G1").Value = "MediumCategoryJP"
    .Range("H1").Value = "MinorCategoryJP"
    .Range("I1").Value = "DetailsJP"
    .Range("J1").Value = "FoodGroupEN"
    .Range("K1").Value = "SubGroupEN"
    .Range("L1").Value = "SubCategoryEN"
    .Range("M1").Value = "AcademicName"
    .Range("N1").Value = "MajorCategoryEN"
    .Range("O1").Value = "MediumCategoryEN"
    .Range("P1").Value = "MinorCategoryEN"
    .Range("Q1").Value = "DetailsEN"
    .Range("A2:Q1892") = workArray3
End With
Set tmpSht = Nothing
Set tmpRng = Nothing
Set tmpArray = Nothing
Set workArray = Nothing
Set RegExp_Japanese = Nothing
Set RegExp_English = Nothing
Set RegExp_ItemNum = Nothing
Set RegExp_Square_Start = Nothing
Set RegExp_SquareExitEN = Nothing
Set RegExp_RoundStartJP = Nothing
Set RegExp_RoundStartEN = Nothing
Set RegExp_RoundExitEN = Nothing
Erase Item_Number()
Erase JapaneseItem()
Erase EnglishItem()
Erase JapaneseClass()
Erase English_Class()
Erase ItemNumArray()
Erase ItemENGArray()
Erase ClassArrayJP()
Erase ClassArrayEN()
Erase SubClassJapanese()
Erase SubClass_English()
Erase MidleClassJP()
Erase MidleClassEN()
Erase SubClass_JPN()
Erase SubClass_ENG()
Erase workArray2()
Erase workArray3()
Set mySht = Nothing
Set myRng = Nothing
Set myAr = Nothing
Set mySht2 = Nothing
Set myRng2 = Nothing
Set myAr2 = Nothing
End Sub

Function NoCancelArray(ByRef Sh As Variant) As Variant
Dim mySht           As Variant
Dim myRng           As Range
Dim tmpAr           As Variant
Dim i               As Long
Dim j               As Long
Dim RegExpCancel    As Object
Dim RegExp_Exit     As Object
Const StrCancel     As String = "^(1\)|residues)$"
Dim CancelItem()    As String
Dim CancelRow1()    As String
Dim CancelRow2()    As String
Dim myCancelAr()    As String
Dim Cancel_Array()  As String
    Set RegExpCancel = CreateObject("VBScript.RegExp")
    With RegExpCancel
        .Pattern = StrCancel
        .IgnoreCase = True
        .Global = True
    End With
tmpAr = Sh
j = 0
For i = LBound(tmpAr) To UBound(tmpAr)
    If RegExpCancel.Test(tmpAr(i, 1)) Then
        ReDim Preserve CancelItem(j)
        ReDim Preserve CancelRow1(i)
        CancelItem(j) = tmpAr(i, 1)
        CancelRow1(j) = i
        j = j + 1
    End If
Next i
ReDim myCancelAr(UBound(CancelItem), 1)
For j = LBound(myCancelAr) To UBound(myCancelAr)
    myCancelAr(j, 0) = CancelItem(j)
    myCancelAr(j, 1) = CancelRow1(j)
Next j
ReDim Preserve myCancelAr(UBound(myCancelAr), 2)
j = 0
For i = LBound(myCancelAr) To UBound(myCancelAr) - 1
    If myCancelAr(i, 0) = "1)" Then
        If UBound(myCancelAr) >= 2 Then
            If myCancelAr(i + 2, 0) = "residues" Then
                myCancelAr(i, 2) = myCancelAr(i + 2, 1)
            Else
                myCancelAr(i, 2) = myCancelAr(i + 1, 1)
            End If
        Else
            myCancelAr(i, 2) = myCancelAr(i + 1, 1)
        End If
        j = j + 1
    End If
Next i
Erase CancelRow1
j = 0
ReDim CancelRow1(j)
ReDim CancelRow2(j)
CancelRow1(j) = myCancelAr(j, 1)
CancelRow2(j) = myCancelAr(j, 2)
For i = LBound(myCancelAr) + 1 To UBound(myCancelAr)
    If myCancelAr(i, 0) = "1)" And _
       myCancelAr(i - 1, 0) <> "1)" Then
        j = j + 1
        ReDim Preserve CancelRow1(j)
        ReDim Preserve CancelRow2(j)
        CancelRow1(j) = myCancelAr(i, 1)
        CancelRow2(j) = myCancelAr(i, 2)
    End If
Next i
ReDim Cancel_Array(UBound(CancelRow1), 1)
j = 0
For j = LBound(Cancel_Array) To UBound(Cancel_Array)
    Cancel_Array(j, 0) = CancelRow1(j)
    Cancel_Array(j, 1) = CancelRow2(j)
Next j
j = 0
Cancel_Array(j, 0) = 1
Cancel_Array(j, 1) = CancelRow1(j)
For j = LBound(Cancel_Array) + 1 To UBound(Cancel_Array)
    Cancel_Array(j, 0) = CancelRow2(j - 1) + 1
    Cancel_Array(j, 1) = CancelRow1(j) - 1
Next j
NoCancelArray = Cancel_Array
End Function

参照:
日本食品標準成分表2010の食品番号をカテゴリー分類する その1
日本食品標準成分表2010のcsvファイル

CSV file of the ‘Standard Tables of Food Composition in Japan 2010’

I had posted the article which contains ‘M_FOODS.txt’, which is derived from the ‘Standard Tables of Food Composition in Japan 2010’, on January 12, 2012. The employee of the Ministry of Education, Culture, Sports, Science & Technology in Japan (MEXT) has asked me to inform on my blog of name and unit of each component of ‘M_FOODS.txt’ file. I have added name and unit to table head of CSV file. Then I post it on my blog.

In original PDF files, comma character is used in component as character rather than as delimiter and space character is used as delimiter. Because I could not use comma character as delimiter, I had to use tab character as delimiter. Although we use double quotes as quote with EXCEL, such other program as relational database management software may use single quotes as quote. Therefore, I didn’t use quote at all. When you open this file, don’t double click to open, please. Please use ‘Text file wizard’. In the last tab of wizard, you would had to select ‘string’ data type of first column. If you would not have followed this warning, you could not open correctly and you would be confused why the length of item number is 4 and the first ‘0’ is missing.

This file has 54 columns and 1,881 rows. The first three lines show data structure, following lines from the fourth line show data itself. Japanese name of components in the first line, English name of components in the second line and unit in the third line. It means ‘g’ as gram, ‘mg’ as milligram and ‘microgram’ as micro-gram.

Please note following:

1. I have replaced the strings ‘(0)’, ‘Tr’, ‘(Tr)’ and ‘-‘ with ‘0’.

2. The text file is derived from ‘Standard Tables of Food Composition in Japan 2010’, published by Report of the Subdivision on Resources The Council for Science and Technology, MEXT, JAPAN. Please contact MEXT to obtain application or notification before duplication or reproduction.

E-mail: kagseis@mext.go.jp

M_FOODS.csv

References:
Classify the Item_Number of the ‘Standard Tables of Food Composition in Japan 2010′, Part 1
Classify the Item_Number of the ‘Standard Tables of Food Composition in Japan 2010′, Part 2

日本食品標準成分表2010のcsvファイル

2012年1月12日,日本食品標準成分表2010のテキストデータの記事を投稿しました.その際に’M_FOODS.txt’ファイルに各項目の名称と単位を付記されたいとの依頼があったと追記しました.今回は表頭に各項目名と単位を付記したcsvファイルを作成しましたので公開いたします.

元のPDFファイルでは各要素内にコンマを使用しており,デリミタとしてスペースを使用していました.本ファイルではタブをデリミタとして使用しています.EXCELでは通常ダブルクォーテーションを引用符として用いますが,他のデータベースソフトではシングルクォーテーションを引用符として用いるものもあります.そのため本ファイルでは引用符を使用しておりません.EXCELに取り込む際にはダブルクリックで開かず,必ず’データ’タブの’外部データをインポートする’から’テキストファイル’を選択してください.またテキストファイルウィザードの最後のタブで1列目のデータ型を’文字列’にしてください.以上の注意点を守らない場合,食品番号は通常5桁の数値ですが,先頭の’0’が欠落する場合があります.



本ファイルは54列1881行から成ります.表頭3行はデータ構造を示し,4行目以降が実際のデータです.1行目は日本語の項目名,2行目は英語の項目名,3行目は単位です.gはグラム,mgはミリグラム,microgramはマイクログラムです.

以下の点にご注意ください.

1.「日本食品標準成分表2010」に記載されている,(0),Tr,(Tr),-,について,当データでは「 0 」と表記しています.

2.本表の食品成分値は文部科学省科学技術・学術審議会資源調査分科会報告「日本食品標準成分表2010」によるものです.食品成分値を複製又は転載する場合は事前に文部科学省への許可申請もしくは届け出が必要となる場合があります.

連絡先:文部科学省科学技術・学術政策局政策課資源室 E-mail: kagseis@mext.go.jp

M_FOODS.csv

参照:
日本食品標準成分表2010の食品番号をカテゴリー分類する その1
日本食品標準成分表2010の食品番号をカテゴリー分類する その2

Classify the Item_Number of the ‘Standard Tables of Food Composition in Japan 2010′, Part 1

I have posted the article Classify the Item_Number of the ‘Standard Tables of Food Composition in Japan 2010′ that caused incomplete result. After post it, I have found good article in Japanese. Therefore, I gave it additional value in English.

Standard Tables of Food Composition in Japan 2010

Make a new EXCEL Book. Copy text from the PDF files (‘1299012_1.pdf’ to ‘1299012_18.pdf’) and option paste to EXCEL worksheet ‘Sheet1’ continuously without blank line between the last line of previous text and the first line of next text. With ‘Text File Wizard’, change option data type of the first column to ‘String’. Download Academic name of food materials, select all text and paste to Sheet2. In the first tab of ‘Text File Wizard’, select option ‘The data field separated by delimiters such as comma or tab’. In second tab, remove check mark ‘Consider continuous delimiters as one’. In the last tab, change option data type of the first column to ‘String’. Save as ‘Sample.xlsm’.

Press ‘Alt’ key and ‘F11’ key to launch VBE. Insert module and paste following code. Run ‘Separate_by_Parent’ procedure.

Option Explicit
Function MajorCategoryAr(ByRef Sh As Worksheet) As String()
Dim mySht               As Worksheet
Dim myRng               As Range
Dim tmpAr               As Variant
Dim StartEnd            As Variant
Dim strFoodGroup        As String
Dim strFoodGroupJP      As String
Dim strFoodGroupEN      As String
Dim strSubFoodGroup     As String
Dim strSubFoodGroupJP   As String
Dim strSubFoodGroupEN   As String
Dim strSub_Category     As String
Dim strSub_CategoryJP   As String
Dim strSub_CategoryEN   As String
Dim strMajor_Category   As String
Dim StartNumber()       As String
Dim Exit_Number()       As String
Dim FoodGroupJP()       As String
Dim FoodGroupEN()       As String
Dim Sub_FoodGroup_JP()  As String
Dim Sub_FoodGroup_EN()  As String
Dim Sub_Category_JPN()  As String
Dim Sub_Category_ENG()  As String
Dim Major_CategoryJP()  As String
Dim Major_CategoryEN()  As String
Dim Major_CategoryLT()  As String
Dim myArray()           As String
Dim i As Long
Dim j As Long
Dim k As Long
Dim n As Long
Dim RegExp_3_Digit_Num  As Object
Dim RegExp_Item_Number  As Object
Dim RegExp_SentakuHanni As Object
Dim RegExp_SubCategory1 As Object
Dim RegExp_SubCategory2 As Object
Dim RegExp_MedCategory  As Object
Dim RegExp_Foods_Group  As Object
Dim RegExp_Jpn_Eng_Mix  As Object
Dim RegExp_JapaneseOnly As Object
Dim RegExp_Upper_Lower  As Object
Dim RegExp_Upper_Only   As Object
Dim RegExp_Lower_Only   As Object
Dim RegExp_RoundBracket As Object
Dim RegExp_SquareBracket    As Object
Dim RegExp_AngleBracket As Object
Dim myMatches           As Object
Dim myMatch             As Object
Const Ptn_3_Digit_Num   As String = "[0-9]{3}$"
Const Ptn_Item_Number   As String = "^[0-9]{5}$"
Const Ptn_SentakuHanni  As String = "(,|~)"
Const Ptn_SubCategory1  As String = "^((|\().()|\))$"
Const Ptn_SubCategory2  As String = "^(<|>)$"
Const Ptn_MedCategory   As String = "^\[.\]$"
Const Ptn_FoodGroupNum  As String = "^([0-9]|[0-9]{2})$"
Const Ptn_Jpn_Eng_Mix   As String = "^[^A-Za-z0-9]+(\([^A-Za-z0-9]+\))?([A-Za-z])"
Const Ptn_JapaneseOnly  As String = "^[^A-Za-z0-9]+(\([^A-Za-z0-9]+\))?$"
Const Ptn_Upper_Lower   As String = "[A-Z][a-z]+"
Const Ptn_Upper_Only    As String = "[A-Z]+"
Const Ptn_Lower_Only    As String = "^[a-z]+$"
Const Ptn_RoundStart    As String = "^[\((]"
Const Ptn_Round_Exit    As String = "[\((][^A-Za-z0-9]+[\))]"
Const Ptn_SquareStart   As String = "^\["
Const Ptn_Square_Exit   As String = "\[[^A-Za-z0-9]+\]"
Const Ptn_AngleStart    As String = "^[\<<]"
Const Ptn_Angle_Exit    As String = "[\<<][^A-Za-z0-9]+[\>>]"
Set mySht = Sh
Set myRng = mySht.UsedRange
tmpAr = myRng
Set RegExp_3_Digit_Num = CreateObject("VBScript.RegExp")
Set RegExp_Item_Number = CreateObject("VBScript.RegExp")
Set RegExp_SentakuHanni = CreateObject("VBScript.RegExp")
Set RegExp_SubCategory1 = CreateObject("VBScript.RegExp")
Set RegExp_SubCategory2 = CreateObject("VBScript.RegExp")
Set RegExp_MedCategory = CreateObject("VBScript.RegExp")
Set RegExp_Foods_Group = CreateObject("VBScript.RegExp")
Set RegExp_Jpn_Eng_Mix = CreateObject("VBScript.RegExp")
Set RegExp_JapaneseOnly = CreateObject("VBScript.RegExp")
Set RegExp_Upper_Lower = CreateObject("VBScript.RegExp")
Set RegExp_Upper_Only = CreateObject("VBScript.RegExp")
Set RegExp_Lower_Only = CreateObject("VBScript.RegExp")
Set RegExp_RoundBracket = CreateObject("VBScript.RegExp")
Set RegExp_SquareBracket = CreateObject("VBScript.RegExp")
Set RegExp_AngleBracket = CreateObject("VBScript.RegExp")
With RegExp_3_Digit_Num
    .Pattern = "[0-9]{3}$"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_Item_Number
    .Pattern = "^[0-9]{5}$"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_SentakuHanni
    .Pattern = "(,|~)"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_SubCategory1
    .Pattern = "^((|\().()|\))$"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_SubCategory2
    .Pattern = "^(<|>)$"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_MedCategory
    .Pattern = "^\[.\]$"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_Foods_Group
    .Pattern = "^([0-9]|[0-9]{2})$"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_Jpn_Eng_Mix
    .Pattern = "^[^A-Za-z0-9]+(\([^A-Za-z0-9]+\))?([A-Za-z])"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_JapaneseOnly
    .Pattern = "^[^A-Za-z0-9]+(\([^A-Za-z0-9]+\))?$"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_Upper_Lower
    .Pattern = "[A-Z][a-z]+"
    .IgnoreCase = False
    .Global = True
End With
With RegExp_Upper_Only
    .Pattern = "[A-Z]+"
    .IgnoreCase = False
    .Global = True
End With
With RegExp_Lower_Only
    .Pattern = "^[a-z]+$"
    .IgnoreCase = False
    .Global = True
End With
j = 0
For i = LBound(tmpAr) + 1 To UBound(tmpAr)
    With RegExp_RoundBracket
        .Pattern = Ptn_RoundStart
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_SquareBracket
        .Pattern = Ptn_SquareStart
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_AngleBracket
        .Pattern = Ptn_AngleStart
        .IgnoreCase = True
        .Global = True
    End With
    strFoodGroup = ""
    strSubFoodGroup = ""
    strSub_Category = ""
    strMajor_Category = ""
    ReDim Preserve StartNumber(j)
    ReDim Preserve Exit_Number(j)
    ReDim Preserve FoodGroupJP(j)
    ReDim Preserve FoodGroupEN(j)
    ReDim Preserve Sub_FoodGroup_JP(j)
    ReDim Preserve Sub_FoodGroup_EN(j)
    ReDim Preserve Sub_Category_JPN(j)
    ReDim Preserve Sub_Category_ENG(j)
    ReDim Preserve Major_CategoryJP(j)
    ReDim Preserve Major_CategoryEN(j)
    ReDim Preserve Major_CategoryLT(j)
    If RegExp_3_Digit_Num.Test(tmpAr(i, 1)) Then
        Select Case True
        Case RegExp_Item_Number.Test(tmpAr(i, 1))
            StartNumber(j) = tmpAr(i, 1)
            Exit_Number(j) = tmpAr(i, 1)
        Case RegExp_SentakuHanni.Test(tmpAr(i, 1))
            StartEnd = StartExit(tmpAr(i, 1))
            StartNumber(j) = StartEnd(0)
            Exit_Number(j) = StartEnd(1)
            Erase StartEnd
        End Select
        FoodGroupJP(j) = strFoodGroupJP
        FoodGroupEN(j) = strFoodGroupEN
        If (i >= 19 And i <= 27) _
        Or (i >= 370 And i <= 596) _
        Or (i >= 599 And i <= 626) _
        Or (i >= 635 And i <= 639) _
        Or (i >= 646 And i <= 668) _
        Then
            Sub_FoodGroup_JP(j) = strSubFoodGroupJP
            Sub_FoodGroup_EN(j) = strSubFoodGroupEN
        End If
        If tmpAr(i, 2) = "" Then
            Sub_Category_JPN(j) = strSub_CategoryJP
            Sub_Category_ENG(j) = strSub_CategoryEN
        End If
        For k = 2 To 8
            strMajor_Category = strMajor_Category & " " & tmpAr(i, k)
        Next k
        strMajor_Category = Trim(strMajor_Category)
        On Error Resume Next
        For k = 1 To 8
            If RegExp_Lower_Only.Test(tmpAr(i + 1, 1)) _
            And Not RegExp_SubCategory1.Test(tmpAr(i + 1, 1)) _
            And Not RegExp_SubCategory2.Test(tmpAr(i + 1, 1)) _
            And Not RegExp_Foods_Group.Test(tmpAr(i + 1, 1)) _
            And Not RegExp_3_Digit_Num.Test(tmpAr(i + 1, 1)) _
            Then
                strMajor_Category = strMajor_Category & " " & tmpAr(i + 1, k)
            End If
        Next k
        On Error GoTo 0
        strMajor_Category = Trim(strMajor_Category)
        If RegExp_Jpn_Eng_Mix.Test(strMajor_Category) Then
            StartEnd = Separate_Jpn_Eng(strMajor_Category)
            Major_CategoryJP(j) = StartEnd(0)
            Erase StartEnd
            Set myMatches = RegExp_Upper_Lower.Execute(strMajor_Category)
            Major_CategoryEN(j) = Mid(strMajor_Category, _
                                    myMatches.Item(0).firstindex + 1, _
                                    myMatches.Item(myMatches.Count - 1).firstindex _
                                  - myMatches.Item(0).firstindex - 1)
            Set myMatch = myMatches.Item(myMatches.Count - 1)
            Major_CategoryLT(j) = Mid(strMajor_Category, myMatch.firstindex + 1)
        Else
        End If
    Else
        Select Case True
        Case RegExp_Foods_Group.Test(tmpAr(i, 1))
            For k = 2 To 8
                strFoodGroup = strFoodGroup & " " & tmpAr(i, k)
            Next k
            strFoodGroup = Trim(strFoodGroup)
            Select Case True
            Case RegExp_Jpn_Eng_Mix.Test(strFoodGroup)
                Set myMatches = RegExp_Jpn_Eng_Mix.Execute(strFoodGroup)
                Set myMatch = myMatches.Item(0)
                strFoodGroupJP = Left(strFoodGroup, myMatches.Item(0).Length - 1)
                strFoodGroupEN = Mid(strFoodGroup, myMatches.Item(0).Length)
            Case RegExp_JapaneseOnly.Test(strFoodGroup)
                Set myMatches = RegExp_JapaneseOnly.Execute(strFoodGroup)
                Set myMatch = myMatches.Item(0)
                strFoodGroupJP = Left(strFoodGroup, myMatches.Item(0).Length - 1)
                strFoodGroupEN = Mid(strFoodGroup, myMatches.Item(0).Length)
            Case Else
            End Select
        Case RegExp_AngleBracket.Test(tmpAr(i, 1))
            For k = 1 To 8
                strSubFoodGroup = strSubFoodGroup & " " & tmpAr(i, k)
            Next k
            strSubFoodGroup = Trim(strSubFoodGroup)
            With RegExp_AngleBracket
                .Pattern = Ptn_Angle_Exit
                .IgnoreCase = True
                .Global = True
            End With
            Set myMatches = RegExp_AngleBracket.Execute(strSubFoodGroup)
            strSubFoodGroupJP = myMatches.Item(0).Value
            strSubFoodGroupEN = Mid(strSubFoodGroup, myMatches.Item(0).Length + 2)
            strSubFoodGroupEN = Replace(strSubFoodGroupEN, "<", "<")
            strSubFoodGroupEN = Replace(strSubFoodGroupEN, ">", ">")
        Case RegExp_RoundBracket.Test(tmpAr(i, 1))
            For k = 1 To 8
                strSub_Category = strSub_Category & " " & tmpAr(i, k)
            Next k
            strSub_Category = Trim(strSub_Category)
            With RegExp_RoundBracket
                .Pattern = Ptn_Round_Exit
                .IgnoreCase = True
                .Global = True
            End With
            Set myMatches = RegExp_RoundBracket.Execute(strSub_Category)
            On Error Resume Next
            strSub_CategoryJP = myMatches.Item(0).Value
            strSub_CategoryJP = Replace(strSub_CategoryJP, "(", "(")
            strSub_CategoryJP = Replace(strSub_CategoryJP, ")", ")")
            strSub_CategoryEN = Mid(strSub_Category, myMatches.Item(0).Length + 2)
            strSub_CategoryEN = Replace(strSub_CategoryEN, "(", "(")
            strSub_CategoryEN = Replace(strSub_CategoryEN, ")", ")")
            On Error GoTo 0
        Case Else
        End Select
        j = j - 1
    End If
    j = j + 1
Next i
ReDim myArray(UBound(StartNumber), 10)
For n = LBound(myArray) To UBound(myArray)
    myArray(n, 0) = StartNumber(n)
    myArray(n, 1) = Exit_Number(n)
    myArray(n, 2) = FoodGroupJP(n)
    myArray(n, 3) = FoodGroupEN(n)
    myArray(n, 4) = Sub_FoodGroup_JP(n)
    myArray(n, 5) = Sub_FoodGroup_EN(n)
    myArray(n, 6) = Sub_Category_JPN(n)
    myArray(n, 7) = Sub_Category_ENG(n)
    myArray(n, 8) = Major_CategoryJP(n)
    myArray(n, 9) = Major_CategoryEN(n)
    myArray(n, 10) = Major_CategoryLT(n)
Next n
MajorCategoryAr = myArray
End Function

Function StartExit(ByVal InputStr As String) As String()
    Dim str     As String
    Dim Ar()    As String
    str = InputStr
    ReDim Ar(1)
    Ar(0) = Left(str, 5)
    Ar(1) = Left(str, 2) & Right(str, 3)
    StartExit = Ar
End Function

Function Separate_Jpn_Eng(ByVal InputStr As String) As String()
    Dim str                 As String
    Dim Ar()                As String
    Dim RegExp_Jpn_Eng_Mix  As Object
    Dim myMatches           As Object
    Dim myMatch             As Object
    Const Ptn_Jpn_Eng_Mix   As String = "^[^A-Za-z0-9]+(\([^A-Za-z0-9]+\))?([A-Za-z])"
    str = InputStr
    ReDim Ar(1)
    Set RegExp_Jpn_Eng_Mix = CreateObject("VBScript.RegExp")
    With RegExp_Jpn_Eng_Mix
        .Pattern = Ptn_Jpn_Eng_Mix
        .IgnoreCase = True
        .Global = True
    End With
    Set myMatches = RegExp_Jpn_Eng_Mix.Execute(str)
    For Each myMatch In myMatches
        If myMatches.Count > 0 Then
            Ar(0) = Left(str, myMatches.Item(0).Length - 1)
            Ar(1) = Mid(str, myMatches.Item(0).Length)
        End If
    Next myMatch
    Separate_Jpn_Eng = Ar
End Function

Sub Separate_by_Parent()
Dim mySht1              As Worksheet
Dim mySht2              As Worksheet
Dim mySht3              As Worksheet
Dim myRng               As Range
Dim tmpAr               As Variant
Dim Major_CategoryAr    As Variant
Dim No_Cancel_Ar        As Variant
Dim ItemNamAr()         As String
Dim ItemNumAr()         As String
Dim JapaneseName()      As String
Dim English_Name()      As String
Dim ItemArray()         As String
Dim Residual_JPN()      As String
Dim Residual_ENG()      As String
Dim Residual_Row()      As String
Dim i                   As Long
Dim j                   As Long
Dim k                   As Long
Dim m                   As Long
Dim n                   As Long
Dim p                   As Long
Dim q                   As Long
Dim r                   As Long
Dim s                   As Long
Dim t                   As Long
Dim str_JPN_Analyse     As String
Dim str_ENG_Analyse     As String
Dim strFoodGroup        As String
Dim strFoodGroupJP      As String
Dim strFoodGroupEN      As String
Dim strSubFoodGroup     As String
Dim strSubFoodGroupJP   As String
Dim strSubFoodGroupEN   As String
Dim strSub_Category     As String
Dim strSub_CategoryJP   As String
Dim strSub_CategoryEN   As String
Dim strMajor_Category   As String
Dim strMajor_CategoryJP As String
Dim strMajor_CategoryEN As String
Dim strMediumCategory   As String
Dim strMediumCategoryJP As String
Dim strMediumCategoryEN As String
Dim strMinor_Category   As String
Dim strMinor_CategoryJP As String
Dim strMinor_CategoryEN As String
Dim strDetailCategory   As String
Dim strDetailCategoryJP As String
Dim strDetailCategoryEN As String
Dim FoodGrouNum()       As String
Dim FoodGroupJP()       As String
Dim FoodGroupEN()       As String
Dim Sub_FoodGroup_JP()  As String
Dim Sub_FoodGroup_EN()  As String
Dim Sub_Group_JP_Row()  As String
Dim Sub_Group_EN_Row()  As String
Dim Sub_Category_JPN()  As String
Dim Sub_Category_ENG()  As String
Dim SubCategory_RowJ()  As String
Dim SubCategory_RowE()  As String
Dim Major_CategoryJP()  As String
Dim Major_CategoryEN()  As String
Dim Major_CategoryLT()  As String
Dim Major_JPN_RowNum()  As String
Dim Major_ENG_RowNum()  As String
Dim Major_Temp_Array()  As String
Dim MediumCategoryJP()  As String
Dim MediumCategoryEN()  As String
Dim Med_JP_RowNumber()  As Long
Dim Med_EN_RowNumber()  As Long
Dim Med_Category_JPN()  As String
Dim Med_Category_ENG()  As String
Dim MediumCategoryAr()  As String
Dim Minor_CategoryJP()  As String
Dim Minor_CategoryEN()  As String
Dim Min_JP_RowNumber()  As Long
Dim Min_EN_RowNumber()  As Long
Dim Min_Category_JPN()  As String
Dim Min_Category_ENG()  As String
Dim Minor_CategoryAr()  As String
Dim DetailCategoryJP()  As String
Dim DetailCategoryEN()  As String
Const Ptn_FoodGroupNum  As String = "^([0-9]|[0-9]{2})$"
Const Ptn_Jpn_Eng_Mix   As String = "^[^A-Za-z0-9]+(\([^A-Za-z0-9]+\))?([A-Za-z])"
Const Ptn_JapaneseOnly  As String = "^[^A-Za-z0-9\*]+(\([^A-Za-z0-9]+\))?$"
Const Ptn_Upper_Lower   As String = "[A-Za-z\s:\-,]+" '"[A-Za-z,\s]+"
Const Ptn_Upper_Only    As String = "[A-Z]+"
Const Ptn_Lower_Only    As String = "^[a-z]+$"
Const Ptn_AngleStart    As String = "^[\<<]"
Const Ptn_Angle_JPN     As String = "[<<].+[>>]"
Const Ptn_Angle_ENG     As String = "[<<].+[>>]"
Const Ptn_RoundStart    As String = "^[\((][^0-9]+"
Const Ptn_Round_JPN     As String = "[\((][^A-Za-z0-9]+[\))]"
Const Ptn_Round_ENG     As String = "[\((][A-Za-z\s]+[\))]"
Const Ptn_SquareStart   As String = "^\["
Const Ptn_Square_JPN    As String = "\[[^A-Za-z0-9]+\]"
Const Ptn_Square_ENG    As String = "\[[A-Za-z\s:\-,]+(\]|])"
Dim RegExp_MedCategory      As Object
Dim RegExp_Foods_Group      As Object
Dim RegExp_Jpn_Eng_Mix      As Object
Dim RegExp_JapaneseOnly     As Object
Dim RegExp_English_Only     As Object
Dim RegExp_Upper_Lower      As Object
Dim RegExp_Upper_Only       As Object
Dim RegExp_Lower_Only       As Object
Dim RegExp_Angle_Bracket    As Object
Dim RegExp_Angle_Bracket_JP As Object
Dim RegExp_Angle_Bracket_EN As Object
Dim RegExp_Round_Bracket    As Object
Dim RegExp_Round_Bracket_JP As Object
Dim RegExp_Round_Bracket_EN As Object
Dim RegExp_SquareBracket    As Object
Dim RegExp_SquareBracket_JP As Object
Dim RegExp_SquareBracket_EN As Object
Dim RegExp_5_Number     As Object
Dim RegExp_Japanese     As Object
Dim RegExp_Alphabet     As Object
Dim myMatches           As Object
Dim myMatch             As Object
Const Ptn_5_Number      As String = "^[0-9]{5}$"
Const Ptn_Japanese      As String = "[^A-Za-z0-9]{2,}"
Const Ptn_Alphabet      As String = "^[A-Za-z]{2,}"
Dim CEREALS             As Long
Dim POTATOES            As Long
Dim SUGARS              As Long
Dim PULSES              As Long
Dim NUTS                As Long
Dim VEGETABLES          As Long
Dim FRUITS              As Long
Dim MUSHROOMS           As Long
Dim ALGAE               As Long
Dim FISHES              As Long
Dim MEATS               As Long
Dim EGGS                As Long
Dim MILK                As Long
Dim OIL                 As Long
Dim CONFECTIONERIES     As Long
Dim BEVERAGES           As Long
Dim SEASONINGS          As Long
Dim PREPARED            As Long
Dim RegExpJapaneseName  As Object
Const Ptn_JapaneseName  As String = "^([0-9%]{1,3})?[^A-Za-z0-9]+"
Set RegExpJapaneseName = CreateObject("VBScript.RegExp")
With RegExpJapaneseName
    .Pattern = Ptn_JapaneseName
    .IgnoreCase = True
    .Global = True
End With
Dim RegExp_EnglishName  As Object
Dim Ptn_EnglishName   As String
Ptn_EnglishName = "^[A-Za-z0-9%\.,\-'" & ChrW(&HC0) & "-" & ChrW(&HFF) & "]+$"
Set RegExp_EnglishName = CreateObject("VBScript.RegExp")
With RegExp_EnglishName
    .Pattern = Ptn_EnglishName
    .IgnoreCase = True
    .Global = True
End With
Set RegExp_5_Number = CreateObject("VBScript.RegExp")
Set RegExp_MedCategory = CreateObject("VBScript.RegExp")
Set RegExp_Foods_Group = CreateObject("VBScript.RegExp")
Set RegExp_Jpn_Eng_Mix = CreateObject("VBScript.RegExp")
Set RegExp_JapaneseOnly = CreateObject("VBScript.RegExp")
Set RegExp_English_Only = CreateObject("VBScript.RegExp")
Set RegExp_Upper_Lower = CreateObject("VBScript.RegExp")
Set RegExp_Upper_Only = CreateObject("VBScript.RegExp")
Set RegExp_Lower_Only = CreateObject("VBScript.RegExp")
Set RegExp_Angle_Bracket = CreateObject("VBScript.RegExp")
Set RegExp_Angle_Bracket_JP = CreateObject("VBScript.RegExp")
Set RegExp_Angle_Bracket_EN = CreateObject("VBScript.RegExp")
Set RegExp_Round_Bracket = CreateObject("VBScript.RegExp")
Set RegExp_Round_Bracket_JP = CreateObject("VBScript.RegExp")
Set RegExp_Round_Bracket_EN = CreateObject("VBScript.RegExp")
Set RegExp_SquareBracket = CreateObject("VBScript.RegExp")
Set RegExp_SquareBracket_JP = CreateObject("VBScript.RegExp")
Set RegExp_SquareBracket_EN = CreateObject("VBScript.RegExp")
Set RegExp_Japanese = CreateObject("VBScript.RegExp")
Set RegExp_Alphabet = CreateObject("VBScript.RegExp")
    With RegExp_5_Number
        .Pattern = Ptn_5_Number
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_Angle_Bracket
        .Pattern = Ptn_AngleStart
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_Angle_Bracket_JP
        .Pattern = Ptn_Angle_JPN
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_Angle_Bracket_EN
        .Pattern = Ptn_Angle_ENG
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_Round_Bracket
        .Pattern = Ptn_RoundStart
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_Round_Bracket_JP
        .Pattern = Ptn_Round_JPN
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_Round_Bracket_EN
        .Pattern = Ptn_Round_ENG
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_SquareBracket
        .Pattern = Ptn_SquareStart
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_SquareBracket_JP
        .Pattern = Ptn_Square_JPN
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_SquareBracket_EN
        .Pattern = Ptn_Square_ENG
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_Japanese
        .Pattern = Ptn_Japanese
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_Alphabet
        .Pattern = Ptn_Alphabet
        .IgnoreCase = False
        .Global = True
    End With
    With RegExp_JapaneseOnly
        .Pattern = Ptn_JapaneseOnly
        .IgnoreCase = True
        .Global = True
    End With
Set mySht1 = Worksheets("Sheet1")
Set mySht2 = Worksheets("Sheet2")
Set myRng = mySht1.UsedRange
tmpAr = myRng
Major_CategoryAr = MajorCategoryAr(mySht2)
ReDim Preserve Major_CategoryAr(UBound(Major_CategoryAr), UBound(Major_CategoryAr, 2) + 2)
m = 0
For i = LBound(tmpAr) To UBound(tmpAr)
    For n = LBound(Major_CategoryAr) To UBound(Major_CategoryAr)
        If Major_CategoryAr(n, 0) = tmpAr(i, 1) Then
            Major_CategoryAr(n, 11) = i
        End If
        If Major_CategoryAr(n, 1) = tmpAr(i, 1) Then
            Major_CategoryAr(n, 12) = i
        End If
    Next n
Next i
m = 0
n = 0
p = 0
q = 0
No_Cancel_Ar = NoCancelArray(mySht1)
For r = LBound(No_Cancel_Ar) To UBound(No_Cancel_Ar)
For i = No_Cancel_Ar(r, 0) To No_Cancel_Ar(r, 1)
        str_JPN_Analyse = ""
        str_ENG_Analyse = ""
        On Error Resume Next
        For k = 1 To 5
            str_JPN_Analyse = str_JPN_Analyse & tmpAr(i, k)
            str_ENG_Analyse = str_ENG_Analyse & " " & tmpAr(i + 1, k)
            str_ENG_Analyse = Replace(str_ENG_Analyse, "  ", " ")
        Next k
        For k = 1 To 3
            str_ENG_Analyse = str_ENG_Analyse & " " & tmpAr(i + 2, k)
            str_ENG_Analyse = Replace(str_ENG_Analyse, "  ", " ")
        Next k
        On Error GoTo 0
        str_ENG_Analyse = Trim(str_ENG_Analyse)
        Select Case True
        Case RegExp_Angle_Bracket.Test(str_JPN_Analyse) And _
             RegExp_Angle_Bracket.Test(str_ENG_Analyse)
            ReDim Preserve Sub_FoodGroup_JP(p)
            ReDim Preserve Sub_FoodGroup_EN(p)
            ReDim Preserve Sub_Group_JP_Row(p)
            ReDim Preserve Sub_Group_EN_Row(p)
            Set myMatches = RegExp_Angle_Bracket_JP.Execute(str_JPN_Analyse)
            Sub_FoodGroup_JP(p) = myMatches.Item(0).Value
            Sub_Group_JP_Row(p) = i
            Set myMatches = RegExp_Angle_Bracket_EN.Execute(str_ENG_Analyse)
            Sub_FoodGroup_EN(p) = myMatches.Item(0).Value
            Sub_FoodGroup_EN(p) = Replace(Sub_FoodGroup_EN(p), "<", "<")
            Sub_FoodGroup_EN(p) = Replace(Sub_FoodGroup_EN(p), ">", ">")
            Sub_Group_EN_Row(p) = i + 1
            p = p + 1
        Case RegExp_Round_Bracket_JP.Test(str_JPN_Analyse) And _
             RegExp_Round_Bracket_EN.Test(str_ENG_Analyse)
            ReDim Preserve Sub_Category_JPN(n)
            ReDim Preserve Sub_Category_ENG(n)
            ReDim Preserve SubCategory_RowJ(n)
            ReDim Preserve SubCategory_RowE(n)
            Set myMatches = RegExp_Round_Bracket_JP.Execute(str_JPN_Analyse)
            Sub_Category_JPN(n) = myMatches.Item(0).Value
            Sub_Category_JPN(n) = Replace(Sub_Category_JPN(n), "(", "(")
            Sub_Category_JPN(n) = Replace(Sub_Category_JPN(n), ")", ")")
            SubCategory_RowJ(n) = i
            Set myMatches = RegExp_Round_Bracket_EN.Execute(str_ENG_Analyse)
            Sub_Category_ENG(n) = myMatches.Item(0).Value
            Sub_Category_ENG(n) = Replace(Sub_Category_ENG(n), "(", "(")
            Sub_Category_ENG(n) = Replace(Sub_Category_ENG(n), ")", ")")
            SubCategory_RowE(n) = i + 1
            n = n + 1
        Case RegExp_SquareBracket_JP.Test(str_JPN_Analyse) And _
             RegExp_SquareBracket_EN.Test(str_ENG_Analyse)
            ReDim Preserve MediumCategoryJP(m)
            ReDim Preserve Med_JP_RowNumber(m)
            ReDim Preserve MediumCategoryEN(m)
            ReDim Preserve Med_EN_RowNumber(m)
            Set myMatches = RegExp_SquareBracket_JP.Execute(str_JPN_Analyse)
            MediumCategoryJP(m) = myMatches.Item(0).Value
            Med_JP_RowNumber(m) = i
            Set myMatches = RegExp_SquareBracket_EN.Execute(str_ENG_Analyse)
            MediumCategoryEN(m) = myMatches.Item(0).Value
            Med_EN_RowNumber(m) = i + 1
            m = m + 1
        Case RegExp_Japanese.Test(str_JPN_Analyse) And _
             RegExp_Alphabet.Test(str_ENG_Analyse)
            ReDim Preserve Major_CategoryJP(q)
            ReDim Preserve Major_CategoryEN(q)
            ReDim Preserve Major_JPN_RowNum(q)
            ReDim Preserve Major_ENG_RowNum(q)
            Set myMatches = RegExp_Japanese.Execute(str_JPN_Analyse)
            Major_CategoryJP(q) = myMatches.Item(0).Value
            Major_JPN_RowNum(q) = i
            Set myMatches = RegExp_Alphabet.Execute(str_ENG_Analyse)
            Major_CategoryEN(q) = myMatches.Item(0).Value
            Major_ENG_RowNum(q) = i + 1
            q = q + 1
        Case Else
        End Select
Next i
Next r
ReDim Major_Temp_Array(UBound(Major_CategoryJP), 5)
For q = LBound(Major_Temp_Array) To UBound(Major_Temp_Array) - 1
    Major_Temp_Array(q, 0) = Major_CategoryJP(q)
    Major_Temp_Array(q, 1) = Major_JPN_RowNum(q)
    Major_Temp_Array(q, 2) = Major_JPN_RowNum(q + 1)
    Major_Temp_Array(q, 3) = Major_CategoryEN(q)
    Major_Temp_Array(q, 4) = Major_ENG_RowNum(q)
    Major_Temp_Array(q, 5) = Major_ENG_RowNum(q + 1)
Next q
    Major_Temp_Array(q, 0) = Major_CategoryJP(UBound(Major_Temp_Array))
    Major_Temp_Array(q, 1) = Major_JPN_RowNum(UBound(Major_Temp_Array))
    Major_Temp_Array(q, 2) = 32757
    Major_Temp_Array(q, 3) = Major_CategoryEN(UBound(Major_Temp_Array))
    Major_Temp_Array(q, 4) = Major_ENG_RowNum(UBound(Major_Temp_Array))
    Major_Temp_Array(q, 5) = 32757
ReDim MediumCategoryAr(UBound(MediumCategoryJP), 5)
For m = LBound(MediumCategoryAr) To UBound(MediumCategoryAr) - 1
    MediumCategoryAr(m, 0) = MediumCategoryJP(m)
    MediumCategoryAr(m, 1) = Med_JP_RowNumber(m)
    MediumCategoryAr(m, 2) = Med_JP_RowNumber(m + 1)
    MediumCategoryAr(m, 3) = MediumCategoryEN(m)
    MediumCategoryAr(m, 4) = Med_EN_RowNumber(m)
    MediumCategoryAr(m, 5) = Med_EN_RowNumber(m + 1)
Next m
    MediumCategoryAr(m, 0) = MediumCategoryJP(UBound(MediumCategoryAr))
    MediumCategoryAr(m, 1) = Med_JP_RowNumber(UBound(MediumCategoryAr))
    MediumCategoryAr(m, 2) = 26271
    MediumCategoryAr(m, 3) = MediumCategoryEN(UBound(MediumCategoryAr))
    MediumCategoryAr(m, 4) = Med_EN_RowNumber(UBound(MediumCategoryAr))
    MediumCategoryAr(m, 5) = 26271
For m = LBound(MediumCategoryAr) To UBound(MediumCategoryAr)
    For n = LBound(Major_CategoryAr) To UBound(Major_CategoryAr)
        If CLng(MediumCategoryAr(m, 1)) > CLng(Major_CategoryAr(n, 11)) And _
           CLng(MediumCategoryAr(m, 1)) < CLng(Major_CategoryAr(n, 12)) And _
           CLng(Major_CategoryAr(n, 12)) < CLng(MediumCategoryAr(m, 2)) Then
            MediumCategoryAr(m, 2) = Major_CategoryAr(n, 12)
        End If
        If CLng(MediumCategoryAr(m, 4)) > CLng(Major_CategoryAr(n, 11)) And _
           CLng(MediumCategoryAr(m, 4)) < CLng(Major_CategoryAr(n, 12)) And _
           CLng(Major_CategoryAr(n, 12)) < CLng(MediumCategoryAr(m, 5)) Then
            MediumCategoryAr(m, 5) = Major_CategoryAr(n, 12)
            Exit For
        End If
    Next n
Next m
p = 0
For i = LBound(tmpAr) To UBound(tmpAr) - 1
    strMinor_CategoryJP = ""
    strMinor_CategoryEN = ""
    For n = LBound(Major_CategoryAr) To UBound(Major_CategoryAr)
        If RegExp_JapaneseOnly.Test(tmpAr(i, 1)) And _
       Not RegExp_5_Number.Test(tmpAr(i, 1)) And _
       Not RegExp_Round_Bracket.Test(tmpAr(i, 1)) And _
       Not RegExp_SquareBracket.Test(tmpAr(i, 1)) And _
       Not RegExp_Angle_Bracket.Test(tmpAr(i, 1)) And _
           InStr(tmpAr(i, 1), Major_CategoryAr(n, 8)) <> 0 And _
           InStr(tmpAr(i + 1, 1), Major_CategoryAr(n, 9)) <> 0 And _
           i >= Major_CategoryAr(n, 11) And _
           i <= Major_CategoryAr(n, 12) Then
            ReDim Preserve Minor_CategoryJP(p)
            ReDim Preserve Minor_CategoryEN(p)
            ReDim Preserve Min_JP_RowNumber(p)
            ReDim Preserve Min_EN_RowNumber(p)
            For k = 1 To 2
                strMinor_CategoryJP = strMinor_CategoryJP & tmpAr(i, k)
                strMinor_CategoryEN = strMinor_CategoryEN & " " & tmpAr(i + 1, k)
                strMinor_CategoryEN = Trim(strMinor_CategoryEN)
            Next k
            Set myMatches = RegExp_JapaneseOnly.Execute(strMinor_CategoryJP)
            Minor_CategoryJP(p) = strMinor_CategoryJP
            Min_JP_RowNumber(p) = i
            Set myMatches = RegExp_Upper_Lower.Execute(strMinor_CategoryEN)
            Minor_CategoryEN(p) = strMinor_CategoryEN
            Min_EN_RowNumber(p) = i + 1
            p = p + 1
        Else
        End If
    Next n
Next i
j = 0
For i = LBound(tmpAr) To UBound(tmpAr)
    strFoodGroup = ""
    strSubFoodGroup = ""
    strSub_Category = ""
    strMajor_Category = ""
    strMinor_Category = ""
    strDetailCategory = ""
    If RegExp_5_Number.Test(tmpAr(i, 1)) And tmpAr(i, 2) <> "(欠番)" Then
        ReDim Preserve ItemNamAr(j)
        ReDim Preserve ItemNumAr(j)
        ReDim Preserve FoodGrouNum(j)
        ReDim Preserve FoodGroupJP(j)
        ReDim Preserve FoodGroupEN(j)
        ReDim Preserve Sub_FoodGroup_JP(j)
        ReDim Preserve Sub_FoodGroup_EN(j)
        ReDim Preserve Sub_Category_JPN(j)
        ReDim Preserve Sub_Category_ENG(j)
        ReDim Preserve Major_CategoryJP(j)
        ReDim Preserve Major_CategoryEN(j)
        ReDim Preserve Major_CategoryLT(j)
        ReDim Preserve Med_Category_JPN(j)
        ReDim Preserve Med_Category_ENG(j)
        ReDim Preserve Minor_CategoryJP(j)
        ReDim Preserve Minor_CategoryEN(j)
        ReDim Preserve DetailCategoryJP(j)
        ReDim Preserve DetailCategoryEN(j)
        ReDim Preserve JapaneseName(j)
        ReDim Preserve English_Name(j)
        ItemNamAr(j) = tmpAr(i, 1)
        ItemNumAr(j) = i
        Select Case True
            Case Left(tmpAr(i, 1), 2) = "01"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "穀類"
                FoodGroupEN(j) = "CEREALS"
                CEREALS = CEREALS + 1
            Case Left(tmpAr(i, 1), 2) = "02"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "いも及びでん粉類"
                FoodGroupEN(j) = "POTATOES AND STARCHES"
                POTATOES = POTATOES + 1
            Case Left(tmpAr(i, 1), 2) = "03"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "砂糖及び甘味類"
                FoodGroupEN(j) = "SUGARS"
                SUGARS = SUGARS + 1
            Case Left(tmpAr(i, 1), 2) = "04"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "豆類"
                FoodGroupEN(j) = "PULSES"
                PULSES = PULSES + 1
            Case Left(tmpAr(i, 1), 2) = "05"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "種実類"
                FoodGroupEN(j) = "NUTS AND SEEDS"
                NUTS = NUTS + 1
            Case Left(tmpAr(i, 1), 2) = "06"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "野菜類"
                FoodGroupEN(j) = "VEGETABLES"
                VEGETABLES = VEGETABLES + 1
            Case Left(tmpAr(i, 1), 2) = "07"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "果実類"
                FoodGroupEN(j) = "FRUITS"
                FRUITS = FRUITS + 1
            Case Left(tmpAr(i, 1), 2) = "08"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "きのこ類"
                FoodGroupEN(j) = "MUSHROOMS"
                MUSHROOMS = MUSHROOMS + 1
            Case Left(tmpAr(i, 1), 2) = "09"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "藻類"
                FoodGroupEN(j) = "ALGAE"
                ALGAE = ALGAE + 1
            Case Left(tmpAr(i, 1), 2) = "10"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "魚介類"
                FoodGroupEN(j) = "FISHES AND SHELLFISHES"
                FISHES = FISHES + 1
            Case Left(tmpAr(i, 1), 2) = "11"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "肉類"
                FoodGroupEN(j) = "MEATS"
                MEATS = MEATS + 1
            Case Left(tmpAr(i, 1), 2) = "12"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "卵類"
                FoodGroupEN(j) = "EGGS"
                EGGS = EGGS + 1
            Case Left(tmpAr(i, 1), 2) = "13"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "乳類"
                FoodGroupEN(j) = "MILKS"
                MILK = MILK + 1
            Case Left(tmpAr(i, 1), 2) = "14"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "油脂類"
                FoodGroupEN(j) = "FATS AND OILS"
                OIL = OIL + 1
            Case Left(tmpAr(i, 1), 2) = "15"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "菓子類"
                FoodGroupEN(j) = "CONFECTIONERIES"
                CONFECTIONERIES = CONFECTIONERIES + 1
            Case Left(tmpAr(i, 1), 2) = "16"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "し好飲料類"
                FoodGroupEN(j) = "BEVERAGES"
                BEVERAGES = BEVERAGES + 1
            Case Left(tmpAr(i, 1), 2) = "17"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "調味料及び香辛料類"
                FoodGroupEN(j) = "SEASONINGS AND SPICES"
                SEASONINGS = SEASONINGS + 1
            Case Left(tmpAr(i, 1), 2) = "18"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "調理加工食品類"
                FoodGroupEN(j) = "PREPARED FOODS"
                PREPARED = PREPARED + 1
            Case Else
        End Select
        If RegExpJapaneseName.Test(tmpAr(i, 2)) Then
            Set myMatches = RegExpJapaneseName.Execute(tmpAr(i, 2))
            JapaneseName(j) = myMatches.Item(0).Value
        End If
        For t = 1 To 6
            If RegExp_EnglishName.Test(tmpAr(i + 1, t)) Then
                English_Name(j) = English_Name(j) & " " & tmpAr(i + 1, t)
                English_Name(j) = Trim(English_Name(j))
            Else
                Exit For
            End If
        Next t
        For k = LBound(Major_CategoryAr) To UBound(Major_CategoryAr)
            If CLng(tmpAr(i, 1)) >= CLng(Major_CategoryAr(k, 0)) _
           And CLng(tmpAr(i, 1)) <= CLng(Major_CategoryAr(k, 1)) Then
                Sub_FoodGroup_JP(j) = Major_CategoryAr(k, 4)
                Sub_FoodGroup_EN(j) = Major_CategoryAr(k, 5)
                Sub_Category_JPN(j) = Major_CategoryAr(k, 6)
                Sub_Category_ENG(j) = Major_CategoryAr(k, 7)
                Major_CategoryJP(j) = Major_CategoryAr(k, 8)
                Major_CategoryEN(j) = Major_CategoryAr(k, 9)
                Major_CategoryLT(j) = Major_CategoryAr(k, 10)
                For m = LBound(MediumCategoryAr) To UBound(MediumCategoryAr)
                    If i >= CLng(MediumCategoryAr(m, 1)) And _
                       i <= CLng(MediumCategoryAr(m, 2)) Then
                        Med_Category_JPN(j) = MediumCategoryAr(m, 0)
                    End If
                    If i >= CLng(MediumCategoryAr(m, 4)) And _
                       i <= CLng(MediumCategoryAr(m, 5)) Then
                        Med_Category_ENG(j) = MediumCategoryAr(m, 3)
                    End If
                Next m
            Else
            End If
        Next k
    Else
        j = j - 1
    End If
    j = j + 1
Next i
ReDim ItemArray(UBound(ItemNamAr), 14)
For i = LBound(ItemArray) To UBound(ItemArray)
    ItemArray(i, 0) = ItemNamAr(i)
    ItemArray(i, 1) = FoodGrouNum(i)
    ItemArray(i, 2) = FoodGroupJP(i)
    ItemArray(i, 3) = FoodGroupEN(i)
    ItemArray(i, 4) = Sub_FoodGroup_JP(i)
    ItemArray(i, 5) = Sub_FoodGroup_EN(i)
    ItemArray(i, 6) = Sub_Category_JPN(i)
    ItemArray(i, 7) = Sub_Category_ENG(i)
    ItemArray(i, 8) = Major_CategoryJP(i)
    ItemArray(i, 9) = Major_CategoryEN(i)
    ItemArray(i, 10) = Major_CategoryLT(i)
    ItemArray(i, 11) = Med_Category_JPN(i)
    ItemArray(i, 12) = Med_Category_ENG(i)
    ItemArray(i, 13) = JapaneseName(i)
    ItemArray(i, 14) = English_Name(i)
Next i
Set mySht3 = Worksheets.Add
With mySht3
    .Name = "Result"
    .Range("A1").Value = "ItemNumber"
    .Range("B1").Value = "食品群番号"
    .Range("C1").Value = "食品群"
    .Range("D1").Value = "FoodGroup"
    .Range("E1").Value = "副分類"
    .Range("F1").Value = "SubFoodGroup"
    .Range("G1").Value = "区分"
    .Range("H1").Value = "SubCategory"
    .Range("I1").Value = "大分類"
    .Range("J1").Value = "MajorCategory"
    .Range("K1").Value = "AcademicName"
    .Range("L1").Value = "中分類"
    .Range("M1").Value = "MediumCategory"
    .Range("N1").Value = "小分類・細分"
    .Range("O1").Value = "MinorCategory_Details"
    .Range("A2:O1879").Value = ItemArray
End With
End Sub

Function NoCancelArray(ByRef Sh As Worksheet) As Variant
Dim mySht           As Worksheet
Dim myRng           As Range
Dim tmpAr           As Variant
Dim i               As Long
Dim j               As Long
Dim RegExpCancel    As Object
Dim RegExp_Exit     As Object
Const StrCancel     As String = "^(1\)|residues)$"
Dim CancelItem()    As String
Dim CancelRow1()    As String
Dim CancelRow2()    As String
Dim myCancelAr()    As String
Dim Cancel_Array()  As String
Set RegExpCancel = CreateObject("VBScript.RegExp")
With RegExpCancel
    .Pattern = StrCancel
    .IgnoreCase = True
    .Global = True
End With
Set mySht = Sh
Set myRng = mySht.UsedRange
tmpAr = myRng
j = 0
For i = LBound(tmpAr) To UBound(tmpAr)
    If RegExpCancel.Test(tmpAr(i, 1)) Then
        ReDim Preserve CancelItem(j)
        ReDim Preserve CancelRow1(i)
        CancelItem(j) = tmpAr(i, 1)
        CancelRow1(j) = i
        j = j + 1
    End If
Next i
ReDim myCancelAr(UBound(CancelItem), 1)
For j = LBound(myCancelAr) To UBound(myCancelAr)
    myCancelAr(j, 0) = CancelItem(j)
    myCancelAr(j, 1) = CancelRow1(j)
Next j
ReDim Preserve myCancelAr(UBound(myCancelAr), 2)
j = 0
For i = LBound(myCancelAr) To UBound(myCancelAr) - 1
    If myCancelAr(i, 0) = "1)" Then
        If myCancelAr(i + 2, 0) = "residues" Then
            myCancelAr(i, 2) = myCancelAr(i + 2, 1)
        Else
            myCancelAr(i, 2) = myCancelAr(i + 1, 1)
        End If
        j = j + 1
    End If
Next i
Erase CancelRow1
j = 0
ReDim CancelRow1(j)
ReDim CancelRow2(j)
CancelRow1(j) = myCancelAr(j, 1)
CancelRow2(j) = myCancelAr(j, 2)
For i = LBound(myCancelAr) + 1 To UBound(myCancelAr)
    If myCancelAr(i, 0) = "1)" And _
       myCancelAr(i - 1, 0) <> "1)" Then
        j = j + 1
        ReDim Preserve CancelRow1(j)
        ReDim Preserve CancelRow2(j)
        CancelRow1(j) = myCancelAr(i, 1)
        CancelRow2(j) = myCancelAr(i, 2)
    End If
Next i
ReDim Cancel_Array(UBound(CancelRow1), 1)
j = 0
For j = LBound(Cancel_Array) To UBound(Cancel_Array)
    Cancel_Array(j, 0) = CancelRow1(j)
    Cancel_Array(j, 1) = CancelRow2(j)
Next j
j = 0
Cancel_Array(j, 0) = 1
Cancel_Array(j, 1) = CancelRow1(j)
For j = LBound(Cancel_Array) + 1 To UBound(Cancel_Array)
    Cancel_Array(j, 0) = CancelRow2(j - 1)
    Cancel_Array(j, 1) = CancelRow1(j)
Next j
NoCancelArray = Cancel_Array
End Function

References:
CSV file of the ‘Standard Tables of Food Composition in Japan 2010′
Classify the Item_Number of the ‘Standard Tables of Food Composition in Japan 2010′, Part 2

日本食品標準成分表2010の食品番号をカテゴリー分類する その1

日本食品標準成分表2010の食品番号を分類するの記事で食品番号を分類する記事を掲載しましたが,不十分な分類しか出来ておりませんでした.今回は既に日本語の完成した分類を見つけましたので,それを元に英語もつけて分類しました.参考にしたのは以下のファイルです.

資源調査分科会報告「日本食品標準成分表2010」について

新しいブックを用意します.”1299012_1.pdf”から”1299012_18.pdf”までのPDFの全テキストをSheet1にオプションでペーストします.その際,下の行方向に行の間隔を空けずに貼り付けます.テキストファイルウィザードで最初のカラムのデータ形式を『文字列』に変更します.原材料的食品のもととなる生物の学名でダウンロードしたPDFの全テキストを選択し,Sheet2にオプションでペーストします.テキストファイルウィザードが開くので,1/3では元のデータ形式で『カンマやタブなどの区切り文字によってフィールドごとに区切られたデータ』を選択します.テキストファイルウィザード2/3では『連続した区切り文字は1文字とみなす』のチェックを外して次に進みます.テキストファイルウィザード3/3では最初の列のデータ形式を『文字列』に変更して完了をクリックします.このEXCELブックに”Sample.xlsm”と名前を付けて保存します.

“Sample.xlsm”ブックを開き,Alt+F11キーを押下してVBEを起動します.挿入メニューから標準モジュールを選択し,下記のコードを貼り付けます.Separate_by_Parentプロシージャを実行すると”Result”という名前のシートが出来ます.

Option Explicit
Function MajorCategoryAr(ByRef Sh As Worksheet) As String()
Dim mySht               As Worksheet
Dim myRng               As Range
Dim tmpAr               As Variant
Dim StartEnd            As Variant
Dim strFoodGroup        As String
Dim strFoodGroupJP      As String
Dim strFoodGroupEN      As String
Dim strSubFoodGroup     As String
Dim strSubFoodGroupJP   As String
Dim strSubFoodGroupEN   As String
Dim strSub_Category     As String
Dim strSub_CategoryJP   As String
Dim strSub_CategoryEN   As String
Dim strMajor_Category   As String
Dim StartNumber()       As String
Dim Exit_Number()       As String
Dim FoodGroupJP()       As String
Dim FoodGroupEN()       As String
Dim Sub_FoodGroup_JP()  As String
Dim Sub_FoodGroup_EN()  As String
Dim Sub_Category_JPN()  As String
Dim Sub_Category_ENG()  As String
Dim Major_CategoryJP()  As String
Dim Major_CategoryEN()  As String
Dim Major_CategoryLT()  As String
Dim myArray()           As String
Dim i As Long
Dim j As Long
Dim k As Long
Dim n As Long
Dim RegExp_3_Digit_Num  As Object
Dim RegExp_Item_Number  As Object
Dim RegExp_SentakuHanni As Object
Dim RegExp_SubCategory1 As Object
Dim RegExp_SubCategory2 As Object
Dim RegExp_MedCategory  As Object
Dim RegExp_Foods_Group  As Object
Dim RegExp_Jpn_Eng_Mix  As Object
Dim RegExp_JapaneseOnly As Object
Dim RegExp_Upper_Lower  As Object
Dim RegExp_Upper_Only   As Object
Dim RegExp_Lower_Only   As Object
Dim RegExp_RoundBracket As Object
Dim RegExp_SquareBracket    As Object
Dim RegExp_AngleBracket As Object
Dim myMatches           As Object
Dim myMatch             As Object
Const Ptn_3_Digit_Num   As String = "[0-9]{3}$"
Const Ptn_Item_Number   As String = "^[0-9]{5}$"
Const Ptn_SentakuHanni  As String = "(,|~)"
Const Ptn_SubCategory1  As String = "^((|\().()|\))$"
Const Ptn_SubCategory2  As String = "^(<|>)$"
Const Ptn_MedCategory   As String = "^\[.\]$"
Const Ptn_FoodGroupNum  As String = "^([0-9]|[0-9]{2})$"
Const Ptn_Jpn_Eng_Mix   As String = "^[^A-Za-z0-9]+(\([^A-Za-z0-9]+\))?([A-Za-z])"
Const Ptn_JapaneseOnly  As String = "^[^A-Za-z0-9]+(\([^A-Za-z0-9]+\))?$"
Const Ptn_Upper_Lower   As String = "[A-Z][a-z]+"
Const Ptn_Upper_Only    As String = "[A-Z]+"
Const Ptn_Lower_Only    As String = "^[a-z]+$"
Const Ptn_RoundStart    As String = "^[\((]"
Const Ptn_Round_Exit    As String = "[\((][^A-Za-z0-9]+[\))]"
Const Ptn_SquareStart   As String = "^\["
Const Ptn_Square_Exit   As String = "\[[^A-Za-z0-9]+\]"
Const Ptn_AngleStart    As String = "^[\<<]"
Const Ptn_Angle_Exit    As String = "[\<<][^A-Za-z0-9]+[\>>]"
Set mySht = Sh
Set myRng = mySht.UsedRange
tmpAr = myRng
Set RegExp_3_Digit_Num = CreateObject("VBScript.RegExp")
Set RegExp_Item_Number = CreateObject("VBScript.RegExp")
Set RegExp_SentakuHanni = CreateObject("VBScript.RegExp")
Set RegExp_SubCategory1 = CreateObject("VBScript.RegExp")
Set RegExp_SubCategory2 = CreateObject("VBScript.RegExp")
Set RegExp_MedCategory = CreateObject("VBScript.RegExp")
Set RegExp_Foods_Group = CreateObject("VBScript.RegExp")
Set RegExp_Jpn_Eng_Mix = CreateObject("VBScript.RegExp")
Set RegExp_JapaneseOnly = CreateObject("VBScript.RegExp")
Set RegExp_Upper_Lower = CreateObject("VBScript.RegExp")
Set RegExp_Upper_Only = CreateObject("VBScript.RegExp")
Set RegExp_Lower_Only = CreateObject("VBScript.RegExp")
Set RegExp_RoundBracket = CreateObject("VBScript.RegExp")
Set RegExp_SquareBracket = CreateObject("VBScript.RegExp")
Set RegExp_AngleBracket = CreateObject("VBScript.RegExp")
With RegExp_3_Digit_Num
    .Pattern = "[0-9]{3}$"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_Item_Number
    .Pattern = "^[0-9]{5}$"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_SentakuHanni
    .Pattern = "(,|~)"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_SubCategory1
    .Pattern = "^((|\().()|\))$"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_SubCategory2
    .Pattern = "^(<|>)$"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_MedCategory
    .Pattern = "^\[.\]$"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_Foods_Group
    .Pattern = "^([0-9]|[0-9]{2})$"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_Jpn_Eng_Mix
    .Pattern = "^[^A-Za-z0-9]+(\([^A-Za-z0-9]+\))?([A-Za-z])"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_JapaneseOnly
    .Pattern = "^[^A-Za-z0-9]+(\([^A-Za-z0-9]+\))?$"
    .IgnoreCase = True
    .Global = True
End With
With RegExp_Upper_Lower
    .Pattern = "[A-Z][a-z]+"
    .IgnoreCase = False
    .Global = True
End With
With RegExp_Upper_Only
    .Pattern = "[A-Z]+"
    .IgnoreCase = False
    .Global = True
End With
With RegExp_Lower_Only
    .Pattern = "^[a-z]+$"
    .IgnoreCase = False
    .Global = True
End With
j = 0
For i = LBound(tmpAr) + 1 To UBound(tmpAr)
    With RegExp_RoundBracket
        .Pattern = Ptn_RoundStart
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_SquareBracket
        .Pattern = Ptn_SquareStart
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_AngleBracket
        .Pattern = Ptn_AngleStart
        .IgnoreCase = True
        .Global = True
    End With
    strFoodGroup = ""
    strSubFoodGroup = ""
    strSub_Category = ""
    strMajor_Category = ""
    ReDim Preserve StartNumber(j)
    ReDim Preserve Exit_Number(j)
    ReDim Preserve FoodGroupJP(j)
    ReDim Preserve FoodGroupEN(j)
    ReDim Preserve Sub_FoodGroup_JP(j)
    ReDim Preserve Sub_FoodGroup_EN(j)
    ReDim Preserve Sub_Category_JPN(j)
    ReDim Preserve Sub_Category_ENG(j)
    ReDim Preserve Major_CategoryJP(j)
    ReDim Preserve Major_CategoryEN(j)
    ReDim Preserve Major_CategoryLT(j)
    If RegExp_3_Digit_Num.Test(tmpAr(i, 1)) Then
        Select Case True
        Case RegExp_Item_Number.Test(tmpAr(i, 1))
            StartNumber(j) = tmpAr(i, 1)
            Exit_Number(j) = tmpAr(i, 1)
        Case RegExp_SentakuHanni.Test(tmpAr(i, 1))
            StartEnd = StartExit(tmpAr(i, 1))
            StartNumber(j) = StartEnd(0)
            Exit_Number(j) = StartEnd(1)
            Erase StartEnd
        End Select
        FoodGroupJP(j) = strFoodGroupJP
        FoodGroupEN(j) = strFoodGroupEN
        If (i >= 19 And i <= 27) _
        Or (i >= 370 And i <= 596) _
        Or (i >= 599 And i <= 626) _
        Or (i >= 635 And i <= 639) _
        Or (i >= 646 And i <= 668) _
        Then
            Sub_FoodGroup_JP(j) = strSubFoodGroupJP
            Sub_FoodGroup_EN(j) = strSubFoodGroupEN
        End If
        If tmpAr(i, 2) = "" Then
            Sub_Category_JPN(j) = strSub_CategoryJP
            Sub_Category_ENG(j) = strSub_CategoryEN
        End If
        For k = 2 To 8
            strMajor_Category = strMajor_Category & " " & tmpAr(i, k)
        Next k
        strMajor_Category = Trim(strMajor_Category)
        On Error Resume Next
        For k = 1 To 8
            If RegExp_Lower_Only.Test(tmpAr(i + 1, 1)) _
            And Not RegExp_SubCategory1.Test(tmpAr(i + 1, 1)) _
            And Not RegExp_SubCategory2.Test(tmpAr(i + 1, 1)) _
            And Not RegExp_Foods_Group.Test(tmpAr(i + 1, 1)) _
            And Not RegExp_3_Digit_Num.Test(tmpAr(i + 1, 1)) _
            Then
                strMajor_Category = strMajor_Category & " " & tmpAr(i + 1, k)
            End If
        Next k
        On Error GoTo 0
        strMajor_Category = Trim(strMajor_Category)
        If RegExp_Jpn_Eng_Mix.Test(strMajor_Category) Then
            StartEnd = Separate_Jpn_Eng(strMajor_Category)
            Major_CategoryJP(j) = StartEnd(0)
            Erase StartEnd
            Set myMatches = RegExp_Upper_Lower.Execute(strMajor_Category)
            Major_CategoryEN(j) = Mid(strMajor_Category, _
                                    myMatches.Item(0).firstindex + 1, _
                                    myMatches.Item(myMatches.Count - 1).firstindex _
                                  - myMatches.Item(0).firstindex - 1)
            Set myMatch = myMatches.Item(myMatches.Count - 1)
            Major_CategoryLT(j) = Mid(strMajor_Category, myMatch.firstindex + 1)
        Else
        End If
    Else
        Select Case True
        Case RegExp_Foods_Group.Test(tmpAr(i, 1))
            For k = 2 To 8
                strFoodGroup = strFoodGroup & " " & tmpAr(i, k)
            Next k
            strFoodGroup = Trim(strFoodGroup)
            Select Case True
            Case RegExp_Jpn_Eng_Mix.Test(strFoodGroup)
                Set myMatches = RegExp_Jpn_Eng_Mix.Execute(strFoodGroup)
                Set myMatch = myMatches.Item(0)
                strFoodGroupJP = Left(strFoodGroup, myMatches.Item(0).Length - 1)
                strFoodGroupEN = Mid(strFoodGroup, myMatches.Item(0).Length)
            Case RegExp_JapaneseOnly.Test(strFoodGroup)
                Set myMatches = RegExp_JapaneseOnly.Execute(strFoodGroup)
                Set myMatch = myMatches.Item(0)
                strFoodGroupJP = Left(strFoodGroup, myMatches.Item(0).Length - 1)
                strFoodGroupEN = Mid(strFoodGroup, myMatches.Item(0).Length)
            Case Else
            End Select
        Case RegExp_AngleBracket.Test(tmpAr(i, 1))
            For k = 1 To 8
                strSubFoodGroup = strSubFoodGroup & " " & tmpAr(i, k)
            Next k
            strSubFoodGroup = Trim(strSubFoodGroup)
            With RegExp_AngleBracket
                .Pattern = Ptn_Angle_Exit
                .IgnoreCase = True
                .Global = True
            End With
            Set myMatches = RegExp_AngleBracket.Execute(strSubFoodGroup)
            strSubFoodGroupJP = myMatches.Item(0).Value
            strSubFoodGroupEN = Mid(strSubFoodGroup, myMatches.Item(0).Length + 2)
            strSubFoodGroupEN = Replace(strSubFoodGroupEN, "<", "<")
            strSubFoodGroupEN = Replace(strSubFoodGroupEN, ">", ">")
        Case RegExp_RoundBracket.Test(tmpAr(i, 1))
            For k = 1 To 8
                strSub_Category = strSub_Category & " " & tmpAr(i, k)
            Next k
            strSub_Category = Trim(strSub_Category)
            With RegExp_RoundBracket
                .Pattern = Ptn_Round_Exit
                .IgnoreCase = True
                .Global = True
            End With
            Set myMatches = RegExp_RoundBracket.Execute(strSub_Category)
            On Error Resume Next
            strSub_CategoryJP = myMatches.Item(0).Value
            strSub_CategoryJP = Replace(strSub_CategoryJP, "(", "(")
            strSub_CategoryJP = Replace(strSub_CategoryJP, ")", ")")
            strSub_CategoryEN = Mid(strSub_Category, myMatches.Item(0).Length + 2)
            strSub_CategoryEN = Replace(strSub_CategoryEN, "(", "(")
            strSub_CategoryEN = Replace(strSub_CategoryEN, ")", ")")
            On Error GoTo 0
        Case Else
        End Select
        j = j - 1
    End If
    j = j + 1
Next i
ReDim myArray(UBound(StartNumber), 10)
For n = LBound(myArray) To UBound(myArray)
    myArray(n, 0) = StartNumber(n)
    myArray(n, 1) = Exit_Number(n)
    myArray(n, 2) = FoodGroupJP(n)
    myArray(n, 3) = FoodGroupEN(n)
    myArray(n, 4) = Sub_FoodGroup_JP(n)
    myArray(n, 5) = Sub_FoodGroup_EN(n)
    myArray(n, 6) = Sub_Category_JPN(n)
    myArray(n, 7) = Sub_Category_ENG(n)
    myArray(n, 8) = Major_CategoryJP(n)
    myArray(n, 9) = Major_CategoryEN(n)
    myArray(n, 10) = Major_CategoryLT(n)
Next n
MajorCategoryAr = myArray
End Function

Function StartExit(ByVal InputStr As String) As String()
    Dim str     As String
    Dim Ar()    As String
    str = InputStr
    ReDim Ar(1)
    Ar(0) = Left(str, 5)
    Ar(1) = Left(str, 2) & Right(str, 3)
    StartExit = Ar
End Function

Function Separate_Jpn_Eng(ByVal InputStr As String) As String()
    Dim str                 As String
    Dim Ar()                As String
    Dim RegExp_Jpn_Eng_Mix  As Object
    Dim myMatches           As Object
    Dim myMatch             As Object
    Const Ptn_Jpn_Eng_Mix   As String = "^[^A-Za-z0-9]+(\([^A-Za-z0-9]+\))?([A-Za-z])"
    str = InputStr
    ReDim Ar(1)
    Set RegExp_Jpn_Eng_Mix = CreateObject("VBScript.RegExp")
    With RegExp_Jpn_Eng_Mix
        .Pattern = Ptn_Jpn_Eng_Mix
        .IgnoreCase = True
        .Global = True
    End With
    Set myMatches = RegExp_Jpn_Eng_Mix.Execute(str)
    For Each myMatch In myMatches
        If myMatches.Count > 0 Then
            Ar(0) = Left(str, myMatches.Item(0).Length - 1)
            Ar(1) = Mid(str, myMatches.Item(0).Length)
        End If
    Next myMatch
    Separate_Jpn_Eng = Ar
End Function

Sub Separate_by_Parent()
Dim mySht1              As Worksheet
Dim mySht2              As Worksheet
Dim mySht3              As Worksheet
Dim myRng               As Range
Dim tmpAr               As Variant
Dim Major_CategoryAr    As Variant
Dim No_Cancel_Ar        As Variant
Dim ItemNamAr()         As String
Dim ItemNumAr()         As String
Dim JapaneseName()      As String
Dim English_Name()      As String
Dim ItemArray()         As String
Dim Residual_JPN()      As String
Dim Residual_ENG()      As String
Dim Residual_Row()      As String
Dim i                   As Long
Dim j                   As Long
Dim k                   As Long
Dim m                   As Long
Dim n                   As Long
Dim p                   As Long
Dim q                   As Long
Dim r                   As Long
Dim s                   As Long
Dim t                   As Long
Dim str_JPN_Analyse     As String
Dim str_ENG_Analyse     As String
Dim strFoodGroup        As String
Dim strFoodGroupJP      As String
Dim strFoodGroupEN      As String
Dim strSubFoodGroup     As String
Dim strSubFoodGroupJP   As String
Dim strSubFoodGroupEN   As String
Dim strSub_Category     As String
Dim strSub_CategoryJP   As String
Dim strSub_CategoryEN   As String
Dim strMajor_Category   As String
Dim strMajor_CategoryJP As String
Dim strMajor_CategoryEN As String
Dim strMediumCategory   As String
Dim strMediumCategoryJP As String
Dim strMediumCategoryEN As String
Dim strMinor_Category   As String
Dim strMinor_CategoryJP As String
Dim strMinor_CategoryEN As String
Dim strDetailCategory   As String
Dim strDetailCategoryJP As String
Dim strDetailCategoryEN As String
Dim FoodGrouNum()       As String
Dim FoodGroupJP()       As String
Dim FoodGroupEN()       As String
Dim Sub_FoodGroup_JP()  As String
Dim Sub_FoodGroup_EN()  As String
Dim Sub_Group_JP_Row()  As String
Dim Sub_Group_EN_Row()  As String
Dim Sub_Category_JPN()  As String
Dim Sub_Category_ENG()  As String
Dim SubCategory_RowJ()  As String
Dim SubCategory_RowE()  As String
Dim Major_CategoryJP()  As String
Dim Major_CategoryEN()  As String
Dim Major_CategoryLT()  As String
Dim Major_JPN_RowNum()  As String
Dim Major_ENG_RowNum()  As String
Dim Major_Temp_Array()  As String
Dim MediumCategoryJP()  As String
Dim MediumCategoryEN()  As String
Dim Med_JP_RowNumber()  As Long
Dim Med_EN_RowNumber()  As Long
Dim Med_Category_JPN()  As String
Dim Med_Category_ENG()  As String
Dim MediumCategoryAr()  As String
Dim Minor_CategoryJP()  As String
Dim Minor_CategoryEN()  As String
Dim Min_JP_RowNumber()  As Long
Dim Min_EN_RowNumber()  As Long
Dim Min_Category_JPN()  As String
Dim Min_Category_ENG()  As String
Dim Minor_CategoryAr()  As String
Dim DetailCategoryJP()  As String
Dim DetailCategoryEN()  As String
Const Ptn_FoodGroupNum  As String = "^([0-9]|[0-9]{2})$"
Const Ptn_Jpn_Eng_Mix   As String = "^[^A-Za-z0-9]+(\([^A-Za-z0-9]+\))?([A-Za-z])"
Const Ptn_JapaneseOnly  As String = "^[^A-Za-z0-9\*]+(\([^A-Za-z0-9]+\))?$"
Const Ptn_Upper_Lower   As String = "[A-Za-z\s:\-,]+" '"[A-Za-z,\s]+"
Const Ptn_Upper_Only    As String = "[A-Z]+"
Const Ptn_Lower_Only    As String = "^[a-z]+$"
Const Ptn_AngleStart    As String = "^[\<<]"
Const Ptn_Angle_JPN     As String = "[<<].+[>>]"
Const Ptn_Angle_ENG     As String = "[<<].+[>>]"
Const Ptn_RoundStart    As String = "^[\((][^0-9]+"
Const Ptn_Round_JPN     As String = "[\((][^A-Za-z0-9]+[\))]"
Const Ptn_Round_ENG     As String = "[\((][A-Za-z\s]+[\))]"
Const Ptn_SquareStart   As String = "^\["
Const Ptn_Square_JPN    As String = "\[[^A-Za-z0-9]+\]"
Const Ptn_Square_ENG    As String = "\[[A-Za-z\s:\-,]+(\]|])"
Dim RegExp_MedCategory      As Object
Dim RegExp_Foods_Group      As Object
Dim RegExp_Jpn_Eng_Mix      As Object
Dim RegExp_JapaneseOnly     As Object
Dim RegExp_English_Only     As Object
Dim RegExp_Upper_Lower      As Object
Dim RegExp_Upper_Only       As Object
Dim RegExp_Lower_Only       As Object
Dim RegExp_Angle_Bracket    As Object
Dim RegExp_Angle_Bracket_JP As Object
Dim RegExp_Angle_Bracket_EN As Object
Dim RegExp_Round_Bracket    As Object
Dim RegExp_Round_Bracket_JP As Object
Dim RegExp_Round_Bracket_EN As Object
Dim RegExp_SquareBracket    As Object
Dim RegExp_SquareBracket_JP As Object
Dim RegExp_SquareBracket_EN As Object
Dim RegExp_5_Number     As Object
Dim RegExp_Japanese     As Object
Dim RegExp_Alphabet     As Object
Dim myMatches           As Object
Dim myMatch             As Object
Const Ptn_5_Number      As String = "^[0-9]{5}$"
Const Ptn_Japanese      As String = "[^A-Za-z0-9]{2,}"
Const Ptn_Alphabet      As String = "^[A-Za-z]{2,}"
Dim CEREALS             As Long
Dim POTATOES            As Long
Dim SUGARS              As Long
Dim PULSES              As Long
Dim NUTS                As Long
Dim VEGETABLES          As Long
Dim FRUITS              As Long
Dim MUSHROOMS           As Long
Dim ALGAE               As Long
Dim FISHES              As Long
Dim MEATS               As Long
Dim EGGS                As Long
Dim MILK                As Long
Dim OIL                 As Long
Dim CONFECTIONERIES     As Long
Dim BEVERAGES           As Long
Dim SEASONINGS          As Long
Dim PREPARED            As Long
Dim RegExpJapaneseName  As Object
Const Ptn_JapaneseName  As String = "^([0-9%]{1,3})?[^A-Za-z0-9]+"
Set RegExpJapaneseName = CreateObject("VBScript.RegExp")
With RegExpJapaneseName
    .Pattern = Ptn_JapaneseName
    .IgnoreCase = True
    .Global = True
End With
Dim RegExp_EnglishName  As Object
Dim Ptn_EnglishName   As String
Ptn_EnglishName = "^[A-Za-z0-9%\.,\-'" & ChrW(&HC0) & "-" & ChrW(&HFF) & "]+$"
Set RegExp_EnglishName = CreateObject("VBScript.RegExp")
With RegExp_EnglishName
    .Pattern = Ptn_EnglishName
    .IgnoreCase = True
    .Global = True
End With
Set RegExp_5_Number = CreateObject("VBScript.RegExp")
Set RegExp_MedCategory = CreateObject("VBScript.RegExp")
Set RegExp_Foods_Group = CreateObject("VBScript.RegExp")
Set RegExp_Jpn_Eng_Mix = CreateObject("VBScript.RegExp")
Set RegExp_JapaneseOnly = CreateObject("VBScript.RegExp")
Set RegExp_English_Only = CreateObject("VBScript.RegExp")
Set RegExp_Upper_Lower = CreateObject("VBScript.RegExp")
Set RegExp_Upper_Only = CreateObject("VBScript.RegExp")
Set RegExp_Lower_Only = CreateObject("VBScript.RegExp")
Set RegExp_Angle_Bracket = CreateObject("VBScript.RegExp")
Set RegExp_Angle_Bracket_JP = CreateObject("VBScript.RegExp")
Set RegExp_Angle_Bracket_EN = CreateObject("VBScript.RegExp")
Set RegExp_Round_Bracket = CreateObject("VBScript.RegExp")
Set RegExp_Round_Bracket_JP = CreateObject("VBScript.RegExp")
Set RegExp_Round_Bracket_EN = CreateObject("VBScript.RegExp")
Set RegExp_SquareBracket = CreateObject("VBScript.RegExp")
Set RegExp_SquareBracket_JP = CreateObject("VBScript.RegExp")
Set RegExp_SquareBracket_EN = CreateObject("VBScript.RegExp")
Set RegExp_Japanese = CreateObject("VBScript.RegExp")
Set RegExp_Alphabet = CreateObject("VBScript.RegExp")
    With RegExp_5_Number
        .Pattern = Ptn_5_Number
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_Angle_Bracket
        .Pattern = Ptn_AngleStart
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_Angle_Bracket_JP
        .Pattern = Ptn_Angle_JPN
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_Angle_Bracket_EN
        .Pattern = Ptn_Angle_ENG
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_Round_Bracket
        .Pattern = Ptn_RoundStart
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_Round_Bracket_JP
        .Pattern = Ptn_Round_JPN
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_Round_Bracket_EN
        .Pattern = Ptn_Round_ENG
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_SquareBracket
        .Pattern = Ptn_SquareStart
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_SquareBracket_JP
        .Pattern = Ptn_Square_JPN
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_SquareBracket_EN
        .Pattern = Ptn_Square_ENG
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_Japanese
        .Pattern = Ptn_Japanese
        .IgnoreCase = True
        .Global = True
    End With
    With RegExp_Alphabet
        .Pattern = Ptn_Alphabet
        .IgnoreCase = False
        .Global = True
    End With
    With RegExp_JapaneseOnly
        .Pattern = Ptn_JapaneseOnly
        .IgnoreCase = True
        .Global = True
    End With
Set mySht1 = Worksheets("Sheet1")
Set mySht2 = Worksheets("Sheet2")
Set myRng = mySht1.UsedRange
tmpAr = myRng
Major_CategoryAr = MajorCategoryAr(mySht2)
ReDim Preserve Major_CategoryAr(UBound(Major_CategoryAr), UBound(Major_CategoryAr, 2) + 2)
m = 0
For i = LBound(tmpAr) To UBound(tmpAr)
    For n = LBound(Major_CategoryAr) To UBound(Major_CategoryAr)
        If Major_CategoryAr(n, 0) = tmpAr(i, 1) Then
            Major_CategoryAr(n, 11) = i
        End If
        If Major_CategoryAr(n, 1) = tmpAr(i, 1) Then
            Major_CategoryAr(n, 12) = i
        End If
    Next n
Next i
m = 0
n = 0
p = 0
q = 0
No_Cancel_Ar = NoCancelArray(mySht1)
For r = LBound(No_Cancel_Ar) To UBound(No_Cancel_Ar)
For i = No_Cancel_Ar(r, 0) To No_Cancel_Ar(r, 1)
        str_JPN_Analyse = ""
        str_ENG_Analyse = ""
        On Error Resume Next
        For k = 1 To 5
            str_JPN_Analyse = str_JPN_Analyse & tmpAr(i, k)
            str_ENG_Analyse = str_ENG_Analyse & " " & tmpAr(i + 1, k)
            str_ENG_Analyse = Replace(str_ENG_Analyse, "  ", " ")
        Next k
        For k = 1 To 3
            str_ENG_Analyse = str_ENG_Analyse & " " & tmpAr(i + 2, k)
            str_ENG_Analyse = Replace(str_ENG_Analyse, "  ", " ")
        Next k
        On Error GoTo 0
        str_ENG_Analyse = Trim(str_ENG_Analyse)
        Select Case True
        Case RegExp_Angle_Bracket.Test(str_JPN_Analyse) And _
             RegExp_Angle_Bracket.Test(str_ENG_Analyse)
            ReDim Preserve Sub_FoodGroup_JP(p)
            ReDim Preserve Sub_FoodGroup_EN(p)
            ReDim Preserve Sub_Group_JP_Row(p)
            ReDim Preserve Sub_Group_EN_Row(p)
            Set myMatches = RegExp_Angle_Bracket_JP.Execute(str_JPN_Analyse)
            Sub_FoodGroup_JP(p) = myMatches.Item(0).Value
            Sub_Group_JP_Row(p) = i
            Set myMatches = RegExp_Angle_Bracket_EN.Execute(str_ENG_Analyse)
            Sub_FoodGroup_EN(p) = myMatches.Item(0).Value
            Sub_FoodGroup_EN(p) = Replace(Sub_FoodGroup_EN(p), "<", "<")
            Sub_FoodGroup_EN(p) = Replace(Sub_FoodGroup_EN(p), ">", ">")
            Sub_Group_EN_Row(p) = i + 1
            p = p + 1
        Case RegExp_Round_Bracket_JP.Test(str_JPN_Analyse) And _
             RegExp_Round_Bracket_EN.Test(str_ENG_Analyse)
            ReDim Preserve Sub_Category_JPN(n)
            ReDim Preserve Sub_Category_ENG(n)
            ReDim Preserve SubCategory_RowJ(n)
            ReDim Preserve SubCategory_RowE(n)
            Set myMatches = RegExp_Round_Bracket_JP.Execute(str_JPN_Analyse)
            Sub_Category_JPN(n) = myMatches.Item(0).Value
            Sub_Category_JPN(n) = Replace(Sub_Category_JPN(n), "(", "(")
            Sub_Category_JPN(n) = Replace(Sub_Category_JPN(n), ")", ")")
            SubCategory_RowJ(n) = i
            Set myMatches = RegExp_Round_Bracket_EN.Execute(str_ENG_Analyse)
            Sub_Category_ENG(n) = myMatches.Item(0).Value
            Sub_Category_ENG(n) = Replace(Sub_Category_ENG(n), "(", "(")
            Sub_Category_ENG(n) = Replace(Sub_Category_ENG(n), ")", ")")
            SubCategory_RowE(n) = i + 1
            n = n + 1
        Case RegExp_SquareBracket_JP.Test(str_JPN_Analyse) And _
             RegExp_SquareBracket_EN.Test(str_ENG_Analyse)
            ReDim Preserve MediumCategoryJP(m)
            ReDim Preserve Med_JP_RowNumber(m)
            ReDim Preserve MediumCategoryEN(m)
            ReDim Preserve Med_EN_RowNumber(m)
            Set myMatches = RegExp_SquareBracket_JP.Execute(str_JPN_Analyse)
            MediumCategoryJP(m) = myMatches.Item(0).Value
            Med_JP_RowNumber(m) = i
            Set myMatches = RegExp_SquareBracket_EN.Execute(str_ENG_Analyse)
            MediumCategoryEN(m) = myMatches.Item(0).Value
            Med_EN_RowNumber(m) = i + 1
            m = m + 1
        Case RegExp_Japanese.Test(str_JPN_Analyse) And _
             RegExp_Alphabet.Test(str_ENG_Analyse)
            ReDim Preserve Major_CategoryJP(q)
            ReDim Preserve Major_CategoryEN(q)
            ReDim Preserve Major_JPN_RowNum(q)
            ReDim Preserve Major_ENG_RowNum(q)
            Set myMatches = RegExp_Japanese.Execute(str_JPN_Analyse)
            Major_CategoryJP(q) = myMatches.Item(0).Value
            Major_JPN_RowNum(q) = i
            Set myMatches = RegExp_Alphabet.Execute(str_ENG_Analyse)
            Major_CategoryEN(q) = myMatches.Item(0).Value
            Major_ENG_RowNum(q) = i + 1
            q = q + 1
        Case Else
        End Select
Next i
Next r
ReDim Major_Temp_Array(UBound(Major_CategoryJP), 5)
For q = LBound(Major_Temp_Array) To UBound(Major_Temp_Array) - 1
    Major_Temp_Array(q, 0) = Major_CategoryJP(q)
    Major_Temp_Array(q, 1) = Major_JPN_RowNum(q)
    Major_Temp_Array(q, 2) = Major_JPN_RowNum(q + 1)
    Major_Temp_Array(q, 3) = Major_CategoryEN(q)
    Major_Temp_Array(q, 4) = Major_ENG_RowNum(q)
    Major_Temp_Array(q, 5) = Major_ENG_RowNum(q + 1)
Next q
    Major_Temp_Array(q, 0) = Major_CategoryJP(UBound(Major_Temp_Array))
    Major_Temp_Array(q, 1) = Major_JPN_RowNum(UBound(Major_Temp_Array))
    Major_Temp_Array(q, 2) = 32757
    Major_Temp_Array(q, 3) = Major_CategoryEN(UBound(Major_Temp_Array))
    Major_Temp_Array(q, 4) = Major_ENG_RowNum(UBound(Major_Temp_Array))
    Major_Temp_Array(q, 5) = 32757
ReDim MediumCategoryAr(UBound(MediumCategoryJP), 5)
For m = LBound(MediumCategoryAr) To UBound(MediumCategoryAr) - 1
    MediumCategoryAr(m, 0) = MediumCategoryJP(m)
    MediumCategoryAr(m, 1) = Med_JP_RowNumber(m)
    MediumCategoryAr(m, 2) = Med_JP_RowNumber(m + 1)
    MediumCategoryAr(m, 3) = MediumCategoryEN(m)
    MediumCategoryAr(m, 4) = Med_EN_RowNumber(m)
    MediumCategoryAr(m, 5) = Med_EN_RowNumber(m + 1)
Next m
    MediumCategoryAr(m, 0) = MediumCategoryJP(UBound(MediumCategoryAr))
    MediumCategoryAr(m, 1) = Med_JP_RowNumber(UBound(MediumCategoryAr))
    MediumCategoryAr(m, 2) = 26271
    MediumCategoryAr(m, 3) = MediumCategoryEN(UBound(MediumCategoryAr))
    MediumCategoryAr(m, 4) = Med_EN_RowNumber(UBound(MediumCategoryAr))
    MediumCategoryAr(m, 5) = 26271
For m = LBound(MediumCategoryAr) To UBound(MediumCategoryAr)
    For n = LBound(Major_CategoryAr) To UBound(Major_CategoryAr)
        If CLng(MediumCategoryAr(m, 1)) > CLng(Major_CategoryAr(n, 11)) And _
           CLng(MediumCategoryAr(m, 1)) < CLng(Major_CategoryAr(n, 12)) And _
           CLng(Major_CategoryAr(n, 12)) < CLng(MediumCategoryAr(m, 2)) Then
            MediumCategoryAr(m, 2) = Major_CategoryAr(n, 12)
        End If
        If CLng(MediumCategoryAr(m, 4)) > CLng(Major_CategoryAr(n, 11)) And _
           CLng(MediumCategoryAr(m, 4)) < CLng(Major_CategoryAr(n, 12)) And _
           CLng(Major_CategoryAr(n, 12)) < CLng(MediumCategoryAr(m, 5)) Then
            MediumCategoryAr(m, 5) = Major_CategoryAr(n, 12)
            Exit For
        End If
    Next n
Next m
p = 0
For i = LBound(tmpAr) To UBound(tmpAr) - 1
    strMinor_CategoryJP = ""
    strMinor_CategoryEN = ""
    For n = LBound(Major_CategoryAr) To UBound(Major_CategoryAr)
        If RegExp_JapaneseOnly.Test(tmpAr(i, 1)) And _
       Not RegExp_5_Number.Test(tmpAr(i, 1)) And _
       Not RegExp_Round_Bracket.Test(tmpAr(i, 1)) And _
       Not RegExp_SquareBracket.Test(tmpAr(i, 1)) And _
       Not RegExp_Angle_Bracket.Test(tmpAr(i, 1)) And _
           InStr(tmpAr(i, 1), Major_CategoryAr(n, 8)) <> 0 And _
           InStr(tmpAr(i + 1, 1), Major_CategoryAr(n, 9)) <> 0 And _
           i >= Major_CategoryAr(n, 11) And _
           i <= Major_CategoryAr(n, 12) Then
            ReDim Preserve Minor_CategoryJP(p)
            ReDim Preserve Minor_CategoryEN(p)
            ReDim Preserve Min_JP_RowNumber(p)
            ReDim Preserve Min_EN_RowNumber(p)
            For k = 1 To 2
                strMinor_CategoryJP = strMinor_CategoryJP & tmpAr(i, k)
                strMinor_CategoryEN = strMinor_CategoryEN & " " & tmpAr(i + 1, k)
                strMinor_CategoryEN = Trim(strMinor_CategoryEN)
            Next k
            Set myMatches = RegExp_JapaneseOnly.Execute(strMinor_CategoryJP)
            Minor_CategoryJP(p) = strMinor_CategoryJP
            Min_JP_RowNumber(p) = i
            Set myMatches = RegExp_Upper_Lower.Execute(strMinor_CategoryEN)
            Minor_CategoryEN(p) = strMinor_CategoryEN
            Min_EN_RowNumber(p) = i + 1
            p = p + 1
        Else
        End If
    Next n
Next i
j = 0
For i = LBound(tmpAr) To UBound(tmpAr)
    strFoodGroup = ""
    strSubFoodGroup = ""
    strSub_Category = ""
    strMajor_Category = ""
    strMinor_Category = ""
    strDetailCategory = ""
    If RegExp_5_Number.Test(tmpAr(i, 1)) And tmpAr(i, 2) <> "(欠番)" Then
        ReDim Preserve ItemNamAr(j)
        ReDim Preserve ItemNumAr(j)
        ReDim Preserve FoodGrouNum(j)
        ReDim Preserve FoodGroupJP(j)
        ReDim Preserve FoodGroupEN(j)
        ReDim Preserve Sub_FoodGroup_JP(j)
        ReDim Preserve Sub_FoodGroup_EN(j)
        ReDim Preserve Sub_Category_JPN(j)
        ReDim Preserve Sub_Category_ENG(j)
        ReDim Preserve Major_CategoryJP(j)
        ReDim Preserve Major_CategoryEN(j)
        ReDim Preserve Major_CategoryLT(j)
        ReDim Preserve Med_Category_JPN(j)
        ReDim Preserve Med_Category_ENG(j)
        ReDim Preserve Minor_CategoryJP(j)
        ReDim Preserve Minor_CategoryEN(j)
        ReDim Preserve DetailCategoryJP(j)
        ReDim Preserve DetailCategoryEN(j)
        ReDim Preserve JapaneseName(j)
        ReDim Preserve English_Name(j)
        ItemNamAr(j) = tmpAr(i, 1)
        ItemNumAr(j) = i
        Select Case True
            Case Left(tmpAr(i, 1), 2) = "01"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "穀類"
                FoodGroupEN(j) = "CEREALS"
                CEREALS = CEREALS + 1
            Case Left(tmpAr(i, 1), 2) = "02"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "いも及びでん粉類"
                FoodGroupEN(j) = "POTATOES AND STARCHES"
                POTATOES = POTATOES + 1
            Case Left(tmpAr(i, 1), 2) = "03"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "砂糖及び甘味類"
                FoodGroupEN(j) = "SUGARS"
                SUGARS = SUGARS + 1
            Case Left(tmpAr(i, 1), 2) = "04"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "豆類"
                FoodGroupEN(j) = "PULSES"
                PULSES = PULSES + 1
            Case Left(tmpAr(i, 1), 2) = "05"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "種実類"
                FoodGroupEN(j) = "NUTS AND SEEDS"
                NUTS = NUTS + 1
            Case Left(tmpAr(i, 1), 2) = "06"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "野菜類"
                FoodGroupEN(j) = "VEGETABLES"
                VEGETABLES = VEGETABLES + 1
            Case Left(tmpAr(i, 1), 2) = "07"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "果実類"
                FoodGroupEN(j) = "FRUITS"
                FRUITS = FRUITS + 1
            Case Left(tmpAr(i, 1), 2) = "08"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "きのこ類"
                FoodGroupEN(j) = "MUSHROOMS"
                MUSHROOMS = MUSHROOMS + 1
            Case Left(tmpAr(i, 1), 2) = "09"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "藻類"
                FoodGroupEN(j) = "ALGAE"
                ALGAE = ALGAE + 1
            Case Left(tmpAr(i, 1), 2) = "10"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "魚介類"
                FoodGroupEN(j) = "FISHES AND SHELLFISHES"
                FISHES = FISHES + 1
            Case Left(tmpAr(i, 1), 2) = "11"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "肉類"
                FoodGroupEN(j) = "MEATS"
                MEATS = MEATS + 1
            Case Left(tmpAr(i, 1), 2) = "12"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "卵類"
                FoodGroupEN(j) = "EGGS"
                EGGS = EGGS + 1
            Case Left(tmpAr(i, 1), 2) = "13"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "乳類"
                FoodGroupEN(j) = "MILKS"
                MILK = MILK + 1
            Case Left(tmpAr(i, 1), 2) = "14"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "油脂類"
                FoodGroupEN(j) = "FATS AND OILS"
                OIL = OIL + 1
            Case Left(tmpAr(i, 1), 2) = "15"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "菓子類"
                FoodGroupEN(j) = "CONFECTIONERIES"
                CONFECTIONERIES = CONFECTIONERIES + 1
            Case Left(tmpAr(i, 1), 2) = "16"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "し好飲料類"
                FoodGroupEN(j) = "BEVERAGES"
                BEVERAGES = BEVERAGES + 1
            Case Left(tmpAr(i, 1), 2) = "17"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "調味料及び香辛料類"
                FoodGroupEN(j) = "SEASONINGS AND SPICES"
                SEASONINGS = SEASONINGS + 1
            Case Left(tmpAr(i, 1), 2) = "18"
                FoodGrouNum(j) = Left(tmpAr(i, 1), 2)
                FoodGroupJP(j) = "調理加工食品類"
                FoodGroupEN(j) = "PREPARED FOODS"
                PREPARED = PREPARED + 1
            Case Else
        End Select
        If RegExpJapaneseName.Test(tmpAr(i, 2)) Then
            Set myMatches = RegExpJapaneseName.Execute(tmpAr(i, 2))
            JapaneseName(j) = myMatches.Item(0).Value
        End If
        For t = 1 To 6
            If RegExp_EnglishName.Test(tmpAr(i + 1, t)) Then
                English_Name(j) = English_Name(j) & " " & tmpAr(i + 1, t)
                English_Name(j) = Trim(English_Name(j))
            Else
                Exit For
            End If
        Next t
        For k = LBound(Major_CategoryAr) To UBound(Major_CategoryAr)
            If CLng(tmpAr(i, 1)) >= CLng(Major_CategoryAr(k, 0)) _
           And CLng(tmpAr(i, 1)) <= CLng(Major_CategoryAr(k, 1)) Then
                Sub_FoodGroup_JP(j) = Major_CategoryAr(k, 4)
                Sub_FoodGroup_EN(j) = Major_CategoryAr(k, 5)
                Sub_Category_JPN(j) = Major_CategoryAr(k, 6)
                Sub_Category_ENG(j) = Major_CategoryAr(k, 7)
                Major_CategoryJP(j) = Major_CategoryAr(k, 8)
                Major_CategoryEN(j) = Major_CategoryAr(k, 9)
                Major_CategoryLT(j) = Major_CategoryAr(k, 10)
                For m = LBound(MediumCategoryAr) To UBound(MediumCategoryAr)
                    If i >= CLng(MediumCategoryAr(m, 1)) And _
                       i <= CLng(MediumCategoryAr(m, 2)) Then
                        Med_Category_JPN(j) = MediumCategoryAr(m, 0)
                    End If
                    If i >= CLng(MediumCategoryAr(m, 4)) And _
                       i <= CLng(MediumCategoryAr(m, 5)) Then
                        Med_Category_ENG(j) = MediumCategoryAr(m, 3)
                    End If
                Next m
            Else
            End If
        Next k
    Else
        j = j - 1
    End If
    j = j + 1
Next i
ReDim ItemArray(UBound(ItemNamAr), 14)
For i = LBound(ItemArray) To UBound(ItemArray)
    ItemArray(i, 0) = ItemNamAr(i)
    ItemArray(i, 1) = FoodGrouNum(i)
    ItemArray(i, 2) = FoodGroupJP(i)
    ItemArray(i, 3) = FoodGroupEN(i)
    ItemArray(i, 4) = Sub_FoodGroup_JP(i)
    ItemArray(i, 5) = Sub_FoodGroup_EN(i)
    ItemArray(i, 6) = Sub_Category_JPN(i)
    ItemArray(i, 7) = Sub_Category_ENG(i)
    ItemArray(i, 8) = Major_CategoryJP(i)
    ItemArray(i, 9) = Major_CategoryEN(i)
    ItemArray(i, 10) = Major_CategoryLT(i)
    ItemArray(i, 11) = Med_Category_JPN(i)
    ItemArray(i, 12) = Med_Category_ENG(i)
    ItemArray(i, 13) = JapaneseName(i)
    ItemArray(i, 14) = English_Name(i)
Next i
Set mySht3 = Worksheets.Add
With mySht3
    .Name = "Result"
    .Range("A1").Value = "ItemNumber"
    .Range("B1").Value = "食品群番号"
    .Range("C1").Value = "食品群"
    .Range("D1").Value = "FoodGroup"
    .Range("E1").Value = "副分類"
    .Range("F1").Value = "SubFoodGroup"
    .Range("G1").Value = "区分"
    .Range("H1").Value = "SubCategory"
    .Range("I1").Value = "大分類"
    .Range("J1").Value = "MajorCategory"
    .Range("K1").Value = "AcademicName"
    .Range("L1").Value = "中分類"
    .Range("M1").Value = "MediumCategory"
    .Range("N1").Value = "小分類・細分"
    .Range("O1").Value = "MinorCategory_Details"
    .Range("A2:O1879").Value = ItemArray
End With
End Sub

Function NoCancelArray(ByRef Sh As Worksheet) As Variant
Dim mySht           As Worksheet
Dim myRng           As Range
Dim tmpAr           As Variant
Dim i               As Long
Dim j               As Long
Dim RegExpCancel    As Object
Dim RegExp_Exit     As Object
Const StrCancel     As String = "^(1\)|residues)$"
Dim CancelItem()    As String
Dim CancelRow1()    As String
Dim CancelRow2()    As String
Dim myCancelAr()    As String
Dim Cancel_Array()  As String
Set RegExpCancel = CreateObject("VBScript.RegExp")
With RegExpCancel
    .Pattern = StrCancel
    .IgnoreCase = True
    .Global = True
End With
Set mySht = Sh
Set myRng = mySht.UsedRange
tmpAr = myRng
j = 0
For i = LBound(tmpAr) To UBound(tmpAr)
    If RegExpCancel.Test(tmpAr(i, 1)) Then
        ReDim Preserve CancelItem(j)
        ReDim Preserve CancelRow1(i)
        CancelItem(j) = tmpAr(i, 1)
        CancelRow1(j) = i
        j = j + 1
    End If
Next i
ReDim myCancelAr(UBound(CancelItem), 1)
For j = LBound(myCancelAr) To UBound(myCancelAr)
    myCancelAr(j, 0) = CancelItem(j)
    myCancelAr(j, 1) = CancelRow1(j)
Next j
ReDim Preserve myCancelAr(UBound(myCancelAr), 2)
j = 0
For i = LBound(myCancelAr) To UBound(myCancelAr) - 1
    If myCancelAr(i, 0) = "1)" Then
        If myCancelAr(i + 2, 0) = "residues" Then
            myCancelAr(i, 2) = myCancelAr(i + 2, 1)
        Else
            myCancelAr(i, 2) = myCancelAr(i + 1, 1)
        End If
        j = j + 1
    End If
Next i
Erase CancelRow1
j = 0
ReDim CancelRow1(j)
ReDim CancelRow2(j)
CancelRow1(j) = myCancelAr(j, 1)
CancelRow2(j) = myCancelAr(j, 2)
For i = LBound(myCancelAr) + 1 To UBound(myCancelAr)
    If myCancelAr(i, 0) = "1)" And _
       myCancelAr(i - 1, 0) <> "1)" Then
        j = j + 1
        ReDim Preserve CancelRow1(j)
        ReDim Preserve CancelRow2(j)
        CancelRow1(j) = myCancelAr(i, 1)
        CancelRow2(j) = myCancelAr(i, 2)
    End If
Next i
ReDim Cancel_Array(UBound(CancelRow1), 1)
j = 0
For j = LBound(Cancel_Array) To UBound(Cancel_Array)
    Cancel_Array(j, 0) = CancelRow1(j)
    Cancel_Array(j, 1) = CancelRow2(j)
Next j
j = 0
Cancel_Array(j, 0) = 1
Cancel_Array(j, 1) = CancelRow1(j)
For j = LBound(Cancel_Array) + 1 To UBound(Cancel_Array)
    Cancel_Array(j, 0) = CancelRow2(j - 1)
    Cancel_Array(j, 1) = CancelRow1(j)
Next j
NoCancelArray = Cancel_Array
End Function

参照:
日本食品標準成分表2010のcsvファイル
日本食品標準成分表2010の食品番号をカテゴリー分類する その2

Classify the Item_Number of the ‘Standard Tables of Food Composition in Japan 2010’

I have released ‘Standard Tables of Food Composition in Japan 2010′ on Jan. 18, 2012. However, I did not classify which Item_Number is categorized into food groups or derived from any organism.

In this contents, I have described incomplete way how to classify them.

Example 1 shows that the code exports Item_Number, major category, medium category, minor category and details. Please note that the tree structures is not complete.

Example 2 shows complete tree structures. However, I could not write the complete code with recursion.

Example 1. Incomplete data
Item Number Major Category Medium Category Minor Category Major Category Medium Category Minor Category
01012 こむぎ [玄穀] 国産 Wheat [Whole grain] Domestic
01013

輸入

Imported
01014

輸入

Imported
01015
[小麦粉] 薄力粉
[Wheat  flour] Soft flour
01016 
[小麦粉] 薄力粉
[Wheat flour] Soft flour
01018

中力粉

Medium flour
01019  
中力粉

Medium flour
01020

強力粉

Hard flour
01021

強力粉

Hard flour
01023 

強力粉

Hard flour
01024

プレミックス粉

Premixed flour
01025

プレミックス粉

Premixed flour
Example 2. Complete data
Item Number Major Category Medium Category Minor Category Major Category MediumCategory MinorCategory
01012 こむぎ [玄穀] 国産 Wheat [Whole grain] Domestic
01013 こむぎ [玄穀] 輸入 Wheat [Whole grain] Imported
01014 こむぎ [玄穀] 輸入 Wheat [Whole grain] Imported
01015 こむぎ [小麦粉] 薄力粉 Wheat [Wheat  flour] Soft flour
01016  こむぎ [小麦粉] 薄力粉 Wheat [Wheat flour] Soft flour
01018 こむぎ [小麦粉] 中力粉 Wheat [Wheat flour] Medium flour
01019  こむぎ [小麦粉] 中力粉 Wheat [Wheat flour] Medium flour
01020 こむぎ [小麦粉] 強力粉 Wheat [Whole flour] Hard flour
01021 こむぎ [小麦粉] 強力粉 Wheat [Wheat flour] Hard flour
01023 こむぎ [小麦粉] 強力粉 Wheat [Wheat flour] Hard flour
01024 こむぎ [小麦粉] プレミックス粉 Wheat [Wheat flour] Premixed flour
01025 こむぎ [小麦粉] プレミックス粉 Wheat [Wheat flour] Premixed flour

Please copy text from the PDF files and paste to EXCEL worksheet by such procedure as described in this content. Press ‘Alt’ key and ‘F11’ key to load VBE. Run the following code:

Option Explicit
Sub ItemNum()
Dim mySht           As Worksheet
Dim myRng           As Range
Dim i               As Long
Dim j               As Long
Dim k               As Long
Dim tmpAr           As Variant
Dim myItem()        As String
Dim myNum1()        As String
Dim myNum2()        As String
Dim ItemNumAr()     As String
Dim myCancel()      As String
Dim Cancel_Ar()     As String
Dim myAr()          As String
Dim myAr2()         As String
Dim myGroupNamJP()  As String
Dim myGroupNumJP()  As String
Dim myGroupNamEN()  As String
Dim myGroupNumEN()  As String
Dim GroupAr()       As String
Dim myRegExp1       As Object
Dim myRegExp2       As Object
Dim myStrPtn        As String
Dim myStrPtn2       As String
Const startStrPtn   As String = "^(1\\)|residues)$"
Dim tmpStrJ         As String
Dim tmpStrE         As String
Const endStrPtn     As String = "[0-9]\\)$"
Const JapStrPtn     As String = "([ぁ-ヶ]|[亜-黑])+$"
Dim myStr           As String
Set mySht = ActiveSheet
Set myRng = Application.Intersect(mySht.Range("A:F"), _
                                    mySht.UsedRange)
tmpAr = myRng
Set myRegExp1 = CreateObject("VBScript.RegExp")
myStrPtn = "^[0-9]{5}$"
With myRegExp1
    .Pattern = myStrPtn
    .IgnoreCase = True
    .Global = True
End With
Set myRegExp2 = CreateObject("VBScript.RegExp")
With myRegExp2
    .Pattern = startStrPtn
    .IgnoreCase = True
    .Global = True
End With
j = 0
For i = LBound(tmpAr) To UBound(tmpAr)
    If myRegExp1.Test(tmpAr(i, 1)) And _
       tmpAr(i, 2) <> "(欠番)" Then
        ReDim Preserve myItem(j)
        ReDim Preserve myNum1(j)
        myItem(j) = tmpAr(i, 1)
        myNum1(j) = i
    Else
        j = j - 1
    End If
    j = j + 1
Next i
ReDim ItemNumAr(j - 1, 2)
    ItemNumAr(LBound(ItemNumAr), 0) = myItem(LBound(ItemNumAr))
    ItemNumAr(LBound(ItemNumAr), 1) = 7
    ItemNumAr(LBound(ItemNumAr), 2) = myNum1(LBound(ItemNumAr))
For k = LBound(ItemNumAr) + 1 To UBound(ItemNumAr)
    ItemNumAr(k, 0) = myItem(k)
    ItemNumAr(k, 1) = myNum1(k - 1) + 1
    ItemNumAr(k, 2) = myNum1(k)
Next k
Erase myItem
Erase myNum1
j = 0
For i = LBound(tmpAr) To UBound(tmpAr)
    If myRegExp2.Test(tmpAr(i, 1)) _
    Then
        ReDim Preserve myItem(j)
        ReDim Preserve myNum1(i)
        myItem(j) = tmpAr(i, 1)
        myNum1(j) = i
    Else
        j = j - 1
    End If
    j = j + 1
Next i
ReDim myCancel(UBound(myItem), 1)
For k = LBound(myCancel) To UBound(myCancel)
    myCancel(k, 0) = myItem(k)
    myCancel(k, 1) = myNum1(k)
Next k
Erase myItem
Erase myNum1
ReDim Preserve myCancel(UBound(myCancel), 2)
j = 0
For i = LBound(myCancel) To UBound(myCancel) - 1
    If myCancel(i, 0) = "1)" Then
        If myCancel(i + 2, 0) = "residues" Then
            myCancel(i, 2) = myCancel(i + 2, 1)
        Else
            myCancel(i, 2) = myCancel(i + 1, 1)
        End If
    Else
        j = j - 1
    End If
    j = j + 1
Next i
ReDim Cancel_Ar(j - 1, 2)
j = 0
For i = LBound(myCancel) To UBound(myCancel) - 1
    If myCancel(i, 0) = "1)" Then
        Cancel_Ar(j, 0) = myCancel(i, 0)
        Cancel_Ar(j, 1) = myCancel(i, 1)
        Cancel_Ar(j, 2) = myCancel(i, 2)
    Else
        j = j - 1
    End If
    j = j + 1
Next i
k = 0
ReDim myItem(k)
ReDim myNum1(k)
ReDim myNum2(k)
For i = LBound(ItemNumAr) To UBound(ItemNumAr)
    ReDim Preserve myItem(k)
    ReDim Preserve myNum1(k)
    ReDim Preserve myNum2(k)
    For j = LBound(Cancel_Ar) To UBound(Cancel_Ar)
        If CLng(ItemNumAr(i, 1)) < CLng(Cancel_Ar(j, 1)) And _
                                   CLng(Cancel_Ar(j, 1)) < CLng(ItemNumAr(i, 2)) And _
           CLng(ItemNumAr(i, 1)) < CLng(Cancel_Ar(j, 2)) And _
                                   CLng(Cancel_Ar(j, 2)) < CLng(ItemNumAr(i, 2)) _
        Then
            If Cancel_Ar(j, 1) - ItemNumAr(i, 1) < 3 Then
                myItem(k) = ItemNumAr(i, 0)
                myNum1(k) = Cancel_Ar(j, 2)
                myNum2(k) = ItemNumAr(i, 2)
            Else
                myNum2(k) = Cancel_Ar(j, 1)
                k = k + 1
                ReDim Preserve myItem(k)
                ReDim Preserve myNum1(k)
                ReDim Preserve myNum2(k)
                myItem(k) = ItemNumAr(i, 0)
                myNum1(k) = Cancel_Ar(j, 2)
                myNum2(k) = ItemNumAr(i, 2)
            End If
        Else
            myItem(k) = ItemNumAr(i, 0)
            myNum1(k) = ItemNumAr(i, 1)
            myNum2(k) = ItemNumAr(i, 2)
        End If
    Next j
    k = k + 1
Next i
ReDim myAr(UBound(myItem), 2)
For i = LBound(myAr) To UBound(myAr)
    myAr(i, 0) = myItem(i)
    myAr(i, 1) = myNum1(i)
    myAr(i, 2) = myNum2(i)
Next i
Erase myItem
Erase myNum1
Erase myNum2
myStrPtn2 = "^(\\[|\\()?[a-zA-Z]+"
With myRegExp1
    .Pattern = myStrPtn2
    .IgnoreCase = True
    .Global = True
End With
k = 0
For i = LBound(tmpAr) To UBound(tmpAr)
    For j = LBound(myAr) To UBound(myAr)
        If CLng(myAr(j, 1)) < i And _
           CLng(myAr(j, 2)) > i And _
           myRegExp1.Test(tmpAr(i, 1)) _
        Then
            ReDim Preserve myGroupNamJP(k)
            ReDim Preserve myGroupNumJP(k)
            ReDim Preserve myGroupNamEN(k)
            ReDim Preserve myGroupNumEN(k)
            myGroupNamJP(k) = tmpAr(i - 1, 1) & _
                           tmpAr(i - 1, 2) & _
                           tmpAr(i - 1, 3) & _
                           tmpAr(i - 1, 4) & _
                           tmpAr(i - 1, 5) & _
                           tmpAr(i - 1, 6)
            myGroupNumJP(k) = i - 1
            myGroupNamEN(k) = RTrim(tmpAr(i, 1) & " " & _
                         Replace(tmpAr(i, 2), "*", "") & " " & _
                         Replace(tmpAr(i, 3), "*", "") & " " & _
                         Replace(tmpAr(i, 4), "*", "") & " " & _
                         Replace(tmpAr(i, 5), "*", "") & " " & _
                         Replace(tmpAr(i, 6), "*", ""))
            myGroupNumEN(k) = i
        Else
            k = k - 1
        End If
        k = k + 1
    Next j
Next i
ReDim GroupAr(UBound(myGroupNamJP), 3)
For i = LBound(GroupAr) To UBound(GroupAr)
    GroupAr(i, 0) = myGroupNamJP(i)
    GroupAr(i, 1) = myGroupNumJP(i)
    GroupAr(i, 2) = myGroupNamEN(i)
    GroupAr(i, 3) = myGroupNumEN(i)
Next i
Erase myGroupNamJP
Erase myGroupNumJP
Erase myGroupNamEN
Erase myGroupNumEN
k = 0
For i = LBound(GroupAr) To UBound(GroupAr)
    ReDim Preserve myGroupNamJP(k)
    ReDim Preserve myGroupNumJP(k)
    ReDim Preserve myGroupNamEN(k)
    ReDim Preserve myGroupNumEN(k)
    myGroupNamJP(k) = GroupAr(i, 0)
    myGroupNumJP(k) = GroupAr(i, 1)
    myGroupNamEN(k) = GroupAr(i, 2)
    myGroupNumEN(k) = GroupAr(i, 3)
    k = k + 1
    For j = LBound(Cancel_Ar) To UBound(Cancel_Ar)
        If CLng(Cancel_Ar(j, 1)) < CLng(GroupAr(i, 1)) And _
           CLng(GroupAr(i, 1)) < CLng(Cancel_Ar(j, 2)) _
        Then
            k = k - 1
        End If
    Next j
Next i
ReDim GroupAr(UBound(myGroupNamJP), 3)
With myRegExp1
    .Pattern = endStrPtn
    .IgnoreCase = True
    .Global = True
End With
With myRegExp2
    .Pattern = JapStrPtn
    .IgnoreCase = True
    .Global = True
End With
For i = LBound(GroupAr) To UBound(GroupAr)
    myGroupNamJP(i) = myRegExp1.Replace(myGroupNamJP(i), "")
    myGroupNamEN(i) = myRegExp1.Replace(myGroupNamEN(i), "")
    myGroupNamEN(i) = RTrim(myRegExp2.Replace(myGroupNamEN(i), ""))
    GroupAr(i, 0) = myGroupNamJP(i)
    GroupAr(i, 1) = myGroupNumJP(i)
    GroupAr(i, 2) = myGroupNamEN(i)
    GroupAr(i, 3) = myGroupNumEN(i)
Next i
ReDim Preserve myAr(UBound(myAr), 5)
ReDim myAr2(UBound(myAr), 3)
For i = LBound(myAr) To UBound(myAr)
    tmpStrJ = ""
    tmpStrE = ""
    myAr2(i, 0) = myAr(i, 0)
    For j = LBound(GroupAr) To UBound(GroupAr)
        If CLng(myAr(i, 1)) < CLng(GroupAr(j, 1)) And _
                              CLng(GroupAr(j, 3)) < CLng(myAr(i, 2)) Then
            tmpStrJ = tmpStrJ & GroupAr(j, 0)
            tmpStrE = RTrim(tmpStrE & " " & GroupAr(j, 2))
            myAr(i, 4) = GroupAr(j, 1)
        End If
    Next j
    If tmpStrJ = "" Then
        myAr(i, 3) = myAr(i - 1, 3)
        myAr(i, 4) = myAr(i - 1, 4)
        myAr(i, 5) = myAr(i - 1, 5)
        myAr2(i, 1) = myAr(i - 1, 3)
        myAr2(i, 2) = myAr(i - 1, 5)
    Else
        myAr(i, 3) = tmpStrJ
        myAr(i, 5) = tmpStrE
        myAr2(i, 1) = tmpStrJ
        myAr2(i, 2) = tmpStrE
    End If
Next i
Set mySht = Worksheets.Add
With mySht
    .Range("A1").Value = "Item_Number"
    .Range("B1").Value = "上位食品名(日)"
    .Range("C1").Value = "上位食品名(英)"
    .Range("A2:C450") = myAr2
End With
Erase ItemNumAr
Erase Cancel_Ar
Erase GroupAr
Erase myAr
Erase myAr2
Set mySht = Nothing
Set myRng = Nothing
Set myRegExp1 = Nothing
Set myRegExp2 = Nothing
End Sub

日本食品標準成分表2010の食品番号を分類する

日本食品標準成分表2010のテキストデータで日本食品標準成分表2010のテキストデータを公開しましたが,食品番号がどの食品群に属するか,どの生物由来かなどの分類ができていませんでした.今回は不十分ではありますが,食品番号を分類する方法を述べます.

注意点として例1に挙げたように,大分類・中分類・小分類・細目のツリー構造が完全ではありません.本来は例2のようであるべきですが,ツリー構造を解析するには再帰呼び出しによる構成展開が必要で,私の今のスキルでは無理でした.ご了承下さい.

例1.コードを実行して得られるデータ
Item Number Major Category Medium Category Minor Category Major Category Medium Category Minor Category
01012 こむぎ [玄穀] 国産 Wheat [Whole grain] Domestic
01013

輸入

Imported
01014

輸入

Imported
01015
[小麦粉] 薄力粉
[Wheat  flour] Soft flour
01016 
[小麦粉] 薄力粉
[Wheat flour] Soft flour
01018

中力粉

Medium flour
01019  
中力粉

Medium flour
01020

強力粉

Hard flour
01021

強力粉

Hard flour
01023 

強力粉

Hard flour
01024

プレミックス粉

Premixed flour
01025

プレミックス粉

Premixed flour
例2.必要なデータ
Item_Number Major Category Medium Category Minor Category Major Category MediumCategory MinorCategory
01012 こむぎ [玄穀] 国産 Wheat [Whole grain] Domestic
01013 こむぎ [玄穀] 輸入 Wheat [Whole grain] Imported
01014 こむぎ [玄穀] 輸入 Wheat [Whole grain] Imported
01015 こむぎ [小麦粉] 薄力粉 Wheat [Wheat  flour] Soft flour
01016  こむぎ [小麦粉] 薄力粉 Wheat [Wheat flour] Soft flour
01018 こむぎ [小麦粉] 中力粉 Wheat [Wheat flour] Medium flour
01019  こむぎ [小麦粉] 中力粉 Wheat [Wheat flour] Medium flour
01020 こむぎ [小麦粉] 強力粉 Wheat [Whole flour] Hard flour
01021 こむぎ [小麦粉] 強力粉 Wheat [Wheat flour] Hard flour
01023 こむぎ [小麦粉] 強力粉 Wheat [Wheat flour] Hard flour
01024 こむぎ [小麦粉] プレミックス粉 Wheat [Wheat flour] Premixed flour
01025 こむぎ [小麦粉] プレミックス粉 Wheat [Wheat flour] Premixed flour

PDFからテキスト情報を貼り付けるのはこのコンテンツに記載したのと同じ手順です.AltキーとF11キーを押下してVBEを起動し,標準モジュールに以下のコードを貼り付けて実行して下さい.

Option Explicit
Sub ItemNum()
Dim mySht           As Worksheet
Dim myRng           As Range
Dim i               As Long
Dim j               As Long
Dim k               As Long
Dim tmpAr           As Variant
Dim myItem()        As String
Dim myNum1()        As String
Dim myNum2()        As String
Dim ItemNumAr()     As String
Dim myCancel()      As String
Dim Cancel_Ar()     As String
Dim myAr()          As String
Dim myAr2()         As String
Dim myGroupNamJP()  As String
Dim myGroupNumJP()  As String
Dim myGroupNamEN()  As String
Dim myGroupNumEN()  As String
Dim GroupAr()       As String
Dim myRegExp1       As Object
Dim myRegExp2       As Object
Dim myStrPtn        As String
Dim myStrPtn2       As String
Const startStrPtn   As String = "^(1\\)|residues)$"
Dim tmpStrJ         As String
Dim tmpStrE         As String
Const endStrPtn     As String = "[0-9]\\)$"
Const JapStrPtn     As String = "([ぁ-ヶ]|[亜-黑])+$"
Dim myStr           As String
Set mySht = ActiveSheet
Set myRng = Application.Intersect(mySht.Range("A:F"), _
                                    mySht.UsedRange)
tmpAr = myRng
Set myRegExp1 = CreateObject("VBScript.RegExp")
myStrPtn = "^[0-9]{5}$"
With myRegExp1
    .Pattern = myStrPtn
    .IgnoreCase = True
    .Global = True
End With
Set myRegExp2 = CreateObject("VBScript.RegExp")
With myRegExp2
    .Pattern = startStrPtn
    .IgnoreCase = True
    .Global = True
End With
j = 0
For i = LBound(tmpAr) To UBound(tmpAr)
    If myRegExp1.Test(tmpAr(i, 1)) And _
       tmpAr(i, 2) <> "(欠番)" Then
        ReDim Preserve myItem(j)
        ReDim Preserve myNum1(j)
        myItem(j) = tmpAr(i, 1)
        myNum1(j) = i
    Else
        j = j - 1
    End If
    j = j + 1
Next i
ReDim ItemNumAr(j - 1, 2)
    ItemNumAr(LBound(ItemNumAr), 0) = myItem(LBound(ItemNumAr))
    ItemNumAr(LBound(ItemNumAr), 1) = 7
    ItemNumAr(LBound(ItemNumAr), 2) = myNum1(LBound(ItemNumAr))
For k = LBound(ItemNumAr) + 1 To UBound(ItemNumAr)
    ItemNumAr(k, 0) = myItem(k)
    ItemNumAr(k, 1) = myNum1(k - 1) + 1
    ItemNumAr(k, 2) = myNum1(k)
Next k
Erase myItem
Erase myNum1
j = 0
For i = LBound(tmpAr) To UBound(tmpAr)
    If myRegExp2.Test(tmpAr(i, 1)) _
    Then
        ReDim Preserve myItem(j)
        ReDim Preserve myNum1(i)
        myItem(j) = tmpAr(i, 1)
        myNum1(j) = i
    Else
        j = j - 1
    End If
    j = j + 1
Next i
ReDim myCancel(UBound(myItem), 1)
For k = LBound(myCancel) To UBound(myCancel)
    myCancel(k, 0) = myItem(k)
    myCancel(k, 1) = myNum1(k)
Next k
Erase myItem
Erase myNum1
ReDim Preserve myCancel(UBound(myCancel), 2)
j = 0
For i = LBound(myCancel) To UBound(myCancel) - 1
    If myCancel(i, 0) = "1)" Then
        If myCancel(i + 2, 0) = "residues" Then
            myCancel(i, 2) = myCancel(i + 2, 1)
        Else
            myCancel(i, 2) = myCancel(i + 1, 1)
        End If
    Else
        j = j - 1
    End If
    j = j + 1
Next i
ReDim Cancel_Ar(j - 1, 2)
j = 0
For i = LBound(myCancel) To UBound(myCancel) - 1
    If myCancel(i, 0) = "1)" Then
        Cancel_Ar(j, 0) = myCancel(i, 0)
        Cancel_Ar(j, 1) = myCancel(i, 1)
        Cancel_Ar(j, 2) = myCancel(i, 2)
    Else
        j = j - 1
    End If
    j = j + 1
Next i
k = 0
ReDim myItem(k)
ReDim myNum1(k)
ReDim myNum2(k)
For i = LBound(ItemNumAr) To UBound(ItemNumAr)
    ReDim Preserve myItem(k)
    ReDim Preserve myNum1(k)
    ReDim Preserve myNum2(k)
    For j = LBound(Cancel_Ar) To UBound(Cancel_Ar)
        If CLng(ItemNumAr(i, 1)) < CLng(Cancel_Ar(j, 1)) And _
                                   CLng(Cancel_Ar(j, 1)) < CLng(ItemNumAr(i, 2)) And _
           CLng(ItemNumAr(i, 1)) < CLng(Cancel_Ar(j, 2)) And _
                                   CLng(Cancel_Ar(j, 2)) < CLng(ItemNumAr(i, 2)) _
        Then
            If Cancel_Ar(j, 1) - ItemNumAr(i, 1) < 3 Then
                myItem(k) = ItemNumAr(i, 0)
                myNum1(k) = Cancel_Ar(j, 2)
                myNum2(k) = ItemNumAr(i, 2)
            Else
                myNum2(k) = Cancel_Ar(j, 1)
                k = k + 1
                ReDim Preserve myItem(k)
                ReDim Preserve myNum1(k)
                ReDim Preserve myNum2(k)
                myItem(k) = ItemNumAr(i, 0)
                myNum1(k) = Cancel_Ar(j, 2)
                myNum2(k) = ItemNumAr(i, 2)
            End If
        Else
            myItem(k) = ItemNumAr(i, 0)
            myNum1(k) = ItemNumAr(i, 1)
            myNum2(k) = ItemNumAr(i, 2)
        End If
    Next j
    k = k + 1
Next i
ReDim myAr(UBound(myItem), 2)
For i = LBound(myAr) To UBound(myAr)
    myAr(i, 0) = myItem(i)
    myAr(i, 1) = myNum1(i)
    myAr(i, 2) = myNum2(i)
Next i
Erase myItem
Erase myNum1
Erase myNum2
myStrPtn2 = "^(\\[|\\()?[a-zA-Z]+"
With myRegExp1
    .Pattern = myStrPtn2
    .IgnoreCase = True
    .Global = True
End With
k = 0
For i = LBound(tmpAr) To UBound(tmpAr)
    For j = LBound(myAr) To UBound(myAr)
        If CLng(myAr(j, 1)) < i And _
           CLng(myAr(j, 2)) > i And _
           myRegExp1.Test(tmpAr(i, 1)) _
        Then
            ReDim Preserve myGroupNamJP(k)
            ReDim Preserve myGroupNumJP(k)
            ReDim Preserve myGroupNamEN(k)
            ReDim Preserve myGroupNumEN(k)
            myGroupNamJP(k) = tmpAr(i - 1, 1) & _
                           tmpAr(i - 1, 2) & _
                           tmpAr(i - 1, 3) & _
                           tmpAr(i - 1, 4) & _
                           tmpAr(i - 1, 5) & _
                           tmpAr(i - 1, 6)
            myGroupNumJP(k) = i - 1
            myGroupNamEN(k) = RTrim(tmpAr(i, 1) & " " & _
                         Replace(tmpAr(i, 2), "*", "") & " " & _
                         Replace(tmpAr(i, 3), "*", "") & " " & _
                         Replace(tmpAr(i, 4), "*", "") & " " & _
                         Replace(tmpAr(i, 5), "*", "") & " " & _
                         Replace(tmpAr(i, 6), "*", ""))
            myGroupNumEN(k) = i
        Else
            k = k - 1
        End If
        k = k + 1
    Next j
Next i
ReDim GroupAr(UBound(myGroupNamJP), 3)
For i = LBound(GroupAr) To UBound(GroupAr)
    GroupAr(i, 0) = myGroupNamJP(i)
    GroupAr(i, 1) = myGroupNumJP(i)
    GroupAr(i, 2) = myGroupNamEN(i)
    GroupAr(i, 3) = myGroupNumEN(i)
Next i
Erase myGroupNamJP
Erase myGroupNumJP
Erase myGroupNamEN
Erase myGroupNumEN
k = 0
For i = LBound(GroupAr) To UBound(GroupAr)
    ReDim Preserve myGroupNamJP(k)
    ReDim Preserve myGroupNumJP(k)
    ReDim Preserve myGroupNamEN(k)
    ReDim Preserve myGroupNumEN(k)
    myGroupNamJP(k) = GroupAr(i, 0)
    myGroupNumJP(k) = GroupAr(i, 1)
    myGroupNamEN(k) = GroupAr(i, 2)
    myGroupNumEN(k) = GroupAr(i, 3)
    k = k + 1
    For j = LBound(Cancel_Ar) To UBound(Cancel_Ar)
        If CLng(Cancel_Ar(j, 1)) < CLng(GroupAr(i, 1)) And _
           CLng(GroupAr(i, 1)) < CLng(Cancel_Ar(j, 2)) _
        Then
            k = k - 1
        End If
    Next j
Next i
ReDim GroupAr(UBound(myGroupNamJP), 3)
With myRegExp1
    .Pattern = endStrPtn
    .IgnoreCase = True
    .Global = True
End With
With myRegExp2
    .Pattern = JapStrPtn
    .IgnoreCase = True
    .Global = True
End With
For i = LBound(GroupAr) To UBound(GroupAr)
    myGroupNamJP(i) = myRegExp1.Replace(myGroupNamJP(i), "")
    myGroupNamEN(i) = myRegExp1.Replace(myGroupNamEN(i), "")
    myGroupNamEN(i) = RTrim(myRegExp2.Replace(myGroupNamEN(i), ""))
    GroupAr(i, 0) = myGroupNamJP(i)
    GroupAr(i, 1) = myGroupNumJP(i)
    GroupAr(i, 2) = myGroupNamEN(i)
    GroupAr(i, 3) = myGroupNumEN(i)
Next i
ReDim Preserve myAr(UBound(myAr), 5)
ReDim myAr2(UBound(myAr), 3)
For i = LBound(myAr) To UBound(myAr)
    tmpStrJ = ""
    tmpStrE = ""
    myAr2(i, 0) = myAr(i, 0)
    For j = LBound(GroupAr) To UBound(GroupAr)
        If CLng(myAr(i, 1)) < CLng(GroupAr(j, 1)) And _
                              CLng(GroupAr(j, 3)) < CLng(myAr(i, 2)) Then
            tmpStrJ = tmpStrJ & GroupAr(j, 0)
            tmpStrE = RTrim(tmpStrE & " " & GroupAr(j, 2))
            myAr(i, 4) = GroupAr(j, 1)
        End If
    Next j
    If tmpStrJ = "" Then
        myAr(i, 3) = myAr(i - 1, 3)
        myAr(i, 4) = myAr(i - 1, 4)
        myAr(i, 5) = myAr(i - 1, 5)
        myAr2(i, 1) = myAr(i - 1, 3)
        myAr2(i, 2) = myAr(i - 1, 5)
    Else
        myAr(i, 3) = tmpStrJ
        myAr(i, 5) = tmpStrE
        myAr2(i, 1) = tmpStrJ
        myAr2(i, 2) = tmpStrE
    End If
Next i
Set mySht = Worksheets.Add
With mySht
    .Range("A1").Value = "Item_Number"
    .Range("B1").Value = "上位食品名(日)"
    .Range("C1").Value = "上位食品名(英)"
    .Range("A2:C450") = myAr2
End With
Erase ItemNumAr
Erase Cancel_Ar
Erase GroupAr
Erase myAr
Erase myAr2
Set mySht = Nothing
Set myRng = Nothing
Set myRegExp1 = Nothing
Set myRegExp2 = Nothing
End Sub