Sie sind auf Seite 1von 18

Introduction to VBA

Mathew Stoessiger

Debugging Code
A breakpoint is a line of code where the program stops running, so that you can examine the variables and see if everything is working as expected. You create a breakpoint by clicking on the left margin opposite the line you want to stop at. The line will be highlighted. Now, when you click Run/Continue, the program will run up to the breakpoint and stop there.

Debugging Code
Watches let you see the value of variables as you Step Into programs The quick Watch function Shift+F9 makes watches particularly easy

Watches
Add watches to all the variables and the Array in this code and then step through the macro using F8. Sub Loops() Dim MyArray(1 To 2, 1 To 4) As Double Dim i As Integer, j As Integer, counter As Integer counter = 1 For i = 1 To 2 For j = 1 To 4 MyArray(i, j) = counter counter = counter + 1 Next j Next i End Sub

Exercise
Can you take 10 numbers in an array and sort them from highest to lowest? Consider using For-Next Loops and If Then constructs Want to time how long your program takes to Run?

At the start of your code add:


Time1 = Timer At the Finish add: WriteTime = Timer - Time1 Msgbox "Write: " & WriteTime

Do - While Loops
The syntax of the Do While Loop is: Do [While condition] [instructions] Loop

Do - While Loops
This procedure opens a text file converts it to uppercase and stores it in the active sheet Sub DoWhileDemo() Dim LineCount As Double Dim LineOfText As String Open "d:\textfile.txt" For Input As #1 LineCount = 0 Do While Not EOF(1) Line Input #1, LineOfText Range("A1").Offset(LineCount, 0) = UCase(LineOfText) LineCount = LineCount + 1 Loop Close #1 End Sub

Exit Do
Do While loops can also contain one or more Exit Do statements. When an Exit Do statement is encountered, the loop ends immediately and control passes to the statement following the Loop statement. This syntax of the Do While Loop is: Do [While condition] [instructions] [Exit Do] [instructions] Loop The Exit Do statement is usually used with an If statement i.e If Counter = 5 Then Exit Do

Text Manipulation
Instr finds one string within another string. The Syntax is: InStr([start, ]string1, string2) Mid Returns a Variant (String) containing a specified number of characters from a string Mid(string, start[, length]) Val Returns the numbers contained in a string Val(string) Test these functions out.

Exercises
Can you modify the Do-While Loop to include an Exit Do statement so that the file will be exit if a * character the first character on a line?

The PBAR Syntax is Pbar,PID,MID,Area,.... Modify the macro to extract the PID and the Area for each PBAR entry place it in an array and then copy the array to the worksheet.

Do Until
The Do Until loop structure is very similar to the Do While structure. The difference is evident only when the condition is tested. In a Do While loop, the loop executes while the condition is True; in a Do Until loop, the loop executes until the condition is True. Do [Until condition] [instructions] [Exit Do] [instructions] Loop

Send a Array to a Range


This code send the elements of an array to the worksheet. Test it out! For i = 1 To NumElements Cells(i, 1) = MyArray(i) Next i

Extend this code above to a 2 dimensional array

Getting Data From Users


You can use a Input Box to get inputs from users. Sub GetValue1() Range("A1").Value = InputBox("Enter the value") End Sub Use input boxes to get the number of rows and columns of a 2 dimensional array and then fill that array with random numbers and output the array to the worksheet. You will need to use the commands: Redim (for the arrary) Rnd() (to generate the random numbers)

Select Cells
The code below lets a user select a cell and places a value in it:
Sub SelectCell() Dim UserCell As Range Set UserCell = Application.InputBox(prompt:="Select a cell", Type:=8) UserCell.Value = 15 End Sub

The key to this is the Type:=8 in the input box

Random Numbers Quickly


Another way to fill cells with random numbers is:
Sub GetUserRange2() Dim UserRange As Range Set UserRange = Application.InputBox( _ prompt:="Select a range.", Type:=8) UserRange.Formula = "=RAND()" End Sub

Dir Function
Dir Returns a String representing the name of a file, directory, or folder that matches a specified pattern or file attribute, or the volume label of a drive Dir(pathname, attributes) To iterate over all files in a folder, specify an empty string: Dir

Batch Processing of Files


You can open all .txt files in the same folder as this workbook using:
Sub BatchProcess2() Dim FileSpec As String Dim i As Integer Dim FileName As String Dim FileList() As String Dim FoundFiles As Integer ' Specify path and file spec FileSpec = ThisWorkbook.Path & "*.txt" FileName = Dir(FileSpec) FoundFiles = 0 Do If FileName = "" Then Exit Do FoundFiles = FoundFiles + 1 ReDim Preserve FileList(1 To FoundFiles) FileList(FoundFiles) = FileName FileName = Dir Loop For i = 1 To FoundFiles Workbooks.OpenText FileName:=FileList(i) Next i End Sub

Exercise
Modify the batch processing macro to copy the contents of all files it opens into separate sheets in one workbook. Can you work out how to close the workbooks once you have copied the data from them.

Das könnte Ihnen auch gefallen