GO BACK

WindowsStart連載「実験工房V.B.A.」
(1)



※これは毎日コミュニケーションの月刊誌「WindowsStart」に連載中の、プログラミング初心者向け入門です。Visual Basic for Applicationを使い、ExcelやWordを使ってちょっと便利な使い方を考えていく予定です。



●2002-06号● VBAってどういうもの?

まずは、VBAがどういうものか、基本的な使い方などについて説明をします。今回は、リストはほとんど登場しません。簡単なマクロを記録し、修正してみる程度です。


[リスト]
Sub Macro1()

Range("A1").Select
ActiveCell.FormulaR1C1 = "Hello"
Range("A1").Select
Selection.Font.Bold = True
End Sub


[リスト2]
Sub Macro1()
ActiveCell.FormulaR1C1 = "Hello"
Selection.Font.Bold = True
End Sub


●2002-07号● セルを自由に操作しよう!

今回は、セルの値を操作する方法について説明します。また条件分岐と繰り返しの基本形を理解し、セルをまとめて操作するようなものを作ってみます。


[リスト1]
Public Sub Macro1()
If Cells(1, 1) < 0 Then
Cells(1, 2) = "赤字"
Else
Cells(1, 2) = "黒字"
End If
End Sub

[リスト2]
Public Sub Macro2()
For i = 1 To 10
If Cells(i, 1) < 0 Then
Cells(i, 2) = "赤字"
Else
Cells(i, 2) = "黒字"
End If
Next
End Sub

[リスト3]
Public Sub QuQu()
For i = 1 To 9
For j = 1 To 9
str1 = "" & i & " × " & j & " = " & i * j
Cells(i, j) = str1
Next
Next
End Sub


●2002-08号● 選択したセルを操作しよう!

今回は、選択したセルを操作する方法についてです。1つだけのセルでなく、選択された複数のセル全てを処理する方法を学びます。またセルのテキストのフォントを変更する方法も説明します。


[リスト1]
Public Sub Macro1()
If ActiveCell < 0 Then
ActiveCell.Offset(0, 1) = "赤字"
Else
ActiveCell.Offset(0, 1) = "黒字"
End If
End Sub

[リスト2]
Public Sub Macro2()
Selection.Font.Name = "MS P明朝"
Selection.Font.FontStyle = "Bold"
Selection.Font.Size = 14
Selection.Font.Color = RGB(255, 0, 0)
End Sub

[リスト3]
Public Sub Macro3()
For Each cell In Selection
If cell < 0 Then
cell.Offset(0, 1) = "赤字"
cell.Offset(0, 1).Font.Color = RGB(255, 0, 0)
Else
cell.Offset(0, 1) = "黒字"
cell.Offset(0, 1).Font.Color = RGB(0, 0, 255)
End If
Next
End Sub

 

●2002-09号● 入出力と罫線の表示!

今回は、ユーザーからの簡単な入出力を行なうためのもの、平たくいえばinputBoxとmsgBoxです。またボーダー(罫線)の設定についても説明します。


[リスト1]
Sub Macro1()

num = InputBox("開始数は?")
If num = "" Then Exit Sub
num = num * 1
num2 = InputBox("増加数は?")
If num2 = "" Then Exit Sub
num2 = num2 * 1
For Each Obj In Selection
Obj.Value = num
num = num + num2
Next
MsgBox "選択範囲に数列を出力しました。"
End Sub


[リスト2]
Sub Macro2()
Set SelRg = ActiveWindow.RangeSelection
num1 = InputBox("輪郭線の太さは?",,"3")
If num1 = "" Then Exit Sub
num1 = num1 * 1
If num1 > 4 Then num1 = 4
If num1 < 1 Then num1 = 1
num2 = InputBox("内部の仕切りの太さは?", , "2")
If num2 = "" Then Exit Sub
num2 = num2 * 1
If num2 > 4 Then num2 = 4
If num2 < 1 Then num2 = 1
SelRg.Borders(xlInsideHorizontal).Weight = num2
SelRg.Borders(xlInsideVertical).Weight = num2
SelRg.Borders(xlEdgeTop).Weight = num1
SelRg.Borders(xlEdgeBottom).Weight = num1
SelRg.Borders(xlEdgeLeft).Weight = num1
SelRg.Borders(xlEdgeRight).Weight = num1
End Sub


[リスト3]
Sub Marco3()
Set SelRg = ActiveWindow.RangeSelection
SelRg.Borders.LineStyle = xlNone
End Sub


 

●2002-10号● フォームを作ろう!

今回は、Visual basic Editorでフォームを利用する基本についてです。簡単なフォームを作り、それを呼び出して利用してみます。


[リスト1]
Private Sub OKButton_Click()
With Me
.Hide
Yoko = .YokoText.Text
Tate = .TateText.Text
End With
For i = 1 To Tate
For j = 1 To Yoko
Cells(i, j) = i * j
Next
Next
End Sub


