Skip to content

Instantly share code, notes, and snippets.

@KotorinChunChun
Created October 31, 2020 05:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KotorinChunChun/1759f2b696d51a9dea820c7e6636e1cf to your computer and use it in GitHub Desktop.
Save KotorinChunChun/1759f2b696d51a9dea820c7e6636e1cf to your computer and use it in GitHub Desktop.
選択中のセルの化学式の書式を整えるVBAマクロ
Rem 選択中のセルの化学式の書式を整えるVBAマクロ
Sub 選択範囲の化学式の書式を整える()
Dim MyRange As Range
Dim i As Integer
Dim s2 As String, s3 As String
Dim PHflg As Boolean
For Each MyRange In Selection
For i = 2 To Len(MyRange.Text)
s2 = Mid(MyRange.Text, i - 1, 2)
If i >= 3 Then s3 = Mid(MyRange.Text, i - 2, 2)
If s2 Like "[A-z]?" Then PHflg = False
If s3 = "pH" Or Left(s3, 1) = ")" Then PHflg = True
If (s2 Like "[A-z][0-9]" Or s2 Like "[0-9][0-9]" Or s2 Like ")[0-9]") And Not PHflg Then
MyRange.Characters(Start:=i, Length:=1).Font.Subscript = True
End If
Next
Next
End Sub
@KotorinChunChun
Copy link
Author

化学式を解読し適切な箇所の数字に下付き文字の書式を適用します。


image

@KotorinChunChun
Copy link
Author

テスト用文字列

C16H8N2Na2O8S2
Mg(NO3)2・6H2O
2Mg(NO3)2・6H2OpH4.01Mg(NO3)2・6H2O
2Mg(NO3)2・6H2OpH4.01 2Mg(NO3)2・6H2O
pH4.01
2Mg(NO3)2・6H2OpH4.01 2Mg(NO3)2・6H2O pH4.01

@KotorinChunChun
Copy link
Author

KotorinChunChun commented Oct 31, 2020

参考文献

このマクロは下記の質問サイトで私が答えた時のもの。
もう一名の方は正規表現で実装されており、こちらも興味深い。

『化学式の数値を一括で下付きにしたいです。』(たなか)
http://www.excel.studio-kazu.jp/kw/20181024103531.html

『化学式の数値を一括で下付き 新しい条件』(たなか)
http://www.excel.studio-kazu.jp/kw/20181109170313.html

『化学式の数値を一括でweb用に』(たなか)
http://www.excel.studio-kazu.jp/kw/20190124143337.html

@KotorinChunChun
Copy link
Author

マクロ登録方法

image

image

マクロ実行方法

3通りの方法がある。

直接実行

image

ショートカットキーに登録して実行

image

リボンに登録して実行

image
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment