Sie sind auf Seite 1von 50

Excel VBA Macro

Programming
Your First Excel VBA Macro

Private Sub Workbook_NewSheet(ByVal Sh As Object)


MsgBox "Hello World“
End Sub
Variables, Arrays, Constants, and Data
Types
declare a variable using the Dim statement
Dim variablename [As type]
Example
Dim MyInteger as Integer

Explicit Declaration
Option Explicit
Scope and Lifetime of Variables

Local Variables
A local variable uses Dim, Static, or ReDim
(arrays only) to declare the variable within a
procedure.
Module-Level Variables
A module-level variable is declared for a
particular module. It is available to all
procedures within that module but not to the
rest of the application.
Scope and Lifetime of Variables

Global Variables
Global variables are declared in the
declarations part of a module with the Global
statement
Example
Global TempVal
Data Types
Arrays
Dim employee1 as String, employee2 as String,.......
Dim employee(25) as String

Dim temp (1 To 15) as String

Multidimensional Arrays
Dim temp(10,4) as String
Dim temp(10,4,3) as String
Dynamic Arrays
Dim temp() LBound(temp)

ReDim temp(100) UBound(temp)


Constants

Constants are, in effect, variables that do not


change.

Example
Const Path_Name = "C:\temp\"
Modules, Functions, and Subroutines
Modules are where you write your code.
Functions and subroutines are the two
different ways of creating a piece of working
code.
The Difference Between Subroutines and Functions
subroutine is different from a function in that it
does not return anything directly and so
cannot be used directly in the spreadsheet
the way a function can.
Public and Private Functions and
Subroutines
keyword Public or Private
Private Sub PrivateSub()

End Sub
Argument Data Types
Function (Target as String)
Optional Arguments
Function Myfunction (Target as String,
Optional Flag as Integer)
Passing Arguments by Value

use the ByVal or ByRef keyword to define


how parameters are passed to procedure:
example,
x = 100
z = Adjust(x)
Function Adjust(ByRef Target as Integer)

x = 100
z = Adjust(x)
Function Adjust(ByVal Target as Integer)
Programming Basics
Decisions

If..Then..Else

Sub test_if()
If Application.ActiveCell = 5 Then
MsgBox "Cell is 5"
Else
MsgBox "Cell is not 5"
End If
End Sub
Conditional operators
Multiple Conditional Statements

If x = 1 And y > 5 Then


MsgBox "x=1 and y>5"
Endif

If x = 1 Or y > 5 Then
MsgBox "x=1 or y>5"
End If
Select Case Statements

Select Case Grade


Case 1
Msgbox "Grade 1"
Case 2, 3
Msgbox "Grade 2 or 3"
Case 4 To 6
Msgbox "Grade 4, 5 or 6"
Case Is > 8
MsgBox "Grade is above 8"
Case Else
Msgbox "Grade not in conditional
statements"
End Select
Looping
For..Next Loops
For n= 10 to 1 Step -1
MsgBox n
Next n
For Each Loops
For Each allows you to step through each item within the collection
or array.
Sub ShowName()
Dim oWSheet As Worksheet
For Each oWSheet In Worksheets
MsgBox oWSheet.Name
Next oWSheet
End Sub
While..Wend Loops
This continues to loop while a specified
condition is true.
example
Sub test_do()
x =0
While x < 50
x =x +1
Wend
MsgBox x
End Sub
Do Until Loops
keeps looping until a specified condition is met.
example

Sub test_do()
x =0
Do Until x = 100
x =x +1
Loop
MsgBox x
End Sub
Early Exit of Loops
example:
Sub test_exit()
For x = 1 To 100
If x = 50 Then
Exit For
End If
Next x
MsgBox x
End Sub
Functions
Splitting Strings
x=Mid("12Richard",3)

Dim iValue as Integer


IValue = Val("12")

x=Left("12Richard",2)
x=Right("12Richard",2)
Searching Strings
InStr([start, ]string1, string2[, compare])

Example
Instr("Richard Shepherd","shepherd")

InStr(1, "Richard Shepherd", "shepherd", vbTextCompare)


Conversion Functions
Cstr
Cstr converts a value to a string.
CInt
CInt converts a value or a string to an integer
(2 bytes).
CLng
CLng converts a value or a string to a long
integer (4 bytes).
Conversion Functions
CDbl
CDbl converts a value or a string to a double
precision floating point number (8 bytes)
Val
Val converts a string to a value.
Format Function
Format(1234567.89, "#,###.#")
Date and Time Functions
Now
returns the current date and time
Date
returns the current date in short format
Date can also be used to set the current
system date: Date = "03/31/03"
Time
returns the current system time
Date and Time Functions
DateAdd
allows the addition and subtraction of a
specified time interval to a date.
MsgBox DateAdd ("m",1,"1-Jan-03")
Date and Time Functions
DateDiff
returns the number of time intervals between
two specified dates
DateDiff("m", "1-jan-03", "15-mar-03")
Date and Time Functions
DatePart function returns a specified part of a
given date
MsgBox DatePart("q", "1-mar-03")
SendKeys Command
SendKeys sends one or more keystrokes to
the active window as if they had been
entered at the keyboard:
SendKeys keytext [,wait]
Sub test_sendkeys()