[リスト2]
Private Sub CancelButton_Click()
Me.Hide
End Sub


[リスト3]
Sub Shape_Click()
MyForm.Show
End Sub


●2002-11号● シェイプを操作しよう!

今回は、シェイプをマクロから操作する基本を覚えます。シェイプの新規作成と種類の設定、塗りつぶしの色などのプロパティの操作、削除といったことを行なってみます。


[リスト1]
Sub macro1()
ActiveSheet.Shapes.AddShape msoShapeRectangle, 50, 50, 50, 50
End Sub

[リスト2]
Sub marco2()
With ActiveSheet
.Shapes.AddShape msoShapeOval, 50, 50, 100, 100
n = .Shapes.Count
.Shapes(n).Fill.ForeColor.RGB = RGB(255, 0, 0)
End With
End Sub

[リスト3]
Sub macro3()
With ActiveSheet
n = .Shapes.Count
For i = 1 To 10
.Shapes.AddShape msoShapeRectangle, i * 20, 20, 20, 20
.Shapes(i + n).Fill.ForeColor.RGB = RGB(i * 25, 0, 255 - i * 25)
.Shapes(i + n).Line.ForeColor.RGB = RGB(i * 25, 0, 255 - i * 25)
Next
End With
End Sub

[リスト4]
Sub macro4()
For Each obj In ActiveSheet.Shapes
obj.Delete
Next
End Sub

●2002-12号● シートとコントロール

今回は、シートの上の直接コントロールを配置して使ってみます。また、簡単な例として、シート上に配置したコントロールをマクロ内から操作する基本について説明をします。


[リスト1]
Private Sub CommandButton1_Click()
num = TextBox1.Text
total = 0
For i = 1 To num
total = total + i
Next
Label1.Caption = "合計は、 " & total & " です。"
End Sub

[リスト2]
Private Sub CommandButton1_Click()
num = TextBox1.Text
Label1.Caption = "文字サイズは" & num & "です。"
Label1.Font.Size = num
End Sub


●2003-01号● シートのデータアクセス

今回は、シート上のコントロールからアクティブでないシートのデータを利用するサンプルを考えてみます。例として、学習型のYES/NO診断ゲームの例を作成します。


[リスト1]
Private Sub StartButton_Click()
StartButton.Visible = False
YesButton.Visible = True
NoButton.Visible = True
Yes2Button.Visible = False
No2Button.Visible = False
Cells(1, 1) = Sheet2.Cells(1, 1)
Sheet2.Cells(1, 7) = 1
End Sub

Private Sub YesButton_Click()
n = Sheet2.Cells(1, 7)
n2 = Sheet2.Cells(n, 2)
If Sheet2.Cells(n, 4) = True Then
Sheet2.Cells(1, 7) = n2
Cells(1, 1) = Sheet2.Cells(n2, 1)
Else
Sheet2.Cells(1, 8) = 2
n2 = "答えは、" & n2 & "ですね?"
Cells(1, 1) = n2
YesButton.Visible = False
NoButton.Visible = False
Yes2Button.Visible = True
No2Button.Visible = True
End If
End Sub

Private Sub NoButton_Click()
n = Sheet2.Cells(1, 7)
n2 = Sheet2.Cells(n, 3)
If Sheet2.Cells(n, 5) = True Then
Sheet2.Cells(1, 7) = n2
Cells(1, 1) = Sheet2.Cells(n2, 1)
Else
Sheet2.Cells(1, 8) = 3
n2 = "答えは、" & n2 & "ですね?"
Cells(1, 1) = n2
YesButton.Visible = False
NoButton.Visible = False
Yes2Button.Visible = True
No2Button.Visible = True
End If
End Sub

Private Sub Yes2Button_Click()
StartButton.Visible = True
Yes2Button.Visible = False
No2Button.Visible = False
Cells(1, 1) = ""
End Sub

Private Sub No2Button_Click()
With Sheet2
r1 = .Cells(1, 7)
c1 = .Cells(1, 8)
ans = .Cells(r1, c1)
str1 = InputBox("正解は、何ですか?", "", "")
str2 = InputBox(ans & "がYESで" & str1 & "がNOとなる質問を考えてください。", "", "")
n1 = .Cells(1, 6) + 1
.Cells(1, 6) = n1
.Cells(r1, c1) = n1
.Cells(r1, c1 + 2) = True
.Cells(n1, 1) = str2
.Cells(n1, 2) = ans
.Cells(n1, 3) = str1
.Cells(n1, 4) = False
.Cells(n1, 5) = False
End With
Yes2Button_Click
End Sub


●2003-02号● グラフ機能でバイオリズム

今回は、グラフの作成についてです。基本的なグラフの種類や範囲指定など必要最小限の事柄について説明します。また例として、簡単なバイオリズム作成マクロを考えてみます。


[リスト1]
Sub Macro1()
Charts.Add
With ActiveChart
.SetSourceData Source:=Sheets("Sheet1").Range("A1:D3"), PlotBy:=xlRows
.ChartType = xlColumnClustered
End With
End Sub

