2012年2月21日火曜日

【Excel2003】名前定義削除(マクロ)

Excel2003で名前定義を削除したい時、文字化けして削除できないときが多々ある。
それごと削除できるマクロを見つけたのでメモメモ。

ちなみに、2007以降では標準機能で一括削除できる。
名前定義の文字化けは未確認。

Public Declare Function SetTimer Lib "user32.dll" _
(ByVal hwnd As Long, ByVal nIDEvent As Long, ByVal uElapse As Long, _
ByVal lpTimerFunc As Long) As Long
Public Declare Function KillTimer Lib "user32.dll" _
(ByVal hwnd As Long, ByVal nIDEvent As Long) As Long
Public Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Sub DeleteDefinedNames()
Dim beforeReferenceStyle As Variant
beforeReferenceStyle = Application.ReferenceStyle
Dim timerID As Long
timerID = SetTimer(0, 0, 100, AddressOf TimerProc)
If beforeReferenceStyle = xlR1C1 Then
Application.ReferenceStyle = xlA1
Else
Application.ReferenceStyle = xlR1C1
End If
Dim n As Name
For Each n In ActiveWorkbook.Names
If Not n.Name Like "*!Print_Area" And _
Not n.Name Like "*!Print_Titles" Then
n.Delete
End If
Next
Application.ReferenceStyle = beforeReferenceStyle
KillTimer 0, timerID
End Sub
Private Sub TimerProc()
Dim hwnd As Long
hwnd = FindWindow("bosa_sdm_XL9", "名前の重複")
If hwnd > 0 Then
SendKeys getRandomString(3, 20), 10
SendKeys "{ENTER}"
End If
End Sub
Private Function getRandomString(min As Long, max As Long) As String
Dim s As String
Dim i As Long
max = Int(max * Rnd)
For i = 0 To min + max
Randomize
s = s & Chr(65 + Int(26 * Rnd))
Next
getRandomString = s
End Function


○参考ブログ
http://alphafocus.cocolog-nifty.com/blog/2011/05/tips-excel-14b4.html
○コード元
http://trash-area.com/archives/677
こういうの本当に助かります。
ありがとうございます。