回答編集履歴

2

サンプルコードを追記

2018/01/19 13:40

投稿

hatena19
hatena19

スコア33715

test CHANGED
@@ -23,3 +23,131 @@
23
23
 
24
24
 
25
25
  [ユーザーフォームに動的にボタン等を追加する - Excelが大好きだ!](http://excellover.hatenablog.com/entry/2017/07/30/155613)
26
+
27
+
28
+
29
+ **追記2:**
30
+
31
+ 作成してみました。
32
+
33
+ VBAウィンドウで、[挿入]-[クラスモジュール]で下記のコードを記述。
34
+
35
+ オブジェクト名を DragableButton とする。
36
+
37
+ ```VBA
38
+
39
+ Option Explicit
40
+
41
+ Private mx As Long, my As Long
42
+
43
+ Private IsClick As Boolean
44
+
45
+ Private WithEvents mBtn As MSForms.CommandButton
46
+
47
+
48
+
49
+ Public Sub Bind(objBtn As CommandButton)
50
+
51
+ Set mBtn = objBtn
52
+
53
+ End Sub
54
+
55
+
56
+
57
+ Private Sub mbtn_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
58
+
59
+ If Button = 1 Then '左ボタンが押されたらドラッグ開始
60
+
61
+ mx = X
62
+
63
+ my = Y
64
+
65
+ IsClick = True
66
+
67
+ End If
68
+
69
+ End Sub
70
+
71
+
72
+
73
+ Private Sub mbtn_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
74
+
75
+ If IsClick = True Then
76
+
77
+ mBtn.Left = mBtn.Left - (mx - X)
78
+
79
+ mBtn.Top = mBtn.Top - (my - Y)
80
+
81
+ End If
82
+
83
+ End Sub
84
+
85
+
86
+
87
+ Private Sub mbtn_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
88
+
89
+ If Button = 1 Then '左ボタンが開放されたらドラッグ終了
90
+
91
+ IsClick = False
92
+
93
+ mx = 0
94
+
95
+ my = 0
96
+
97
+ End If
98
+
99
+ End Sub
100
+
101
+ ```
102
+
103
+ ユーザーフォームにコマンドボタンを配置して、オブジェクト名は `cmdMakeBtn` とする。
104
+
105
+ ユーザーフォームのモジュール
106
+
107
+ ```VBA
108
+
109
+ Option Explicit
110
+
111
+ Dim dBtnCol As Collection
112
+
113
+ Dim dBtn As DragableButton
114
+
115
+
116
+
117
+ Private Sub cmdMakeBtn_Click()
118
+
119
+ Dim mCmdBtn As MSForms.CommandButton
120
+
121
+ Set mCmdBtn = UserForm1.Controls.Add("Forms.CommandButton.1", _
122
+
123
+ "CommandButton" & dBtnCol.Count + 1, True)
124
+
125
+ With mCmdBtn
126
+
127
+ .Left = 10
128
+
129
+ .Top = 10
130
+
131
+ .Width = 150
132
+
133
+ .Caption = .Name
134
+
135
+ End With
136
+
137
+ Set dBtn = New DragableButton
138
+
139
+ dBtn.Bind mCmdBtn '生成したボタンをDragableButtonクラスに接続
140
+
141
+ dBtnCol.Add dBtn
142
+
143
+ End Sub
144
+
145
+
146
+
147
+ Private Sub UserForm_Initialize()
148
+
149
+ Set dBtnCol = New Collection
150
+
151
+ End Sub
152
+
153
+ ```

1

参考リンクを追加

2018/01/19 13:39

投稿

hatena19
hatena19

スコア33715

test CHANGED
@@ -6,8 +6,20 @@
6
6
 
7
7
 
8
8
 
9
+
10
+
9
11
  下記はAccessのフォームなので、PowerPointのユーザーフォームとは若干異なりますが、移動できるコントロールのクラスモジュールのコード例です。
10
12
 
11
13
 
12
14
 
13
15
  [ドラッグできるラベルのクラス化 - hatena chips](https://hatenachips.blog.fc2.com/blog-entry-160.html)
16
+
17
+
18
+
19
+ **追記:**
20
+
21
+ 下記の方が今回のものに近いかも。Excel ですが、基本的には同じでしょう。
22
+
23
+
24
+
25
+ [ユーザーフォームに動的にボタン等を追加する - Excelが大好きだ!](http://excellover.hatenablog.com/entry/2017/07/30/155613)