[リスト2]
Sub BioRythm()
str1 = InputBox("生年月日(yyyy/mm/dd)", , Date)
If str1 = "" Then Exit Sub
d1 = Date
d2 = DateValue(str1)
dd = d1 - d2
Pi = 3.1415
With Sheet2
.Cells(1, 1) = "日付"
.Cells(1, 2) = "身体"
.Cells(1, 3) = "感情"
.Cells(1, 4) = "知性"
For i = 0 To 30
.Cells(i + 2, 1) = d1 + i
.Cells(i + 2, 2) = Sin(2 * Pi / 23 * ((dd + i) Mod 23))
.Cells(i + 2, 3) = Sin(2 * Pi / 28 * ((dd + i) Mod 28))
.Cells(i + 2, 4) = Sin(2 * Pi / 33 * ((dd + i) Mod 33))
Next
End With
Charts.Add
With ActiveChart
.ChartType = xlLine
.SetSourceData Source:=Sheets("Sheet2").Range("A1:D31"), PlotBy:=xlColumns
.HasTitle = True
.ChartTitle.Characters.Text = str1 & " 生まれのバイオリズム"
End With
End Sub


●2003-03号● エクセルを使いやすくする!

今回は、Excelを使いやすくするためのユーティリティマクロを考えてみます。例として、Excelおよびシートのウィンドウサイズを設定するものを考えます。また、そのための個人用ブックの利用についても説明します。


[リスト1]
Sub SetExcelWindow()
With Application
.Left = 100
.Top = 100
.Width = 500
.Height = 400
End With
End Sub

[リスト2]
Sub SetSheetWindow()
With ActiveWindow
.WindowState = xlNormal
.Left = 50
.Top = 50
.Width = 200
.Height = 200
End With
End Sub

[リスト3]
Sub SetSheetSplit()
With ActiveWindow
If .Split Then
.Split = False
Else
.Split = True
.SplitColumn = 3
.SplitRow = 10
End If
End With
End Sub

[リスト4]
Private Sub Workbook_Open()
SetExcelWindow
End Sub


●2003-04号● エクセルで簡単メモ帳プログラム!

今回は、実用プログラムの作成を考えてみます。取りあえず、今まで覚えた事柄だけで作れるものとして、メモ帳を作ってみます。ダブルクリックで起動するとメモのウィンドウが現れるもので、Excel本体はまったく見えないため、普通のアプリと同じ感覚で使えます。


[リスト1]
Sub Workbook_Open()
MemoForm.Show
End Sub

[リスト2]
Dim memoNum As Integer

Private Sub UserForm_Initialize()
Application.Visible = False
memoNum = 2
loadNow
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
saveNow
ActiveWorkbook.Save
Application.Quit
End Sub

Private Sub newBtn_Click()
saveNow
n = Sheets("memo").Cells(1, 4) + 1
memoNum = n
Sheets("memo").Cells(1, 4) = n
loadNow
End Sub

Private Sub prevBtn_Click()
If memoNum = 2 Then
MsgBox "これが一番最初のメモです。"
Else
saveNow
memoNum = memoNum - 1
loadNow
End If
End Sub

Private Sub nextBtn_Click()
n = Sheets("memo").Cells(1, 4) * 1
If memoNum = n Then
MsgBox "これが一番最後のメモです。"
Else
saveNow
memoNum = memoNum + 1
loadNow
End If
End Sub

Sub loadNow()
With Sheets("memo")
titleText.Text = .Cells(memoNum, 1)
If .Cells(memoNum, 2) = "" Then
timeText.Text = Now
Else
timeText.Text = .Cells(memoNum, 2)
End If
memoText.Text = .Cells(memoNum, 3)
End With
End Sub

Sub saveNow()
With Sheets("memo")
.Cells(memoNum, 1) = titleText.Text
.Cells(memoNum, 2) = timeText.Text
.Cells(memoNum, 3) = memoText.Text
End With
End Sub


●2003-05号● Webブラウザ・コントロールを使う

今回は、Web Browserコントロールをエクセルのフォームから使ってみます。例として、gooの辞書サーバを使った辞書フォームを作成してみます。

[リスト1]
Private Sub searchBtn_Click()
If EtoJ.Value Then
num = 0
ElseIf JtoE.Value Then
num = 1
Else
num = 2
End If
str1 = urlText.Text
urlstr = "http://dictionary.goo.ne.jp/cgi-bin/dict_search.cgi?MT=" & str1 & "&sw=" & num
browser.webview.Navigate urlstr
End Sub

Private Sub webview_DocumentComplete(ByVal pDisp As Object, url As Variant)
status.Caption = "検索終了。"
End Sub

Private Sub webview_StatusTextChange(ByVal Text As String)
status.Caption = Text
End Sub

[リスト2]
Sub showBrowser()
browser.Show
End Sub



GO NEXT



※連載についてのご意見・質問コーナー


GO HOME