x = Shell("calc.exe")

For n = 1 To 10

SendKeys n & "{+}", True

Next n

MsgBox "Press OK to close calculator"

AppActivate "calculator"

SendKeys "%{F4}", True

End Sub
Errors and the Error
Function
Sub Test_Error()
On Error GoTo err_handler
temp = Dir("a:\*.*")
Exit Sub
err_handler:
If Err.Number = 71 Then
MsgBox "The A drive is not
ready"
Else
MsgBox "An error occurred"

End If
End Sub
The Resume Statement

Sub Test_Error()

On Error Resume Next

temp = Dir("a:\*.*")

End Sub
Dialogs
User Form
Properties
Displaying Your Form in Code

Private Sub Workbook_NewSheet(ByVal Sh As Object)


UserForm1.Show
End Sub
Command Bars and Buttons
Sub Test_Menu()
MsgBox "You pressed my menu item"
End Sub

Sub MenuCommand()
CommandBars("Worksheet Menu Bar").Controls _
("Tools").Controls.Add _
(Type:=msoControlButton).Caption = "MyMenu"
CommandBars("Worksheet Menu Bar").Controls _
("Tools").Controls("MyMenu").OnAction = "Test_Menu“
End Sub
Enable And Visible Menu

CommandBars("Worksheet Menu Bar"). _


Controls("Tools").Controls("MyMenu").Enabled =
False

CommandBars("Worksheet Menu Bar"). _


Controls("Tools").Controls("MyMenu").Visible =
False
PopUp Menu
Sub Test_Popup()
Dim newsubitem As Object
CommandBars("Worksheet menu bar").Controls("Tools"). _
Controls.Add(Type:=msoControlPopup).Caption = "MyPopup"
Set newsubitem = CommandBars("Worksheet Menu Bar"). _
Controls("Tools").Controls("MyPopup")
With newsubitem
.Controls.Add(Type:=msoControlButton).Caption = "Option1"
.Controls("Option1").OnAction = "Test_Menu"
.Controls.Add(Type:=msoControlButton).Caption = "Option2"
.Controls("Option2").OnAction = "Test_Menu"
End With
End Sub
The Excel Object Model
Application Object
is at the highest point in the hierarchy of the object
model and represents the whole Excel application.
Main Properties, Methods, and Collections
ActiveCell Application.ActiveCell.Address

ActivePrinter Application.ActivePrinter
ActiveSheet Application.ActiveSheet.Cells (10,10).Select

ActiveWindow Application.ActiveWindow.Caption

ActiveWorkbook Application.ActiveWorkbook.Name
AddIns
Sub test()
Dim MyAddin As AddIn
For Each MyAddin In AddIns
MsgBox MyAddin.FullName
Next
End Sub
Caption
Application.Caption = "MyApplication"
Quit
Application.Quit
Sheets
Application.Sheets("sheet1").Print

Undo
Application.Undo
Version
Application.Version
OperatingSystem
Application.OperatingSystem
Workbook Object
SAVE
Workbooks("book1").Save
SAVE AS …
Workbooks("book3").SaveAs "C:\Myfile.xls"

CLOSE
Workbooks(“book3”).Close
Window Objects
Caption
ActiveWindow.Caption = "MyWindow"
Display Properties
DisplayFormulas
DisplayGridlines
DisplayHeadings
DisplayHorizontalScrollBar
DisplayOutline
DisplayRightToLeft Zoom
ActiveWindow.Zoom = 80
DisplayVerticalScrollBar
DisplayworkBookTabs
DisplayZeros
Example
ActiveWindow.DisplayWorkbookTabs = False
Worksheet Object
PrintOut and PrintPreview
Worksheets("sheet2").PrintOut
Worksheets("sheet2").PrintPreview
Protect
Worksheets("sheet2").Protect ("apple")
Un Protect
Worksheets("Sheet2"),Unprotect ("apple")
Visible
Worksheets("sheet2").Visible = False
Range Object
AddComment
Worksheets("sheet1").Range("a1").AddComment ("MyComment")

Clear
Worksheets("sheet2").Range("a3:d12").Clear

ClearContents
Worksheets("sheet2").Range("a3:d12").ClearContents

ClearFormats
Worksheets("sheet2").Range("a3.d12").ClearFormats

Das könnte Ihnen auch gefallen