VBA 2
-
Upload
kunal-bhodia -
Category
Documents
-
view
216 -
download
0
Transcript of VBA 2
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 2/44
Open EOF
Freefile
Input Input#
Line Input
Write
Close Reset
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 3/44
This function is used to open a file for eitherinput or output, depending on the exactsyntax used.
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 4/44
You use this function to obtain the next validnumber for use when performing fileoperations
Note that after allocating a number in thisway, you must open or close a file beforeusing it again, otherwise the same number is
generated.
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 5/44
◦ intInFile = FreeFileintOutFile = FreeFileOpen "C:\in.txt" For Input As intInFileOpen "C:\out.txt" For Output As intOutFile
◦ intInFile = FreeFileOpen "C:\in.txt" For Input As intInFileintOutFile = FreeFileOpen "C:\out.txt" For Output As intOutFile
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 6/44
This function indicates when you havereached the end of a file, and as such it isnormally used as the condition for a Do loop.
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 7/44
This function will read data from a file thathas been written to using the Write function.
As this means that text will normally bedelimited with quotes and similar, it is not of
much use for general text importing.Modecan be
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 8/44
This function will input a line at a time from the textfile
You will often read this into a temporary variable, andthen split it using the string handling functions (Left,Mid, etc.) as required
This is probably of most use when you have a recordof fixed width
One trick with this function is to read the whole file inone go
this is often faster than reading it line by line or
character by character, and then separating it
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 9/44
Sub sImportAll()
On Error GoTo E_HandleDim strImport As StringDim lngChars As LongDim intFile As IntegerintFile = FreeFileOpen "C:\test.txt" For Input As intFile
Do while not EOF( intFile )
line input #intfile,fieldsmsgbox fields
LoopGoto E_exit
E_Handle:
MsgBox Err.Description, vbOKOnly + vbCritical, "Error: " & Err.NumberE-exit:End Sub
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 10/44
This function is used to write data to anoutput file.
I would normally use this function, ratherthan Write, as it does not wrap data in specialcharacters, making the exported moreuniversally available.
E.g. Print filenumber, string
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 11/44
This function is used to write data to a file,
but as it 'wraps' data with special characters(such as double quotes)
it is not that useful as far as exporting datafor use in other programs is concerned
Also be aware that it ignores locale settings,such as the decimal separator.
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 12/44
You use this function to close a file that hasbeen opened using the Open statement.
It is important to close files that you haveopened, either using this function or Reset,otherwise they are 'locked'.
E.g. close filenumber
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 13/44
Returns the number of bytes in a file
E.g.Filelen(filenumber)
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 14/44
You use this function to reset all files that havebeen opened
therefore it should be used with care, as you mayfind yourself closing a file that has been openedin another procedure
Unless I know that I have a file open in anotherprocedure, I will normally have this statement inthe exit point for a procedure, otherwise I will
use the Close statement on each individual file.
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 15/44
You encounter error while running the code
Not all error are because of bad code
You might encounter an error because the
procedure might anticipate different data Type Whatever is the cause, you will need determine
source of the error and resolve the issue
The process of finding error is called debugging
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 16/44
Design Error
Compile Error
Runtime Error
Logical Error
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 17/44
Predominantly created when you write code
Most design errors are syntax error when youmistype a statement
You create design errors when you forget aboutfunction argument or missing paranthesis
E.g MsgBox(“sample text”
As long as you use the code setting of VBA
editor, you immediately know when a syntaxerror occurs
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 18/44
Compiling is converting the VBA to the formatthat computer can understand
In other languages you need to compile
before you run the code In VBA compilation of code happens when
you run the macro/subroutine If any error occurs during compile process an
error message box pops up and VBA editorhighlights the location of the error
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 19/44
You encounter runtime errors when your codeexecutes
If you not handled runtime error the
execution of macro/procedure stops To avoid stopping of execution you need to
write
On Error Resume Next
VBA put information of error in “Err” Object
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 20/44
Err Object
Error object property
Description Contains VBA descriptionof the runtime error
Number Contains VBA errornumber of the runtimeerror
Source Indicate name of thecurrent procedure whichhas caused as error
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 21/44
Logical error do not produce any type of errormessage
Instead logical error return unexpected result
E.g Price1 = 4.45
Price2 = 6.95
TotalCost =(Price1 +price2)*1.75
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 23/44
Workbook can be opened using Open Methodof workbooks Collection
It requires filename
E.g.Workbooks.Open(“C:\Workbooks\budget.xls”)
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 24/44
You can open a text file within Excel usingOpenText method of workbooks collectionmethod
It requires filename Text file remains text file but you can modify
it using excel as editor
E.g. Workbooks.Opentext filename : =“C:\Workbooks\Sample.txt”), Datatype :+xlDelimited, Tab:= True
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 25/44
you can retrieve the name of the file withprompting the user with Open dialog box
To display open dialog box, you use theGetOpenFileName method
When you use this method file does not openwhen user clicks ok. The dialog passes thename to variable name and then you canopen the file using open property
E.g. Dim UF as Variant Application.GetOpenFileName(FileFilter :=
“*.txt”, Title:= “Text Files”
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 26/44
You can save currently selcted workbookusing save or save as method.
e.g workbooks(sample.xls).save
Thisoworkbook.saveas Filename:= Test.xls
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 27/44
You can request the name, location andformat for saving workbook file from the user
e.g GetSaveAsFileName opens dialogbox
The dialog box does not save the file whereas
it retunes user specified information information to a variable
To save the file you use SaveAs command
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 28/44
Myworkbook = workbooks(1).name You can compare Myworkbook to filename
you want to check
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 29/44
You can close the workbook using close method
E.g. Activeworkbook.close or Thisworkbook.close
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 30/44
You can create new workbook using the Add method of workbooks collection
E.g. workbooks.Add(Tempalate)
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 31/44
VBA provides ability to delete workbook or any othe file suing Kill method
E.g. kill(pathname)
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 32/44
You can find file on your computer By using this you can check if file exits
before doing any operation on the file
You use “FileSearch” object to serach for file
on the computer
You can set .filename property to filename you want to search
You can set .LookIn property to directory where you want to search the file
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 33/44
PRN – 11 Name-12
Course-5
Sem-3
PERCENTAGE-3
Grade-2
-
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 35/44
Axes Collection – Collection of Axis objects including Axistilte, Border,Gridlines and Ticklables
Chart Area – Chart Area including Border,Font
and Interior object Chartobjects Collection- Collection of chart
objects on the sheet
Charttitle
Datatable – represents chart data table
Legend
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 36/44
There are different chart types available You can select charttype by specifying
xlChartType constant value of Charttype property
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 37/44
Dim Newchart as Chart Set Newchart = Thisworkbook.charts.Add()
NewChart.Name = “My Chart Sheet”
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 38/44
With any chart you must specify chart’s range of data
You use SetSourceData method to specify datasource for your chart
E.g Mychart.SetSourceData
Source:=Worhsheets(“Sheet1”).Range(“A1:A5”)
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 39/44
Dim Echart Aas ChartObject Set Echart
=Sheets(“Sheet1”).ChartObjects.Add(left:=50,top:=100, Widhth:=300, Height :=400)
Setting the chart type Worksheets(“Sheet1”).Chartobjects(1).chart.ch
artytype =xlColumstacked
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 40/44
You can use “chartwizard” method of specific chartobject to set different properties of chart objects
Source
Gallery
Format PlotBy
CategoryLabels
SeriesLabels
HasLegend Title
CategoryTitle
ValueTitle
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 41/44
e.g.Dim SelectChart As Chart
Set SelectChart =ThisWorkbook.Charts(“Chart2”)
SelectChart.ChartWizard Gallery:=xL3DLine,
Format=2,Categorylables:= True
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 42/44
To define new Data series or to add to existing dataseries you create a new “Series” object and add it to SeriesCollection object using add method
E.g SelectChart.SeriesCollection.Add
Source:=Worksheets(“Sheet1”).Range(“D1:D7” )
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 43/44
You can customize the text of the chart by changing font and colour attribute
e.g.
With Selectchart
.ChartArea.Font.Name =“Tahoma”
.ChartArea.Font.Colour = RGB(0,0,255)
7/29/2019 VBA 2
http://slidepdf.com/reader/full/vba-2 44/44
You can customize each Axis of the chart using Axis Object properties and Methods
Each Chart Axis is separate object
Axes collection object contains all chart Axis
objects E.g. with SelectChart.Axes(xlValue)
.HasTitle =True
.AxisTitle.Text =“Value Axis”