Quick Tutorial on VBA Using Excel
Total Page:16
File Type:pdf, Size:1020Kb
Quick tutorial on VBA using Excel
1. Start Excel and go to the Tools menu, Macros, and Record a new macro
2. Record the macro, it doesn’t necessarily need to have anything in it. Click on Stop recording. Go to the Tools menu again, Macros, and select Macros. Your new macro should show up there. Select (highlight) your macro and click on Edit 3. You can now edit the code, just as you would in VB. For example, you can place values in cells like this:
Sub Macro1() Dim i As Integer For i = 1 To 5 Cells(1, i) = 8 Next i Cells(5, 3) = "Hello" End Sub
4. Running the macro yields the following output:
5. You can add your own functions, here is one that will increment the target by 1.
Function addOne(x As Integer) As Integer addOne = x + 1 End Function Simply use the formula like you would in VB
6. The following is an example that will take a string and put each character of that string in an adjacent cell
Sub Parse() Dim strX, strChr As String Dim i, intLen As Integer strX = ActiveCell.Value intLen = Len(strX) For i = 1 To intLen strChr = Mid(strX, i, 1) ActiveCell.Offset(0, 1).Select ActiveCell.Value = strChr Next i End Sub
is the output 7. This VBA code will open a textfile that must already exist, named c:\data.dat and read the values into the spreadsheet. Data.dat is simply a textfile that can be created with NotePad or any other wordprocessor. If you use Microsoft Word to create a textfile, make sure you change the File Type to “text”.
Sub readData() Dim i As Integer Dim strX As String Dim lngVal As Long i = 0 Open "c:\data.dat" For Input As #1 While Not EOF(1) Line Input #1, strX i = i + 1 lngVal = Val(strX) Cells(i, 1) = lngVal Wend Close #1 End Sub
Note: Notice how the loop uses the function to check for and “End of File” EOF before asking for data. Also this example shows how textfiles are used. You must always open the file first. This involves assigning a real filename to a File variable ( in VB the values are #1, #2, etc). Then each read or write to the file is done with that file variable. When you are finished it is very important to Close the file. Unpredictable behavior can occur if you don’t do that (i.e. bad things).
Sample output, which matches the values in data.dat
For the last lab, you could use this code to read in the file, then have Excel verify your code by showing you the max, min, etc.
A good VBA book to start with is Excel Programming by Simon. ISBN 0-7645-3646-X $26.99