Цель работы: изучение возможностей создания MDI – приложений, записи информации в файлы и использование технологии OLE при работе с приложениями MS Office
Задание 1. Разработайте MDI – приложение, позволяющее вводить информацию о студентах: фамилия, имя, факультет, группа (в качестве дочерней формы можно использовать разработанное приложение в задании 4 лабораторной работы 5 – 6). Приложение должно обеспечивать возможность выводить данные о выбранном студенте в существующую дочернюю форму или создавать для каждого студента свою форму.
1) Запускаем Visual Basic 6.0. Выбираем “StandartEXE”.
2) Добавляем в проект MDI - форму. Для этого открываем меню «Проект» → «Добавить MDI- форму»
3) У Form1 устанавливаем значение свойства Child равным True.
4) Создаем меню для MDI- формы, состоящее из пунктов «Добавить форму», «Добавить студента», «Выход» и «Вид окон».
5) Также добавляем в проект модуль.
Код для MDI – формы:
Dim i As Integer
Private Sub New_form_Click()
Dim newform As New Form1
newform.Show
newform.Caption = "Новыйстудент"
End Sub
Private Sub New_student_Click()
add_student
End Sub
Private Sub Exit_Click()
End
End Sub
Private Sub WindowArrange_Click()
MDIForm1.Arrange vbArrangeIcons
End Sub
Private Sub WindowCascade_Click()
MDIForm1.Arrange vbCascade
End Sub
Private Sub WindowTileH_Click()
MDIForm1.Arrange vbTileHorizontal
End Sub
Private Sub WindowTileV_Click()
MDIForm1.Arrange vbTileVertical
End Sub
Коддля Form1:
Private Sub Command1_Click()
Unload Me
EndSub
Код для Модуля1;
Private Type StudentType
fam As String * 30
Name As String * 20
Fac As String * 10
Gru As String * 10
End Type
Public tmp As StudentType
Public arr() As StudentType
Public col As Integer
Sub add_student()
Do
wrk
IfMsgBox("Добавить еще студента???", vbYesNo, "Еще??") = vbNo Then: Exit Do
Loop
End Sub
Sub form_active()
If MDIForm1.ActiveForm Is Nothing Then
Dim tmpfrm As New Form1
tmpfrm.Show
End If
End Sub
Sub wrk()
Dim i As Integer
Dim tmp_str As String
A = MsgBox("Добавить в эту же форму???", vbYesNo, "Куда???")
If A = vbNo Then
Dim tmpfrm As New Form1
tmpfrm.Show
tmpfrm.Caption = "Новый студент"
End If
form_active
Inp_inf_stud tmp
ReDim Preserve arr(col)
arr(col) = tmp
col = col + 1
For i = 0 To 3
With arr(col - 1)
Select Case i
Case 0: tmpstr = .fam
Case 1: tmpstr = .Name
Case 2: tmpstr = .Fac
Case 3: tmpstr = .Gru
End Select
End With
MDIForm1.ActiveForm.List1(i).AddItem tmpstr
Next i
End Sub
Private Sub Inp_inf_stud(ByRef StudentData As StudentType)
Dim s(3) As String
Dim i As Integer
i = 0
Do Until i > 3
Select Case i
Case 0: s(0) = InputBox("Введите фамилию", "Студент")
Case 1: s(1) = InputBox("Введите имя", "Студент")
Case 2: s(2) = InputBox("Введите факультет", "Студент")
Case 3: s(3) = InputBox(“Введите группу", "Студент")
End Select
For n = 0 To 3
If s(n) = "" Then s(n) = "Нетданных"
Next n
With StudentData
Select Case i
Case 0: .fam = s(0)
Case 1: .Name = s(1)
Case 2: .Fac = s(2)
Case 3: .Gru = s(3)
End Select
End With
For n = 0 To 3
s(n) = ""
Next n
i = i + 1
Loop
EndSub
Запускаем приложение (рис.1-3)
Рис.1 MDI – приложение: окна каскадом
Рис.2 MDI – приложение: окна ориентированы вертикально
Рис.3 MDI – приложение: ввод данных
Задание 2. Осуществите запись полученной информации в файл
Добавляем в проект пункт меню «Сохранить все» (для MDI – формы).
Для события save_Clickпишем код:
Private Sub save_Click()
Dim FNamber As Integer
Dim adress As String
Dim i As Integer
Dim k As Integer
FNamber = FreeFile()
adress = InputBox("Введите адрес файла, в котором сохранится информация", "Сохранить как", "E:student.txt")
Open adress For Random Access Write As FNamber Len = Len(arr(i))
Do
If i = col Then: Exit Do
k = i + 1
Put #FNamber, k, arr(i)
i = i + 1
Loop
Close FNamber
End Sub
Запускаем приложение (рис.4,5)
Рис.4 Сохранение данных в файл
Рис.5 Текстовый файл с данными о студенте
Задание 3.
Запишите данные в рабочий ЛИСТ 1 приложения EXCELинтегрированного пакета MSOFFICE.
Добавляем в проект пункт меню «Экспортировать в Excel» (для MDI – формы). Подключаем к VisualBasic 6.0 библиотеку объектов Excel. Для этого открываем меню «Проект» → «Информация». Выбираем MicrosoftExcel 11.0 ObjectLibrary.
Для события Excel_Click записываем код:
Private Sub Excel_Click()
Dim appl As New Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheets
Set appl = New Excel.Application
appl.Visible = True
Set wb = appl.Workbooks.Add
With wb.Worksheets("Лист1")
Dim i As Integer
Dim j As Integer
For i = 0 To co - 1
For j = 1 To 4
Select Case j
Case 1: .Cells(i + 1, j) = arr(i).fam
Case 2: .Cells(i + 1, j) = arr(i).Name
Case 3: .Cells(i + 1, j) = arr(i).Fac
Case 4: .Cells(i + 1, j) = arr(i).Gru
End Select
Next j
Next i
End With
End Sub
Запускаем приложение (рис.6)
Рис.6 Файл EXCEL с данными о студенте
Вывод:
Выполняя данную лабораторную работу, мы научились создавать MDI- приложения. Используя такое приложение, пользователь может одновременно работать с несколькими документами. MDI-приложения позволяют использовать несколько экземпляров одной и той же формы, что увеличивает производительность и гибкость программ.
Также были изучены основные приемы работы с записью данных в файл, а также экспорт данных в приложения MicrosoftOffice, на примере MSExcel интегрированного пакета MSOffice.
Другие работы по теме:
Визуальное программирование в Delphi
Изучение методов визуального программирования в Delphi. Задание: Построить графики функций ; ; Текст программы: unit Graph; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Создание приложений OLE 2
Создание приложений OLE 2 В этом разделе вы создадите два новых приложения OLE. Первое - простая программа-сервер OLE, второе - пример простого контейнера OLE. Эти программы предназначены для демонстрации минимальных затрат программирования, необходимых для создания приложений OLE 2.
Federalists Vs Antifederalists Essay Research Paper Federalists
Federalists Vs. Antifederalists Essay, Research Paper Federalists vs. Antifederalists To amend the Articles of Confederation, unanimous approval by all thirteen colonies was a necessity. Instead of reforming the preexisting document, it was decided that once approved by nine states, a newly written document would become the supreme law of the land.
Worms Essay Research Paper Welcome to WORMS
Worms Essay, Research Paper Welcome to WORMS ARMAGEDDON by Team17. We have worked very hard to try and include every last ounce of playability, options, features and cool ideas into this game, we hope that you enjoy it.
Progressivism Essay Research Paper The Progressive EraThe
Progressivism Essay, Research Paper The Progressive Era The Progressive Era initiated reforms that benefited the individual and the whole society. Industrial and social reforms were launched to benefit the individual and the whole society. Movements were begun to help the individual benefit from the corrupt industrial system .
Jeffersonian Republicans Vs Madison Administratoin Essay Research
Paper In the time period between 1801 and 1817 the Jeffersonian Republicans were regarded as strict constructionists however this political party made many decisions that were characterized as broad constructionism. The Federalists who were characterized as broad constructionism also abandoned their method of interpreting the constitution more than once and interpreted the constitution quite strictly.
Islam Expansion Essay Research Paper The Islamic
Islam Expansion Essay, Research Paper The Islamic civilization spread to such an extensive empire through many techniques. They conquered neighboring areas rapidly. They spread Islam onto the people in three ways. One practice that caused them to spread was their expertise on war. Another would be the forced conversion of Islam to the people.
Telephone Usability Essay Research Paper Socalled data
Telephone Usability Essay, Research Paper So-called data phones have not sold well so far. I do believe in the integration of telephony and computing, but data phones will not take off as long as they are designed from the wrong conceptual model. So far, all these devices have been designed as telephones with a data add-on.
Documents Reflect History Essay Research Paper Written
Documents Reflect History Essay, Research Paper Written documents reflect what has happened. Actions that may have happened in history, give historical documents a reason to be. Although actions may not have occurred to cause documents to be written, they may have been just to prevent them from happening.
None Essay Research Paper host granting access
None Essay, Research Paper host, granting access rights to anyone using the guest computer, carry out the following procedure. NOTE: The following procedure is just one of many that could be used
View From The Bottom Rail
– Slavery Essay, Research Paper January 29, 2001 HIS 2112 Dr. Harris A View From the Bottom Rail The View From the Bottom Rail is a document dealing with the ways in which historians have tried to recover the newly freed slaves’ feelings and point of view after the Civil War. In almost every way, it is impossible to determine what the slaves really thought and felt about slavery and their masters because of the lack of proper evidence.
Cgi Scripts Essay Research Paper CGI Scripts
Cgi Scripts Essay, Research Paper CGI Scripts Must have Internet service provider that will allow you to run CGI scripts. You should really have telnet access to your account, too
Islam Spread Essay Research Paper Islam is
Islam Spread Essay, Research Paper Islam is known as one of the fastest-expanding religions in history. Only contained in Arabia in 632, its conquests led to its expansion to Persia and
Project 2 Cases 2 Essay Research Paper
Project 2 Cases 2 There are several features in Microsoft Word 2000 that makes document making simple. With features like Automatic Spell Checking, that places a red wavy line under the word that is misspelled automatically. Auto Correct, which automatically corrects commonly, made mistakes that are predetermined in Word.
IMPROVING DOCUMENT PRODUCTIVITY Essay Research Paper IMPROVING
IMPROVING DOCUMENT PRODUCTIVITY Essay, Research Paper IMPROVING DOCUMENT PRODUCTIVITY My plan for improving my productivity in producing documents is to focus on time management and on work organization. If you can improve both of these factors, my overall productivity will be significantly higher.
Declaration Of Independence 2 Essay Research Paper
The Declaration of Independence The Declaration of Independence is made up of five distinct parts: the introduction; the preamble; the body, which can be divided into two sections; and a conclusion. The introduction says that the declaration will declare the causes that have made it required for the American colonies to leave the British Empire.
Multiple Sclerosis 2 Essay Research Paper Multiple
Multiple Sclerosis 2 Essay, Research Paper Multiple Sclerosis is a disease in which areas of the brain, spinal cord, and peripheral nerves are stripped of their myelin, which is the fat covering that insulates the nerve fibers. This makes it harder for the transmission of messages between the central nervous system and the rest of the body.
Basic Html Essay Research Paper There are
Basic Html Essay, Research Paper There are six basic steps you must follow in order to create a web page in HTML. For those who don t know what it HTML is, it is the coding language that is used to create, develop, and maintain these WebPages such as Yahoo, MSN, Altavista, etc. Although there are other complex languages such as XML and DHTML, they are derived from the basics of HTML.
Poison Essay Research Paper PoisonA Game Instructions
Poison Essay, Research Paper Poison A Game Instructions: Start off with ten counters. Each team will take a turn, taking one or two counters each time. The team that must take the final counter, also known as the poison counter, loses.
An Arrest Warrant Essay Research Paper Arrest
An Arrest Warrant Essay, Research Paper Arrest Warrant In the case of Darlie Routier, an arrest warrant was needed to be issued so that Darlie would be taken to the police station by a police officer. The officer woho signed Darlie’s arrest warrant was Officer Jimmy Patterson. The warrant spelled out the police version of the story and it was later released to the media.
The Fight Club
& Multiple Personality Disorder Essay, Research Paper THE FIGHT CLUB There are many people in the world that suffer from any kind of disease or mental problem. In the movie ?the fight club? the narrator, Edward Norton, suffers from multiple personality disorder. This is a mental disorder that affects almost one million Americans, making their life difficult and troublesome. (www.geocities/HotSprings/Villa/8755/) The movie is particularly characterized by the fact that the main character and narrator suffers from this popular disorder.
Iomega Zip Drives Essay Research Paper Iomega
Iomega Zip Drives Essay, Research Paper Iomega offers a wide range of zip drives which include the USB Port drives, parallel Port drives, SCSI port drives, and Internal drives. There are advantages and disadvantages to each of the four mentioned. Like any other item you wish to purchase you should know what you needs are before you purchase a zip drive, so that you may purchase the right unit.
The Declaration Of Independence Essay Research Paper
The Declaration of Independence is one of the most important documents ever written. In honor of the total separation of America from British rule, Thomas Jefferson, Benjamin Franklin, and John Adams wrote the document. The document is broken down into two parts. The first part of the document is based on the theory of John Locke, that governments are there to protect life, liberty, and property of its people.
Cpu Internal Organisations Essay Research Paper CPU
Cpu Internal Organisations Essay, Research Paper CPU Internal Organisations The input/output (I/O) interface, bus structures, microprocessor, memories and peripherals (also known as external or I/O devices) are the major components of a computer system. These components constantly trade information and instructions to complete assigned operations.
Backup Disaster Essay Research Paper IS 40
Backup Disaster Essay, Research Paper IS 40 Assignment Planning for disaster With the increasing usage of computers in the education field, I as a student and many other of my classmates are compelled to develop a backup strategy for our assignments. A strategy which will wipe out my fear of loosing my document to a computer hard disk failure, accidental erased and many other possibilities that could occur.
Bill And Monica An Oral History Essay
, Research Paper The Solution The purpose of Plagiarism and Turnitin is to help put a stop to digital plagiarism. This means that papers will never again be recirculated or recycled every year, that papers will not be copied from one class and used for a different class, that papers from one university will not find their way to another university course, and finally, that papers acquired from the Internet will never be used to fulfill a course requirement.
How To Do Frames On Web Sites
Essay, Research Paper How To Do Frames On Web Sites Dividing a web page into frames is quite simple. Frames organize web pages by dividing them into rows or columns. The
Understanding Maya
Maya is a character animation and visual effects system designed for the professional animator. To understand how Maya works at a conceptual level. The user interface and marking menu. Perspective and orthographic cameras. Image planes onto the camera.