vb :: DBgrid/DBFlexGrid 사용예제

#DBgrid컨트롤 사용하기
1] DBgrid를 사용하려면 구성요소에서 [microsoft data bound grid control]을 선택한다.
2] 다음과 같이 컨트롤을 위치시키고 속성을 설정한다.
속성설정DBgrid1
└ dataSource : data1
└ headFont : 굴림
└ caption : 고객데이터
data1
└ databaseName : Nwind.mdb
└ recordSource : customers
└ visible : false

사용자 삽입 이미지
이 경우에서 데이터컨트롤은 DB를 연결시켜주는 역할만 하므로 이것의 속성중 visible속성을 true에서 false로 변경시켜주면 데이터컨트롤을 보이지 않게 할 수 있다.
실행모드에서는 column이나 row의 크기를 변경시킬 수 있다.
 
#MSFlexGrid컨트롤 사용하기
1] MSFlexGrid컨트롤을 사용하려면 구성요소에서 [microsoft flexGrid control 6.0]을 추가한다.
2] 다음과 같이 컨트롤을 위치시키고 속성을 설정한다.
속성설정MSFlexGrid1
└ dataSource : data1
└ fixedCols : 0
└ toolTipText : 스크롤바를 이용하여 검색하세요
└ allowUserResizing : 1(flexResizeColumn) - 크기변경가능
data1
└ databaseName : nwind.mdb
└ recordSource : customers
└ visible : false

3] 연결된 DB의 일부데이터만을 보기로 한다. 그래서 필요한 데이터만을 선택하여 새로운 데이터를 만들고 모양을 조금 변경시켜 보도록 한다.
소스코드Private Sub Form_Load()
    Dim sql As String
    '원시 nwind.mdb의 필드중 customerID, companyName, contactName
    'address, city, phone만을 sql문을 이용해 새롭게 DB를 만든다.
   
    sql = "SELECT customers.customerID, customers.companyName"
    sql = sql + ", customers.contactName, customers.address, customers.city"
    sql = sql + ", customers.phone FROM customers"
   
    Data1.RecordSource = sql
    Data1.Refresh
    Data1.Recordset.MoveLast
   
    totrows = Data1.Recordset.RecordCount
    MSFlexGrid1.Rows = totrows + 5      'rows는 필드네임행까지 포함, 늘어나는 행수는 4
   
    'MSFlexGrid의 record heading채우기
   
    MSFlexGrid1.Row = 0     '셀좌표
    MSFlexGrid1.Col = 0
    MSFlexGrid1.Text = "고객번호"       '필드네임을 변경한다.
    MSFlexGrid1.ColWidth(0) = 1000      'column폭을 조정한다.
   
    MSFlexGrid1.Col = 1
    MSFlexGrid1.Text = "회사명"
    MSFlexGrid1.ColWidth(1) = 1000
   
    MSFlexGrid1.Col = 2
    MSFlexGrid1.Text = "담당직원"
    MSFlexGrid1.ColWidth(2) = 1000
   
    MSFlexGrid1.Col = 3
    MSFlexGrid1.Text = "주소"
    MSFlexGrid1.ColWidth(3) = 3000
   
    MSFlexGrid1.Col = 4
    MSFlexGrid1.Text = "시"
    MSFlexGrid1.ColWidth(4) = 1500
   
    MSFlexGrid1.Col = 5
    MSFlexGrid1.Text = "전화번호"
    MSFlexGrid1.ColWidth(5) = 2000
    Data1.Recordset.MoveFirst
   
    'table의 record채우는 소스예제
    For i = 1 To totrows
        MSFlexGrid1.Row = MSFlexGrid1.Row + 1
        MSFlexGrid1.Col = 0
        MSFlexGrid1.Text = Data1.Recordset.Fields("customerID")
        MSFlexGrid1.Col = 1
        MSFlexGrid1.Text = Data1.Recordset.Fields("companyName")
        MSFlexGrid1.Col = 2
        MSFlexGrid1.Text = Data1.Recordset.Fields("contactName")
        MSFlexGrid1.Col = 3
        MSFlexGrid1.Text = Data1.Recordset.Fields("address")
        MSFlexGrid1.Col = 4
        MSFlexGrid1.Text = Data1.Recordset.Fields("city")
        MSFlexGrid1.Col = 5
        MSFlexGrid1.Text = Data1.Recordset.Fields("phone")
       
        Data1.Recordset.MoveNext
    Next i
   
End Sub

사용자 삽입 이미지
4] 실행하면 조금 더 조정된 폼을 볼 수 있다.
Posted by 나비:D
:
vb :: 드라이브, 폴더, 파일처리 _파일에 데이터추가
텍스트 파일이 작성된 뒤 파일에 데이터를 추가하려면 다음 단계를 밟으면 된다.
- 파일열기 :: file.openAsTextStream 또는 fileSystemObject.openTextFile
- 데이터추가 :: write 또는 writeLine과 writeBlankLines 모두 textStream개체로 writeLine메서드는 지정된 문자열 끝에 줄바꿈 문자를 추가하고 커서를 다음라인 첫칸으로 이동한다.  writeBlankLines메서드는 새 줄을 텍스트파일에 추가하는 것이다.
- 파일닫기 :: textStream.close
 

#아래 예제는 3개의 쓰기 메서드 모두를 사용하여 파일을 열고 데이터를 추가하고 파일을 닫도록 한다.
사용자 삽입 이미지
소스코드Private Sub Command1_Click()
    Dim fso, txtfile
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set txtfile = fso.CreateTextFile("c:\my documents\test.txt", True)
   
    txtfile.Write ("테스트용입니다. ")
    txtfile.WriteLine ("테스트 1, 2, 3")
    txtfile.WriteBlankLines (3)
    txtfile.Write ("3줄 다음입니다.")
    txtfile.Close
End Sub


#파일읽기
텍스트파일에서 데이터를 읽으려면 다음 메서드들이 사용된다. 이들은 모두 textStream개체들이다.
메서드
설 명
read 파일에서 지정된 개수의 문자를 읽는다.
readLine 줄바꿈 문자(줄바꿈 문자제외)까지 한 줄 전체를 읽는다.
readAll 텍스트파일의 전체내용을 읽는다.
skip 지정한 문자를 뛰어 넘어 읽는다.
skipLine 지정한 줄을 뛰어 넘어 읽는다.

다음은 파일을 작성하여 쓰고, 다시 읽는 예제코드이다.
소스코드Private Sub Command1_Click()
    Dim fso As New FileSystemObject, txtfile, fil1 As File, ts As TextStream
    fso.CreateTextFile ("c:\my documents\read.txt")
   
    Set fil1 = fso.GetFile("c:\my documents\read.txt")
    Set ts = fil1.OpenAsTextStream(ForWriting)
   
    ts.WriteLine "안녕하십니까?"
    ts.WriteLine "반갑습니다."
    ts.Close
   
    Set ts = fil1.OpenAsTextStream(ForReading)
   
    Print ts.ReadLine
    Print ts.Read(3)
    ts.Close
End Sub


#파일 이동, 복사, 삭제
FSO모델에는 파일을 이동하고 복사하고 삭제하기 위한 메서드가 다음표처럼 각각 두개씩 있다.
메서드
설 명
file.move 또는 fileSystemObject.moveFile 파일 이동
file.copy 또는 fileSystemObject.copyFile 파일 복사
file.delete 또는 fileSystemObject.DeleteFile 파일 삭제
아래 예제는 c드라이브의 내문서폴더에 텍스트파일을 만들고 그 파일에 대한 정보를 작성하여 \tmp라는 폴더로 이동하고 \temp라는 폴더에 사본을 만들고 두 폴더 모두에서 사본들을 삭제한다.

이 예제를 실행하려면 내 문서폴더에 temp폴더와 tmp폴더가 있어야 한다.
소스코드Private Sub Command1_Click()
    Dim fso As New FileSystemObject, txtfile As TextStream, fil1, fil2 As File
   
    Set txtfile = fso.CreateTextFile("c:\my documents\test.txt", True)
    txtfile.Write ("테스트용입니다.")
    txtfile.Close
   
    Set fil1 = fso.GetFile("c:\my documents\test.txt")  '지정파일에 대한 핸들을 가져온다.
    fil1.Move ("c:\my documents\tmp\test.txt")
    fil1.Copy ("c:\my documents\temp\test.txt")
   
    Set fil1 = fso.GetFile("c:\my documents\tmp\test.txt")
    Set fil2 = fso.GetFile("c:\my documents\temp\test.txt")
    fil1.Delete
    fil2.Delete
End Sub
Posted by 나비:D
:

출처 : http://cafe.naver.com/muchknow.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=82

Public Function IsBeing(경로 As String, Optional 형식 As Byte = 0) As Boolean
'먼저 프로젝트메뉴->참조의 Microsoft Scriping Runtime 을 참조해야 합니다.
'형식 Value : 0 -> 파일, 1 -> 디렉터리,  2 -> 드라이브
    Dim fso As New FileSystemObject
    Dim objDrive As Object


    Select Case 형식
        Case 0
            IsBeing = IIf(fso.FileExists(경로), True, False)
        Case 1
            IsBeing = IIf(fso.FolderExists(경로), True, False)
        Case 2
            IsBeing = IIf(fso.DriveExists(경로), True, False)
    End Select
End Function


 

자동업데이트 스크립트 생성기 만들면서 폴더선택하는 거 한답시고 API폴더 파인드 만질래다가 포기하고

그냥 텍스트 박스에서 써넣은 후 아래 함수로 체크해서 하위폴더중 없는 폴더가 있으면 자동으로 생성하는

함수를 만들었네요.. 인덱스를 Integer을 썼으니 6만 얼마 생성가능한데 OS가 그만큼 지원해주는지는 모르

겠네여.. 어쨋든 유용하게 써먹으시길


'이 함수는 경로를 인수로 받아서 디렉터리가 있는지 확인하고 없으면 생성시켜주는 함수입니다.
Public Function IsBeingDir(StrPath As String) As Boolean
    On Error GoTo err
  
    If IsBeing(StrPath, 1) = True Then
        IsBeingDir = True
        Exit Function
    End If


    Dim FolderCount() As String
    Dim DiffStr As String
    Dim Idx As Integer
    FolderCount = Split(StrPath, "\")

    DiffStr = FolderCount(0)
    For Idx = 1 To UBound(FolderCount)
        DiffStr = DiffStr & "\" & FolderCount(Idx)
        If IsBeing(DiffStr, 1) = False Then
            MkDir DiffStr
        End If
    Next
    IsBeingDir = True
    Exit Function
err:
    IsBeingDir = False
End Function


Posted by 나비:D
:
visual basic6.0부터는 Open문을 사용해 파일만을 처리했던 구 버전과는 달리 파일은 물론, 드라이브, 폴더까지 다룰 수 있는 FSO(File System Object)모델을 소개하고 있다. FSO모델을 사용하면 폴더를 작성, 변경, 이동, 삭제뿐만 아니라 폴더에 대해 여러가지 정보를 얻을 수 있다. 또한 파일을 쉽게 처리할 수 있다.  파일을 처리하는 주요목표는 공간과 컴퓨터자원을 효율적으로 사용하고 접근하기 쉬운 데이터를 저장하는 것이다. 이러한 파일처리목표를 달성할 수 있는 것이 FSO모델이다.
 
#파일시스템개체(FSO)구성
FSO모델의 개체구성원을 사용하려면 먼저 [프로젝트-참조]메뉴를 선택해 참조대화상자에서 "Microsoft Scripting Runtime"을 선택해야 한다.
 Scripting형식 라이브러리를 참조했다면 [보기-개체찾아보기]메뉴를 선택하여 개체찾아보기 대화상자에서 Scripting라이브러리를 선택하면 개체에 들어 있는 다양한 속성과 메서드 그리고 이벤트에 대한 내용을 볼 수 있다.
FSO모델은 아래와 같이 대표적인 개체로 구성되어 있다.
- drive :: 시스템에서 사용할 수 있는 디스크공간, 디스크의 공유이름과 같은 디스크정보를 얻을 수 있게 해준다. "drive"에는 하드디스크 이름이외에도 cd-rom드라이브, ram디스크와 같은 이름을 사용할 수 있다.
- folder :: 폴더를 만들고 삭제하고 이동할 수 있도록 해주며 이름과 경로 등에 대하여 시스템에 쿼리할 수 있게 한다.
- files :: 파일을 만들고 삭제하고 이동할 수 있도록 해주며 이름과 경로 등에 대하여 시스템에 쿼리할 수 있게 한다.
- FileSystemObject :: 그룹의 주 개체로 드라이브, 폴더, 파일을 일반적으로 조작하고 만들고 삭제하고 정보를 얻을 수 있도록 해주는 메서드가 들어있다.  이 개체와 연관된 많은 메서드들은 다른 개체에 들어있는 메서드들과 중복되어 있다.
- textStream :: 텍스트파일을 읽고 쓸 수 있게 한다.
 
#FSO모델 프로그래밍
이러한 FSO모델로 드라이브, 폴더, 파일을 다루려면 다음과 같은 3가지작업이 필요하다.
- CreateObject메서드를 사용하거나 변수를 FileSystemObject개체로 선언하여 FileSystemObject개체를 하나 만든다.
- 새로 만든 개체에 적절한 메서드를 사용한다.
- 개체의 속성을 엑세스한다.
 
#FileSystemObject개체 만들기
첫째 작업은 작업할 FileSystemObject개체를 만드는 것으로, 다음 두가지 방법이 있다.
  |형식| dim fso as new FileSystemObject  '변수를 FileSystemObject개체형식으로 선언
또는
  |형식| set fso = CreateObject("scripting.FileSystemObject")  'CreateObject메서드를 사용하여 FileSystemObject개체를 만든다.

#적절한 메서드사용
다음 작업은 FileSystemObject개체의 적절한 메서드를 사용하는 것이다.
예를 들어, 폴더에 대해선 CreateFolder메서드를 사용하여 폴더를 작성한다거나 MoveFolder메서드를 사용해 폴더를 이동할 수 있다.
 
#개체의 속성 엑세스
개체에 대한 핸들을 얻으면 get메서드를 사용하여 개체의 정보를 액세스할 수 있다. 예를 들어 특정폴더의 이름을 얻으려면 먼저 해당개체의 인스턴스를 하나 만들고 적절한 메서드를 사용하여 인스턴스에 대한 핸들을 얻을 수 있다.
다음은 이러한 3가지 단계를 이용해 새 폴더를 만들어보고, 기존 폴더에 대한 정보를 액세스하는 예제코드이다.
소스코드Private Sub Form_Click()
    Dim fso As New FileSystemObject, existF, newF As Folder
           
    Set newF = fso.CreateFolder("c:\my documents\test")
    Set existF = fso.GetFolder("c:\my documents")
   
    Debug.Print "새 폴더이름 :"; newF.Name
    Debug.Print "기 폴더이름 :"; existF.Name
    Debug.Print "새 폴더 작성시간 :"; newF.DateCreated
    Debug.Print "기 폴더 작성시간 :"; existF.DateCreated
End Sub
이 예제코드에서 createFolder메서드를 사용하여 새폴더를 만들 때는, name, path, dateCreated와 같은 속성을 액세스하는데 getFolder메서드를 사용할 필요가 없다. 반면에 기존에 있는 폴더의 속성을 액세스하려면 반드시 getFolder메서드가 필요함을 보여주고 있다.
Posted by 나비:D
:

 비주얼 베이직에서 사용하는 모든 함수를 배워봅시다.



 : 자주사용하는 함수


 : 일반적으로 많이 아는 함수


 : 특수한 경우에만 사용하는 함수

 ◈ 함수명 : Abs

 ◈ 함수명 : Array

 형식 : Abs(number)

 형식 : Array(arglist)

 설명 : 가로안의 수치에 대한 절대값을 구합니다.

 설명 : 배열이 포함된 값을 반환합니다.

 예제 : Abs(21.7) ☞ 21.7을 반환합니다.
          Abs(-21.7) ☞ 21.7을 반환합니다.

 예제 : m=Array("월","화","수","목","금","토","일")
          d=m(2) ☞ d에는 "화"가 들어갑니다.

 ◈ 함수명 : Asc

 ◈ 함수명 : Atn

 형식 : Asc(string)

 형식 : Atn(number)

 설명 : 문자열의 첫 글자에 해당하는 문자 코드를 나타내는           integer 값을 반환합니다.

 설명 : 가로안의 수치의 아크탄젠트(arctangent)값을           지정하는 Double을 반환합니다.

 예제 : Asc("A") ☞ 65를 반환합니다.
          Asc("a") ☞ 97를 반환합니다.

 예제 : pi=4*Atn(1) ☞ 원주율의 값을 계산합니다.
          Atn은 삼각함수 Tan의 역함수입니다.

 ◈ 함수명 : Choose

 ◈ 함수명 : Chr

 형식 : Choose(index,선택1,선택2....)

 형식 : Chr(charcode)

 설명 : 인수목록에서 값을 선택하고 그 값을 반환합니다.

 설명 : ASCII코드값에 해당되는 문자를 반환합니다.

 예제 : Gsun=Choose(ind,"빠름","중간","느림")
          ☞ ind값에 따라 선택목록에서 값을 반환합니다.

 예제 : Chr(65) ☞ A를 반환합니다.
          Chr(97) ☞ a를 반환합니다.

 ◈ 함수명 : Command

 ◈ 함수명 : Cos

 형식 : Command

 형식 : Cos(number)

 설명 : 비주얼베이직으로 개발된 실행 프로그램을 시작했던           명령줄의 인수부분을 반환합니다.

 설명 : 특정한 각의 코사인 값을 반환합니다.

 예제 : VB /cmd cmdinsu ☞ cmdinsu는 Command함수에           의해 반환된 인수를 나타냅니다.

 예제 : Cos(30) ☞ Cos 30도 값을 반환합니다.

 ◈ 함수명 : CreateObject

 ◈ 함수명 : CurDir

 형식 : CreateObject(class)

 형식 : CurDir(drive)

 설명 : ActiveX 개체에 대한 참조를 만들거나 반환합니다.

 설명 : 현재 경로를 나타내는 문자열을 반환합니다.

 예제 : CreateObject("Excel.Application)
          ☞ Excel.Application개체에 대한 참조를 만들어               전달합니다.

 예제 : CurDir ("C") ☞ 현재 경로가 "C:\vbasic\연습"이라면           이 경로값을 반환합니다.

 ◈ 함수명 : CVErr

 ◈ 함수명 : Date

 형식 : CVErr(errornumber)

 형식 : Date

 설명 : 사용자가 지정한 오류번호를 반환합니다.

 설명 : 현재의 시스템 날짜를 반환합니다.

 예제 : CVErr(1357) ☞ 사용자정의 오류 번호를 반환합니다.

 예제 : d=Date ☞ d에 현재 시스템 날짜를 반환합니다.

 ◈ 함수명 : DateAdd

 ◈ 함수명 : DateDiff

 형식 : DateAdd(interval, number, date)

 형식 : DateDiff(interval, date1, date2,[firstdayofweek,...])

 설명 : 특정 시간 간격을 포함한 Date값을 반환합니다.

 설명 : 지정된 두 날짜간의 시간 간격을 반환합니다.

 예제 : DateAdd("m", 1, "31-Jul-99") ☞ 99년 7월31에           1개월을 더한 99년 8월 31일 값을 반환합니다.

 예제 : dd=InputBox("Enter a date")
          cha=DateDiff("d", Now, dd)
          ☞ 입력한 날짜와 현재날짜와의 차이값을 반환합니다.

 ◈ 함수명 : DatePart

 ◈ 함수명 : DateSerial

 형식 : DatePart(interval, date[,firstdayofweek...)

 형식 : DateSerial(year, month, day)

 설명 : 관련 자료의 특정부분의 값을 반환합니다.

 설명 : 지정된 년, 월, 일의 값을 반환합니다.

 예제 : dd=InputBox("Enter a date")
          cha=DatePart("w", dd) ☞ 입력받은 날짜의 요일을
          반환합니다.

 예제 : mdate=DateSerial(1980, 5,10)
          ☞ mdate에 1980년 5월 10일의 날짜값을 반환합니다.

 ◈ 함수명 : DateValue

 ◈ 함수명 : Day

 형식 : DateValue(date)

 형식 : Day(date)

 설명 : 날짜값을 반환합니다.

 설명 : 해당월의 날짜를 의미하는 정수값을 반환합니다.

 예제 : DateValue("October 15, 1985)
         ☞ 영문표기법에 의한 날짜값을 반환합니다.

 예제 : mdate=#October 15, 1990#
          m=Day(mdate) ☞ m은 15를 받습니다.

 ◈ 함수명 : DDB

 ◈ 함수명 : Dir

 형식 : DDB(cost, salvage, life, period[,factor])

 형식 : Dir(pathname[,attributes])

 설명 : 특정기간동안 자산의 감가상각값을 반환합니다.

 설명 : 지정된 파일속성등이 일치하는 파일이름을 반환합니다

 예제 : period=((cost-salvage)*factor)/life
          ☞ DDB함수는 윗 공식을 사용하여 주어진 기간동안의           감가상각을 계산합니다.

 예제 : Dir(*.jpg) ☞ 해당 pathname과 일치하는 첫 번째 파일           이름을 반환합니다.

 ◈ 함수명 : DoEvents

 ◈ 함수명 : Environ

 형식 : DoEvents()

 형식 : Environ({envstring | number})

 설명 : 운영체제가 다른 이벤트를 처리할 수 있도록 실행을
          넘겨줍니다.

 설명 : 운영체제 환경변수와 관련된 문자를 반환합니다.

 예제 :  DoEvents() ☞ 파일검색처럼 시작한 후 사용자가 그            프로세스를 취소할 수 있도록 해주는 것과 같은
           간단한 작업에 아주 유용합니다.

 예제 : Environ(Ind) ☞ 환경변수를 읽어들입니다.

 ◈ 함수명 : EOF

 ◈ 함수명 : Error

 형식 : EOF(filenumber)

 형식 : Error(errornumber)

 설명 : Input용으로 열린 파일의 끝에 도달하면 Boolean
          값을 True값을 반환합니다.

 설명 : 주어진 오류번호에 해당하는 오류메세지를 반환합니다

 예제 : Do While Not EOF(1) ☞ 파일의 끝을 확인합니다.

 예제 : Error(1231) ☞ errornumber해당하는 오류메세지를
          반환합니다.

 ◈ 함수명 : Exp

 ◈ 함수명 : FileAttr

 형식 : Exp(number)

 형식 : FileAttr(filenumber, returntype)

 설명 : e(자연로그의 밑)의 거듭제곱수를 반환합니다.

 설명 : Open문으로 연 파일의 파일모드를 반환합니다.

 예제 : Exp(-1 * 1.3)/2 ☞ 쌍곡선 사인값을 반환합니다.

 예제 : FileAttr(FileNum, 1) ☞ Append 파일모드입니다.

 ◈ 함수명 : FileDateTime

 ◈ 함수명 : FileLen

 형식 : FileDateTime(pathname)

 형식 : FileLen(pathname)

 설명 : 파일이 생성되거나 마지막으로 수정된 날짜와 시간을
          반환합니다.

 설명 : 파일 길이를 바이트 수로 반환합니다.

 예제 : FileDateTime("TTFILE") ☞ TTFILE이 수정된 날짜와
          시간을 반환합니다.

 예제 : ms=FileLen("TTFILE") ☞ 파일길이를 반환합니다.

 ◈ 함수명 : Int, Fix

 ◈ 함수명 : Format

 형식 : Int(number), Fix(number)

 형식 : Format(expression, format...)

 설명 : 특정 숫자의 정수 부분을 전달된 형식으로 반환합니다

 설명 : 형식 식의 명령대로 구성된 문자를 반환합니다.

 예제 : Int(99.8) ☞ 99   Int(-99.2) ☞ -100
          Fix(99.8) ☞ 99   Fix(-99.2) ☞ -99 를 반환합니다.

 예제 : Format(53000,"##,###") ☞ 53,000
          Format(2, "0.00%") ☞ 200.00%을 반환합니다.

 ◈ 함수명 : FreeFile

 ◈ 함수명 : FV

 형식 : FreeFile(rangenumber)

 형식 : FV(rate, nper, pmt[,pv,type])

 설명 : Open문에 사용할 수 있는 다음 파일번호를 반환.

 설명 : 정기고정 지불액과 고정 이율을 기준으로 연금에
             대한 미래 가치를 반환합니다.

 예제 : FileNumbr=FreeFile ☞ 사용하지 않은 파일번호를
          가져와서 Open문에서 이용합니다.

 예제 : rate(일정기간당 이율), nper(연금의 총지불 기간수)
          pmt(각 기간에 지불할 금액, PV(장래의 지불액에 대
          한 현재의 값), Type(지불 만기일)

 ◈ 함수명 : GetAllSettings

 ◈ 함수명 : GetAttr

 형식 : GetAllsettings(appname, section)

 형식 : GetAttr(pathname)

 설명 : 윈도우 레지스트리의 응용 프로그램 항목에서 키 설정
          의 이름과 값들의 목록을 반환합니다.

 설명 : 파일, 디렉토리, 또는 폴더속성을 반환합니다.

 예제 : GetAllsettings(appname:="MyApp" , section :=
          "Startup") ☞ 윈도우 .INI파일의 항목을 만들기 위해
          설정된 내용을 표시합니다.

 예제 : r=GetAttr(Fname) And vbArchive ☞ 보관속성이 설정
          되어있다면 0이 아닌값이 되돌려 지고 설정되어 있지
          않으면 반환값은 0입니다.

 ◈ 함수명 : GetAutoServerSettings

 ◈ 함수명 : GetObject

 형식 : object.GetAutoServerSettings([progid,clsid])

 형식 : GetObject([pathname, class])

 설명 : ActiveX 구성요소의 등록상태에 대한 정보를 반환

 설명 : 파일에서 ActiveX개체에 대한 참조를 반환합니다.

 예제 : oRegClass.GetAutoServerSettings ("Hproj.HClass")            ☞ 명명된 원격 등록 개체 정보를 검색하여 반환

 예제 : GetObject("C:\Photo\Cat.psd) ☞ 해당 응용프로
          그램이 시작되고 지정된 파일의 개체가 활성화됩니다.

 ◈ 함수명 : GetSetting

 ◈ 함수명 : Hex

 형식 : GetSetting(appname, section, key[,default])

 형식 : Hex(number)

 설명 : 윈도우 레지스트리에서 키 설정값을 반환합니다.

 설명 : 숫자의 16진수값을 문자값으로 반환합니다.

 예제 : GetSetting(appname:="MyApp", section:="Startup",           key:="Left", defaulf:="25")  ☞ 레지스트리의 키 설정
          값을 반환합니다.

 예제 : mHex=Hex(7) ☞ 7를 반환합니다.
          mHex=Hex(10) ☞ A를 반환합니다.
          mHex=Hex(27) ☞ 1B를 반환합니다.

 ◈ 함수명 : Hour

 ◈ 함수명 : IIf

 형식 : Hour(time)

 형식 : IIf(expr, truepart, falsepart)

 설명 : 시간을 나타내는 0에서 23사이의 정수값을 반환합니다

 설명 : 식을 평가한 결과에 따라 값을 반환합니다.

 예제 : MTime=#3:20:45 PM#.
          MHour=Hour(MTime) ☞ 15값이 반환됩니다.

 예제 : IIf(su>200, dan*su*0.8, dan*su)
          ☞ 주어진 식을 평가하여 참, 거짓문장을 수행합니다.

 ◈ 함수명 : IMEStatus

 ◈ 함수명 : Input

 형식 : IMEStatus

 형식 : Input(number,[#]filenumber)

 설명 : IME모드를 나타내는 값을 반환합니다.

 설명 : Input 또는 Binary 모드로 연 파일로부터 문자가          들어있는 문자를 반환합니다.

 예제 : vbIMEModeNoControl ☞ 0(현재 상태 유지)
          vbIMEModeHangul ☞ 10(한글)

 예제 : Open "TFile" For Input As #1 ☞ 파일을 엽니다.
          MChar=Input(1,#1) ☞ 한 문자를 가져옵니다.

 ◈ 함수명 : InputBox

 ◈ 함수명 : InStr

 형식 : InputBox(prompt[,title,default,xpos, ypos,helpfile])

 형식 : InStr([,start,]string1,string2[,compare])

 설명 : 대화 상자안의 프롬프트를 보여주며, 사용자가 입력을
         하면 입력된 내용을 포함하는 문자열을 반환합니다.

 설명 : 한 문자열안에 특정 문자열이 처음으로 발생한 위치를
          수치값으로 반환합니다.

 예제 : InputBox(msg,"입력연습", "없음")
          ☞ 메시지와 Input박스의 제목과 기본값을 설정합니다.

 예제 : InStr(3,"honggildong","d",1)
          ☞ 3 위치에서 비교시작하여 d가 발견된 8을 반환

 ◈ 함수명 : IPmt

 ◈ 함수명 : IRR

 형식 : IPmt(rate, per, nper, pv[, fv[,type]])

 형식 : IRR(values()[,guess])

 설명 : 정기고정 지불액과 고정이율을 기준으로 일정기간동안
          연금의 이자 지불액을 반환합니다.

 설명 : 일정기간의 자금흐름(지불액과 수령액)에 대한 내부
          수익률을 반환합니다.

 예제 : rate(일정기간 당 이율), per,nper(연금의 총 지불 기간
          수), pv(장래의 지불액이나 수령액에 대한 현재의 값)
          fv(마지막으로 지불한 후에 원하는 장래의 값이나 자금
          잔액), type(지불 만기일)

 예제 : values()(자금 흐름값을 지정하는 Double유형의 배열
          guess(추정치를 지정하는 Variant는 IRR로 얻을 수 있
          습니다. 생략하면 guess는 0.1(10%)이 됩니다.

 ◈ 함수명 : IsArray

 ◈ 함수명 : IsDate

 형식 : IsArray(varname)

 형식 : IsDate(expression)

 설명 : 변수가 배열인지 나타내는 Boolean값을 반환합니다.

 설명 : 식을 날짜로 변환할 수 있는지를 Boolean값으로 반환

 예제 : Dim k(2,3)
          if IsArray(k) ☞ True값을 반환합니다.

 예제 : MDate="#2/18/78#"
          if IsDate(MDate) ☞ True값을 반환합니다.

 ◈ 함수명 : IsEmpty

 ◈ 함수명 : IsError

 형식 : IsEmpty(expression)

 형식 : IsError(expression)

 설명 : 변수가 초기화 되었는지를 Boolean값으로 반환합니다

 설명 : 식이 오류 값인지를 나타내는 Boolean값을 반환

 예  제 : Dim Mchk
            if IsEmpty(Mchk) ☞ True값을 반환합니다.

 예제 : if IsError(Rel)☞ Rel이 오류면 True값을 반환합니다.

 ◈ 함수명 : IsMissing

 ◈ 함수명 : IsNull

 형식 : IsMissing(argname)

 형식 : IsNull(expression)

 설명 : 선택적인 Variant인수가 프로시저에 전달되었는지
          나타내는 Boolean값을 반환합니다.

 설명 : 식이 Null값인지를 Boolean값으로 반환합니다.

 예제 : Function ReT(Optional A)
          If IsMissing(A) ☞ 인수값이 있으면 참값을 반환합니다

 예제 : Myvar=Null
          if IsNull(MyVar) ☞ True값을 반환합니다.

 ◈ 함수명 : IsNumeric

 ◈ 함수명 : IsObject

 형식 : IsNumeric(expression)

 형식 : IsObject(idenfifier)

 설명 : 식을 수로 평가할 수 있는지를 Boolean값으로 반환

 설명 : 식별자가 개체변수인지를 Boolean값으로 반환합니다.

 예제 : su=30
          if IsNumeric(su) ☞ True값을 반환합니다.

 예제 : Dim Mobj As Object
          Set Yobj=Mobj ☞ 개체참조를 지정합니다.
          if IsObject(Yobj) ☞ Treu를 반환합니다.

 ◈ 함수명 : LBound

 ◈ 함수명 : LCase

 형식 : LBound(arrayname[, dimension])

 형식 : LCase(string)

 설명 : 지정된 배열 차원에 사용할 수 있는 가장 작은 첨자를
          포함하는 Long형 값을 반환합니다.

 설명 : 소문자로 변환된 문자값을 반환합니다.

 예제 : Dim Marray(1 To 10, 10 To 20) ☞ 배열변수 선언
          L=LBound(Marray,1) ☞ 1을 반환합니다.

 예제 : k="SEOUL"
          m=LCase(k) ☞ "seoul"를 반환합니다.

 ◈ 함수명 : Left

 ◈ 함수명 : Len

 형식 : Left(string, length)

 형식 : Len(string | varname

 설명 : 문자열의 좌즉에서부터 지정된 수만큼 문자를 반환

 설명 : 문자열의 갯수를 수치로 반환합니다.

 예제 : s="hello chulsu"
          m=Left(s, 3) ☞ "hel"을 반환합니다.

 예제 : Len("chanbin") ☞ 7을 반환합니다.

 ◈ 함수명 : LoadPicture

 ◈ 함수명 : Loc

 형식 : LoadPicture(stringexpression)

 형식 : Loc(filenumber)

 설명 : 폼의 PictureBox컨트롤, Image컨트롤에 그림을 호출

 설명 : 열려있는 파일에서 현재의 R/W위치를 반환합니다.

 예제 : Picture1.Picture=LoadPicture("chan.jpg")
         ☞ 픽쳐박스에 그림을 불러옵니다.

 예제 : MyLocation=Loc(1) ☞ 파일안의 현재위치를 반환

 ◈ 함수명 : LOF

 ◈ 함수명 : Log

 형식 : LOF(filenumber)

 형식 : Log(number)

 설명 : Open문으로 연 파일의 크기를 반환합니다.

 설명 : 특정한 수의 자연로그값을 계산합니다.

 예제 : Flen=LOF91) ☞ 파일의 길이를 구합니다.

 예제 : Log(x) ☞ x값에 대한 자연로그값을 구합니다.

 ◈ 함수명 : LTrim, RTrim, Trim

 ◈ 함수명 : Mid

 형식 : LTrim(string), RTrim(string), Trim(string)

 형식 : Mid(string, start[,length])

 설명 : 지정된 문자열의 좌측, 우측, 양쪽에 공백이 없는 문자
          열을 반환합니다.

 설명 : 한 문자열에서 시작위치에서 지정한 수 만큼이 문자들
          을 반환합니다.

 예제 : k=" seoul "
          m=LTrim(k) ☞ "seoul "을 반환합니다.

 예제 : k="hello chanbin"
          m=Mid(k,7,4) ☞ "chan"을 반환합니다.

 ◈ 함수명 : Minute

 ◈ 함수명 : MIRR

 형식 : Minute(time)

 형식 : MIRR(values(), finance_rate, reinvest_rate)

 설명 : 분을 나타내는 0에서 59사이의 정수값을 반환합니다.

 설명 : 일정기간의 자금흐름에 대한 수정된 내부이익을 지정
          하는 값을 반환합니다.

 예제 : MyTime=#5:38:23# ☞ 시간을 지정합니다.
          m=Minute(MyTime) ☞ 38을 반환합니다.

 예제 : values()(자금흐름값을 지정), finance_rate(재정처리
         비용으로 지불할 이율을 지정), reinvest_rate(자금 재
         투자로 인한 수익에서 받을 이율을 지정)

 ◈ 함수명 : Month

 ◈ 함수명 : MsgBox

 형식 : Month(date)

 형식 : MsgBox(prompt[,buttons, title, helpfile, context])

 설명 : 월을 나타내는 1에서 12사이의 정수값을 반환합니다.

 설명 : 대화 상자안에 메시지를 보여줍니다.

 예제 : Mydate=#October 15, 1990# ☞ 날짜를 지정합니다.
          m=Month(Mydate) ☞ 10을 반환합니다.

 예제 : MsgBox "안녕하세요" ☞ 해당메세지를 보여줍니다.

 ◈ 함수명 : Now

 ◈ 함수명 : NPer

 형식 : Now

 형식 : NPer(rate, pmt, pb[,fv, type])

 설명 : 사용자 컴퓨터 시스템 날짜와 시간을 반환합니다.

 설명 : 정기고정 지불액과 고정이율을 기준으로 연금의 기간
          수를 반환합니다.

 예제 : Td=Now ☞ 현재 날짜와 시간을 반환합니다.

 예제 : rate(일정기간 이율을 지정), pmt(각 기간에 지불할
          지불액), pv(장래의 지불액), fv(마지막으로 지불한후
          에 원하는 장래의 값), type(지불만기일)

 ◈ 함수명 : NPV

 ◈ 함수명 : Oct

 형식 : NPV(rate, values())

 형식 : Oct(number)

 설명 : 정기적인 자금 흐름과 할인율을 기준으로 현재의 순
          투자 가치를 반환합니다.

 설명 : 숫자의 8진수값을 문자로 반환합니다.

 예제 : rate(전 기간에 걸친 할인율을 지정), values()(자금 흐
          름값을 지정)

 예제 : m=Oct(5) ☞ 5를 반환합니다.
          d=Oct(9) ☞ 11을 반환합니다.

 ◈ 함수명 : Partition

 ◈ 함수명 : Pmt

 형식 : Partition(number, start, stop, interval)

 형식 : Pmt(rate, nper, pv[,fv, type])

 설명 : 계산된 범위내이 어느곳에서 숫자가 발생했는지를
          알려주는 문자열을 반환합니다.

 설명 : 정기고정 지불액과 고정이율을 기준으로 연금에 대한
          지불액을 반환합니다.

 예제 : 주어진 범위안에서 주문량을 구하기 위해 많은 사용

 예제 : rate(일정기간 당 이율을 지정), nper(연금의 총 지불
          기간수을 지정), pv((장래의 지불액), fv(마지막으로 지
          불한 후에 원하는 장래의 값), type(지불 만기일)

 ◈ 함수명 : PPmt

 ◈ 함수명 : PV

 형식 : PPmt(rate, per, nper, pv[,fv, type])

 형식 : PV(rate, nper, pmt[,fv, type])

 설명 : 정기고정 지불액과 고정이율을 기준으로 일정기간동안
          연금의 원금 지불액을 반환합니다.

 설명 : 장래의 지불할 정기고정 지불액과 고정 이율을 기준으
          로 연금의 현재 가치를 반환합니다.

 예제 : rate(일정기간 당 이율을 지정), Nper(연금의 총지불
         기간수),pmt(각 기간에 지불할 지불액), fv(마지막으로
         지불한 후에 원하는 장래의 값),type(지불만기일)

 예제 : rate(일정기간 당 이율을 지정), nper(연금의 총 지불
          기간수를 지정), pmt(각 기간에 지불할 지불액), fv(마
          지막으로 지불할 후에 원하는 장래의 값), type(지불
          만기일)

 ◈ 함수명 : QBColor

 ◈ 함수명 : Rate

 형식 : QBColor(color)

 형식 : Rate(nper, pmt, pv, fv[, type, guess])

 설명 : 지정된 색 번호에 대응하는 칼라를 나타냅니다.

 설명 : 연금에 대한 일정기간 당 이율을 반환합니다.

 예제 : QBColor(0) ☞ 검정색을 반환합니다. 1(파랑), 2(초록)
          3(청록), 4(빨강), 5(진홍), 6(노랑), 7(흰색), 8(회색),
          9(연파랑), 10(연초록), 11(연청록), 12(연빨강),
          13(연진홍), 14(연노랑), 15(옅은 흰색)  

 예제 : nper(연금의 총지불 기간수를 지정), pmt(각 기간에
          지불할 지불액을 지정), pv(장래의 지불액이나 수령액
          에 대한 현재의 값을 지정), fv(마지막으로 지불한 후에
          원하는 장래의 값), type(지불만기일), guess(추정치를
          지정하는 Variant는 Rate로 얻음)

 ◈ 함수명 : RGB

 ◈ 함수명 : Right

 형식 : RGB(red, green, blue)

 형식 : Right(string, length)

 설명 : RGB색값을 Long형식의 정수로 반환합니다.

 설명 : 문자열의 우측에서 지정한 수만큼의 문자열을 반환

 예제 : RGB(255, 0, 0) ☞ 빨강색을 반환합니다.
          RGB(0, 0 ,255)) ☞파랑색을 반환합니다.

 예제 : k="hello chanbin"
          m=Right(k, 3) ☞ "bin"을 반환합니다.

 ◈ 함수명 : Rnd

 ◈ 함수명 : Second

 형식 : Rnd(number)

 형식 : Second(time)

 설명 : 난수를 반환합니다.(0에서 1사이의 수치)

 설명 : 초를 나타내는 0에서 59사이의 수를 반환합니다.

 예제 : m=int((Rnd*6))+1 ☞ 1에서 6사이의 난수를 발생합니다

 예제 : MyTime=#2:40:55 PM# ☞ 시간을 지정합니다.
          s=Second(MyTime) ☞ 55를 반환합니다.

 ◈ 함수명 : Seek

 ◈ 함수명 : Sgn

 형식 : Seek(filenumber)

 형식 : Sgn(number)

 설명 : Open문으로 열린 파일안의 R/W의 위치를 반환합니다

 설명 : 특정 숫자의 부호를 수치로 반환합니다.

 예제 : Mc=Input(1, #1) ☞ 데이터의 문자를 읽어드립니다.
          Debug.Print Seek(1) ☞ 디버그창의 바이트 위치를
          출력합니다.

 예제 : m=Sgn(50) ☞ 양수이면 1을 0이면 0을 음수이면 -1을
          반환합니다. 따라서 여기서는 1을 반환합니다.

 ◈ 함수명 : Shell

 ◈ 함수명 : Sin

 형식 : Shell(pathname[, windowstyle])

 형식 : Sin(number)

 설명 : 사용자에 의해 지정된 응용프로그램을 실행합니다.

 설명 : 각도의 사인값을 반환합니다.

 예제 : k=Shell("C:\windows\calc.exe", 1)
         ☞ 계산기를 실행합니다.

 예제 : Sin(30*pi/180) ☞ 사인 30도값을 구합니다.

 ◈ 함수명 : SLN

 ◈ 함수명 : Space

 형식 : SLN(cost, salvage, life)

 형식 : Space(number)

 설명 : 단일 기간 동안의 정액법을 지정하는 값을 반환합니다.

 설명 : 지정된 수의 공백을 반환합니다.

 예제 : cost(초기자산 비용을 지정), Salvage(유용기간이 끝
          나는 시점의 자산액수를 지정), Life(자산의 유용기간
          길이를 지정)

 예제 : m="hello" & Space(10) & "chanbin"
          ☞ 두 문자열 사이에 10 공백을 삽입합니다.

 ◈ 함수명 : Spc

 ◈ 함수명 : Str

 형식 : Spc(n)

 형식 : Str(number)

 설명 : Print메서드에서 출력위치를 지정합니다.

 설명 : 숫자형식의 데이터를 문자열 데이터로 변환합니다.

 예제 : Print spc(5) "chanbin" ☞ 5칸을 띤 후에 출력합니다.

 예제 : Str(390) ☞ "390"를 반환합니다.

 ◈ 함수명 : StrComp

 ◈ 함수명 : StrConv

 형식 : StrComp(string1.string2[, compare])

 형식 : StrConv(string, conversion)

 설명 : 문자열 비교의 결과값을 수치로 반환합니다.

 설명 : 지정된 대로 변환된 문자열을 반환합니다.

 예제 : a="chanbin" b="chanbin"
          StrComp(a, b, 1) ☞ 0을 반환합니다.

 예제 : vbUpperCase(문자열을 대문자로), vbLowerCase(문
          열을 소문자로), vbWide(1바이트문자를 2바이트로)

 ◈ 함수명 : String

 ◈ 함수명 : Switch

 형식 : String(number, character)

 형식 : Switch(expr-1, value-1[,expr-2, value-2....])

 설명 : 지정된 길이의 반복되는 문자열을 반환합니다.

 설명 : 식의 목록식을 평가한 후 목록에서 True값을 갖는 최
          최의 식과 관련된 값이나 식을 반환합니다.

 예제 : String(7, "*") ☞ "*******"을 반환합니다.
          String(10, 65) ☞ "AAAAAAAAAA"을 반환합니다.

 예제 : Switch(CityName="London", "Englich", CityName=
          "Roma", "Italian") ☞ 도시의 이름과 일치하는 언어이
           름을 반환합니다.

 ◈ 함수명 : SYD

 ◈ 함수명 : Tab

 형식 : SYD(cost, salvage, life, period)

 형식 : Tab(n)

 설명 : 지정된 기간동안 자산의 감가상각값을 반환합니다.

 설명 : Print메서드에서 출력위치를 정합니다.

 예제 : cost(초기 자산비용을 지정), salvage(유용기간이 끝
          나는 시점의 자산액수를 지정), life(자산의 유용기간
          길이), period(자산의 감가상각을 계산하는 기간지정)

 예제 : Print Tab(10) "chanbin"
          ☞ 10번째 칸에서부터 "chanbin"을 출력

 ◈ 함수명 : Tan

 ◈ 함수명 : Time

 형식 : Tan(number)

 형식 : Time

 설명 : 각도의 탄젠트값을 반환합니다.

 설명 : 현재의 시스템 시간을 반환합니다.

 예제 : Tan(30*pi/180) ☞ 탄젠트 30값을 구합니다.

 예제 : MyTime=Time ☞ 현재 시스템 시간을 반환합니다.

 ◈ 함수명 : Timer

 ◈ 함수명 : TimeSerial

 형식 : Timer

 형식 : TimeSerial(hour, minute, second)

 설명 : 자정 이후 경과한 초 수를 반환합니다.

 설명 : 특정 시, 분, 초에 대한 시간을 반환합니다.

 예제 : Finish=Timer ☞ 종료시간을 지정합니다.

 예제 : TimeSerial(15, 30,27) ☞ 오후 3시 30분 27을 표현

 ◈ 함수명 : TimeValue

 ◈ 함수명 : TypeName

 형식 : TimeValue(time)

 형식 : TypeName(varname)

 설명 : 시간 값을 포함한 Date값을 반환합니다.

 설명 : 변수에 대한 정보를 제공하는 문자형값을 반환합니다.

 예제 : TimeValue("3:20:32 PM") ☞ 시간을 반환합니다.

 예제 : TypeName(IntVar) ☞ "integer"를 반환합니다.

 ◈ 함수명 : Ubound

 ◈ 함수명 : UCase

 형식 : Ubound(arrayname[, dimension])

 형식 : UCase

 설명 : 배열차원을 나타내는 첨자를 반환합니다

 설명 : 지정한 문자열을 대문자로 변환합니다.

 예제 : Dim Myarray(1 To 10)
          Ubound(Myarray) ☞ 10을 반환합니다.

 예제 : k="chanbin"
          UCase(k) ☞ "CHANBIN"을 반환합니다.

 ◈ 함수명 : Val

 ◈ 함수명 : VarType

 형식 : Val(string)

 형식 : VarType(varname)

 설명 : 문자열내에 포함된 수치를 숫자값으로 변환합니다.

 설명 : 변수의 하위 형식을 나타내는 값을 수치로 반환합니다.

 예제 : Val("3500") ☞ 3500을 반환합니다.

 예제 : IntVar=235
          VarType(IntVar) ☞ 정수를 나타내는 2를 반환합니다.

 ◈ 함수명 : Weekday

 ◈ 함수명 : Year

 형식 : Weekday(date, [firstdayofweek])

 형식 : Year(date)

 설명 : 평일을 나타내는 정수값을 반환합니다.

 설명 : 연도를 나타내는 정수값을 반환합니다.

 예제 : MyDate=#October 26, 2000#
          k=Weekday(Mydate) ☞ Mydate가 목요일을 나타내기
          때문에 5가 k에 반환됩니다.

 예제 : Mydate=#October 26, 2000# ☞ 날짜를 지정합니다.
          k=Year(Mydate) ☞ 2000을 나타냅니다.


Posted by 나비:D
:

vb :: 코드모듈

사용자 삽입 이미지

텍스트박스안에 입력된 문구를 거꾸로 출력한다.
개체변수를 사용하는 것은 다른 변수를 사용하는 것과 비슷하지만 변수를 지정할 때는 다음과 같은 단계를 따른다.
먼저 Dim [변수] As [클래스이름] 구문을 사용해 변수를 선언하고, Set [변수] = New [개체]문을 사용해 개체를 변수에 지정한다.

#코드모듈
Visual Basic의 코드는 모둘이라는 곳에 저장된다. 이러한 코드모듈에는 폼, 표준, 클래스의 3가지 종류가 있다. 간단한 응용프로그램이라면 하나의 폼으로도 구성이 가능하며 모든 코드도 폼 모듈내에 작성할 수 있지만 응용프로그램이 커지고 복잡해짐에 따라 많은 폼을 추가하게 된다. 여러 폼에서 실행되는 코드가 공통적으로 사용된다면 공통적인 코드는 각 폼에 중복시키지 않고 독립된 모듈내에 만드는 게 좋다. 이 독립된 모듈이 표준 모듈이 된다. 시간이 지나면 공유프로시저를 가지는 모듈의 라이브러리를 만들 수 있다. 이러한 코드모듈(폼, 표준, 클래스모튤)에는 다음과 같은 구조로 형성되어 있다.
 - 선언부분
폼, 클래스, 표준모듈의 모듈수준에 상수, 형식, 변수, 동적연결 라이브러리(DLL)프로시저를 선언하는 곳이다.
 - 프로시저 부분
Sub, Function, Property 프로시저와 같은 하나의 단위로 실행될 수 있는 간단한 코드들이 존재한다.

#폼모듈
프로젝트 탐색기 창에 폼이라는 폴더에는 일반 폼과 추가될 수 있는 MDI폼이 있음을 볼 수 있다. 여기에 작성될 폼 모듈에는 폼과 컨트롤에 대한 설명, 컨트롤 속성에 대한 설명을 포함하며, 상수, 변수, 외부 프로시저, 이벤트 프로시저, 일반 프로시저에 대한 폼 수준 선언도 포함될 수 있다.
이 폼모듈에는 Form_Load()이벤트프로시저라는 코드구역이 있으며 이 곳에 특정이벤트에 응답하여 실행되는 명령을 놓아두면 된다. 폼은 컨트롤을 가지며 폼 모듈에는 폼의 각 컨트롤에 대응하는 일련의 이벤트 프로시저가 있다. 이벤트 프로시저 외에도 폼 모듈은 다른 이벤트 프로시저의 호출에 응답하여 실행하는 VaildateTime()과 같은 일반 프로시저도 가질 수 있다.

#표준모듈
표준모듈(.bas)은 폼 모듈과 달리 프로시저, 형식, 데이터선언과 정의만 포함하는 모듈을 의미한다. 즉, 특정폼이나 컨트롤과 관련되지 않은 코드가 들어있다. 표준모듈에서 모듈수준선언과 정의는 기본값이 Public이다. 이러한 표준모듈은 응용프로그램 내에서 다른 모듈들이 공통으로 액세스할 수 있는 프로시저와 선언영역에 대한 컨테이너가 된다.
표준모듈에 작성하는 코드가 반드시 특정프로그램에 묶여있을 필요는 없다. 즉, 이름으로 특정폼이나 컨트롤을 참조하지 않는 것만 주의한다면 표준모듈은 서로 다른 많은 응용프로그램에서 다시 사용할 수 있음을 명심하기 바란다.

#클래스모듈
클래스모듈(.cls)은 화면에 보이는 사용자 인터페이스가 없다는 점만 제외하고는 폼 모듈과 비슷하다. 이러한 클래스모듈은 VisualBasic에서 개체지향 프로그래밍의 기초가 된다. 또한 클래스모듈에 코드를 작성한여 새로운 개체를 작성할 수 있다. 이렇게 만들어진 새로운 개체에 사용자 정의한 속성과 메서드를 넣을 수 있다. 실제로 폼 역시 폼 창을 화면에 나타내고 그 위에 컨트롤을 놓을 수 있는 클래스모듈의 일부분임을 알아야 한다.

인터페이스클래스모듈 추가
textbox : 1
commandbutton : 1
labelbox : 1
속성클래스모듈.name : Thing
text1.text : 입력하세요
command1.caption : 거꾸로
label1.caption : 거꾸로 출력합니다.
Posted by 나비:D
:

출처 : http://yatoyato.tistory.com/

vb :: 간단한 응용프로그램작성

사용자 삽입 이미지

이번 장은 버튼을 누르면 아이콘을 출력하는 간단한 프로그램을 작성한다.
form의 Load이벤트에 코드를 작성한다.
소스코드Private Sub Form_Load()    '폼을 메모리에 불러올 때 발생하는 이벤트
 picIcon.Visible = false    'picture박스의 그림이 보이지 않게한다.
End Sub    '이벤트종료

Load이벤트란 폼을 컴퓨터메모리에서 불러올 때 발생하게 된다. Load이벤트가 발생되면, Load이벤트 내의 코드를 실행하게 된다. 즉, 현재 PictureBox를 보이지않게 하라는 의미인 picIcon.Visible=false를 실행하게 된다. 그리고 End Sub를 만나 프로시저를 종료한다.

 작은 따옴표(')로 시작된 문장은 주석문이다. 주석문은 컴파일시 실행되지 않으며, 그 코드에 대한 부연설명을 하기 위한 것이다. 좋은 프로그램은 얼마만큼 주석문을 잘 표시해 놓느냐에 따라 달려있다. 팀 단위로 어플리케이션이 공동개발될 경우 팀원간에 코드를 공유할 필요가 있게 되는데. 이때 다른 팀원이 이해하기 쉽도록 주석문을 달아 놓는다.
주석문과 마찬가지로 들여쓰기를 잘 해놓으면 나중에 자신뿐만 아니라 타인이 보더라도 잘 이해할 수 있다.

코드창의 개체상자 리스트박스에서 cmdIcon을 선택하면, Click이벤트프로시저가 자동적으로 나올 것이다. 이 이벤트프로시저는 기본적으로 CommandButton을 선택했을 때 기본적으로 나오는 이벤트이다. 이처럼 각 개체마다 기본적으로 갖는 이벤트는 다르다. 예를 들어, 폼을 선택했을 때 기본적으로 나타나는 이벤트 프로시저는 Load이벤트이다.

비주얼베이직은 어떤 이벤트에 의해 실행되지 때문에, 이벤트 중심 프로그램이라 불린다. 모든 윈도우용 어플리케이션은 이벤트단위로 코드가 이루어져 있기 때문에 특정사건을 유발시켜야 그 사건에 해당하는 이벤트를 실행하게 된다. 우리가 작성한 어플리케이션도 마찬가지이다. 실행시 초기화면에는 아무 그림도 나타나지 않는다. 그대로 방치하면 어떠한 변화도 폼에는 일어나지 않는다. 그러나 [실망이야]버튼을 클릭했을 때 해당이벤트, cmdIcon_Click이벤트를 만나 그 안에 있는 코드를 실행시켰다는 것을 알기 바란다.

#구성요소를 저장시
- 폼 파일 (.frm) : 모든 폼과 MDI폼을 저장한다.
- 클래스 파일 (.cls) : 모든 클래스모듈을 저장한다.
- 모듈 파일 (.bas) : 모든 표준 모듈을 저정한다.
- 속성 페이지 파일 (.pag) : 모든 속성페이지를 저장한다.
- 사용자 정의 컨트롤파일 (.ctl) : 모든 사용자컨트롤을 저장한다.
- 문서개체파일 (.dob) : 모든 문서개체를 저장한다.
이러한 구성요소는 하나의 개체로 작용되기 때문에 독립되어 저장된다. 이처럼 비주얼베이직 파일은 독립개체로 저장되기 때문에 나중에 필요한 구성요소를 찾아 다른 프로젝트에서도 재사용할 수 있다.

인터페이스picturebox : 1
commandbutton : 1
속성picturebox1
- name : picIcon
- autosize : true
- picture : 이미지지정

commandButton1
- name : cmdIcon
- caption : 실망이야

form1
- name : frmIcon
- caption : 실망

소스코드Option Explicit

Private Sub cmdIcon_Click()
    picIcon.Visible = True
End Sub

Private Sub Form_Load()
    picIcon.Visible = False
End Sub

Posted by 나비:D
:

출처 : http://yatoyato.tistory.com

vb :: 비주얼베이직이란?

 Visual Basic의 "Visual"이란 사용자로 하여금 Windows프로그램을 쉽게 이해하고, 쉽게 사용할 수 있도록 그래픽 인터페이스(GUI)사용하는 방법을 말한다. 인터페이스란 사용자가 시스템을 원활히 사용할 수 있도록 시스템과 사용자간에 제공되는 환경을 말하며, 사용자 인터페이스는 주로 입출력 장치와 대화형 언어체계를 포함한다. 즉, 인터페이스의 모양과 위치를 작성하는 데 있어 수많은 코드를 작성하는 것보다, 간단하게 미리 만들어져 있는 개체를 마우스의 드래그(drag)와 드롭(drop)기능을 사용하여 스크린위에 배치시키면 된다.
 "Basic"이란 전산의 역사상 프로그래머들에 의해 다른 언어보다 더 많이 사용된 BASIC(Beginners All-Purpose Symbolic Instruction Code)언어를 말한다. Visual Basic은 원래의 BASIC언어에서 발전하여 지금은 수백개의 문, 함수, 키워드를 가지고 있고, 그 중 많은 부분이 Windows GUI와 직접 관련되어 있다. 초보자들은 키워드 몇 개만 배우면 유용한 응용프로그램을 만들 수 있으며, 프로그래머들은 다른 Windows프로그래밍언어를 사용하여 이룰 수 있는 모든 것을 할 수 있다.

#VB응용프로그램 개발 단계
Visual Basic에서 응용프로그램을 작성하기위해 다음의 세가지 주요단계가 필요하다.

- 1단계 인터페이스 만들기
사용자와 컴퓨터간에 상호정보를 주고받기위한 기초작업을 하는 단계이다.
인터페이스는 응용프로그램 개발의 첫 단계로, 폼은 인터페이스의 기초가 된다. 집짓는 것에 비유하자면 폼은 집터가 될 것이고, 도구상자에 있는 컨트롤들은 각종 건축자재에 해당할 것이다. 컨트롤을 폼에 추가시키는 것은 프래임같은 개체를 컨테이너안에 그룹화시킬 필요가 있을 때 사용한다.

- 2단계 속성설정
각 개체에 대해 이름을 지정해 주거나 색깔, 모양, 개체위치, 개체크기등의 속성을 설정해주는 단계이다.
두번째 단계로 개체에 속성을 부여한다. 이것도 인간이 집을 만들때, 용도에 맞게 방의 크기도 정하고, 또한 방의 위치도 생각할 것이다.
그리고 난 다음 집을 짓고, 명패를 달고, 색깔도 칠하는 등 여러가지 부속작업을 하는 것에 비유할 수 있다.  이러한 속성을 설정하기 위해 비주얼베이직은 속성창이라는 것을 제공하고 있다. 속성창은 폼뿐만 아니라 폼 내에 있는 모든 컨트롤의 속성을 설정할 수 있도록 속성목록을 제공하고 있다.
폼뿐만 아니라 모든 컨트롤에 이름을 굳이 다시 부여하지 않아도 되지만, 이렇게하면 혼동되기 쉽다. 예를 들어, 하나의 프로젝트에 10개의 폼이 존재한다고 가정하자. 비주얼베이직은 폼 추가 순서대로 폼의 이름을 form1, form2, form3 ... 이런 식으로 부여하게 된다. 이 중 form3가 하는 일이 네트워크의 로그인 폼이라고 하자. 비주얼베이직의 특징중의 하나가 개체의 재활용이다. 즉 기존에 있던 프로젝트뿐만 아니라 폼, 모둘 등은 언제든지 필요하다면 다시 불러 쓸 수 있다는 것이다. 이러한 특징을 이용해 다른 프로젝트에서 네트워크 로그인 역할을 하는 기존의 폼을 쓰기 위해 하드디스크에서 찾을 것이다. 그러한 폼의 이름이 form1.frm, form2.frm ... 식으로 되어있다면 찾기 힘들 것이다.
그러나, 만약 form3대신 frmLogin이라고 이름을 부여했다면, 앞의 접두어 frm때문에 다른 개체와 확연히 구분될 뿐만 아니라 이름에 의미가 있기때문에 쉽게 찾아 사용할 수 있다. 이러한 이유때문에 개체종류를 나타내는 접두어를 의미있는 이름과 사용하는 것이 나중에 좋다.

- 3단계 코드쓰기
개체에 이벤트가 발생하면 수행해야 할 일을 적어두는 단계이다.
속성설정만으로 완전히 어플리케이션이 될 수는 없다. 모든 어플리케이션의 생명은 바로 코드작성에 있다. [코드창]은 비주얼베이직 코드를 작성할 수 있는 곳으로 코드는 언어문장, 상수, 선언문으로 구성되어 있다.
비주얼베이직에 있는 모든 코드는 프로시저(Procedure)라고하는 작은 단위로 이루어진다. 하나의 이벤트 프로시저(Event Procedure)에는 어떤 사건 발생시 수행하는 코드를 포함하게 된다.

Posted by 나비:D
:

How can return XML from a stored procedure using VB? (10762 Requests)

I've gotten quite a few requested for an example using a stored procedure instead of a template. So this example uses a regular stored procedure.

  1. Create a new EXE project in VB.
  2. Add references to MSXML 4.0 and ADO 2.6
  3. Create the stored procedure listed below.
  4. Copy the code below into your form's code. Be sure to change the connection string.

Stored Procedure

create proc employee_get
(
	@id int
)
as

	select 	FirstName, 
		LastName, 
		Title,
		Region
	from 	employees
	where	employeeid = @id
	for xml auto

go

VB Code

Dim oCmd As Command
Dim oPrm As Parameter
Dim oDom As IXMLDOMDocument2
   
Set oDom = New DOMDocument40
   
Set oCmd = New Command
oCmd.ActiveConnection = "Provider=SQLOLEDB; Data Source=; " & _
    "User ID=; Password=; Database=Northwind"
       
oCmd.CommandText = "employee_get"
oCmd.CommandType = adCmdStoredProc
    
Set oPrm = New Parameter
oPrm.Name = "@id"
oPrm.Value = "1"
oPrm.Type = adInteger
oPrm.Size = 4
oCmd.Parameters.Append oPrm
        
oCmd.Properties("Output Stream") = oDom
oCmd.Execute , , 1024

oDom.Save "c:\temp\results.xml"
    
Unload Me

Other Resources:
Returning XML in VB with a template

HOWTO: Retrieve XML Data by Using a SQL XML Query in a Visual Basic Client

HOWTO: Retrieve XML Data with a Template File from a Visual Basic Client

Posted by 나비:D
:

출처 : http://www.topxml.com/sql/articles/adoforxml/
Using VB and ADO to return and update Record Set based XML

by: Sean Grimaldi, Serious Consulting LLC.

This article is about making the most of ADO and XML until the complete Visual Basic.net, including ADO.net, becomes available.  This article is focused on how you, as a developer, can use ADO and XML today; and get valuable skills that apply to Visual Basic.net.  I also want to show how you can use ADO, XML, and XSL today, to improve the quality of your development.

 I am taken aback almost daily, at the slow adoption many standards-based technologies face.  XSLT is a fine example.  XSLT reached candidate recommendation, meaning the w3c considered it stable and encouraged implementation, in November 2000.   I am writing this article six months later, in a room packed with developers working for a worldwide software company.  Not one of these developers, that I am aware of, has ever used XSLT in a production environment.

 Part of the blame must go to how Microsoft spoiled us with Visual Basic.  As a development tool, it is unparalleled.  Think how simple it is to get an ADO Recordset; Visual Basic will even assist you in debugging the SQL query.

Unfortunately, at this time the situation is not at all the same with XSLT.  Microsoft does not currently make a powerful IDE that includes a powerful XML editor.  Visual Interdev, for example, mangles XSL. The best XML IDE available from Microsoft is XML Notepad (http://msdn.microsoft.com/xml/NOTEPAD/download.asp). As Visual Basic developers expecting features like statement completion, this is a tremendous loss.

We all suspect Visual Basic.net will provide us with the tools to make the use of these technologies simple, but until then, I would like to offer a few pointers to flatten the learning curve.

As an example of coming XML tools, Microsoft includes a XML Designer with color codes and statement and tag completion in Visual Studio.net.

Figure 1. Color-Coded XML Designer with Statement and Tag Completion

Since most developers prefer code samples to help illustrate technologies with which they are unfamiliar, this article loosely follows a sample. The sample scenario is simple and something you will likely run into frequently.  I am interested in improvements you may make or ways in which you extend it to be more useful.  Please email me your comments at my website, http://www.SeriousConsulting.com.

ADO

Every Visual Basic developer sooner or later becomes quite strong with ADO, because it is comparatively simple and allows access to every data source the developer is likely to encounter.

The disconnected Recordset is the staple of Microsoft web development.  It is most likely the single programming practice that can increase the scalability of a Visual Basic and/or ASP driven web site more than any other.  ADO makes it almost effortless.  A disconnected Recordset is simply a Recordset that no longer has a live connection to the server.  To disconnect a recordset, set it's ActiveConnection property equal to nothing. At this point it is safe to close the ADO connection object as well.  In ADO.net by default the data set is disconnected.

'declare variables

Dim objConn as new ADODB.Connection

Dim objRS as new ADODB.Recorset

Dim strConnectionString as String

Dim strSQL as String

'open Connection

objConn.open strConnectionString

'optimize record set properties

objRS.CursorLocation = AdUseClient

objRS.CursorType = adOpenStatic

objRS.LockType = adLockBatchOptimistic

'open the record set

objRS.open strSQL , objConn

'disconnect the record set and close Connection

Set objRS.ActiveConnection = Nothing

ObjConn.Close

'use the recordset

While NOT objRS.eof

'do something

Wend

In a couple of lines data can be retrieved from almost any data source a developer is likely to encounter, including text files and many spreadsheets.

XML

XML is the future for almost all data transmission and data manipulation.  Notice that I did not say anything about the Internet; XML is that huge!

Microsoft, IBM, and Sun support XML-based standards, which include SOAP and UDDI.  These two XML based technologies promise interoperability at the method level across languages, domains, and platforms.  This interoperability allows the RAD abilities of Visual Basic to be felt everywhere, ensuring Visual Basics' place as the most popular development language for years to come.

SOAP is a platform independent protocol, in this sense like HTTP, for exchanging messages in a decentralized, distributed-environment using XML.  SOAP is more standards-based and platform-neutral than previous technologies like CIS, RDS, and Remote Scripting.

The Universal Discovery Description and Integration (UDDI) specifications define a way to publish and discover information about Web Services using XML.  Since a major portion of new development will be Web Services based, UDDI is extremely important because it allows the appropriate functionality to be found on the Internet and utilized.

Best of all, this major shift to platform-independent Web Services as a new industry-wide software model, is fairly simple, all thanks to XML.

Although you can hand-code XML, as you can with HTML, it is easier to have the application do the work. Although this is really BizTalk's forte, here is an example of SQL Server 2000 doing the work, using the very handy FOR XML clause.

SELECT TOP 10 FirstName

FROM Employees

FOR XML AUTO

Results in:

<Employees FirstName="Nancy" EmployeeID="1"/>

<Employees FirstName="Andrew" EmployeeID="2"/>

<Employees FirstName="Janet" EmployeeID="3"/>

<Employees FirstName="Margaret" EmployeeID="4"/>

<Employees FirstName="Steven" EmployeeID="5"/>

<Employees FirstName="Michael" EmployeeID="6"/>

<Employees FirstName="Robert" EmployeeID="7"/>

<Employees FirstName="Laura" EmployeeID="8"/>

<Employees FirstName="Anne" EmployeeID="9"/>

Unfortunately, the FOR XML AUTO clause does not support all SQL statements.  It currently does not even support GROUP BY, for example, which is fairly common.

An alternative to the FOR XML clause is executing SQL statements using the URL.  Although this sounds like the dream of every ASP developer, after all it takes the form of a URL with a SQL statement in the query string, URL access does not allow you to easily write generic Visual Basic functions that return XML from any data source.

http://IISServer/Nwind?sql=SELECT+top+10+FirstName+FROM+Employees +FOR+XML+RAW&root=ROOT

How can you write a generic Visual Basic function that accepts standard SQL statements?  You can not just tack FOR XML AUTO on the end of a regular SQL statement or stick it in the URL.

Even worse, you rely on other database vendors supporting FOR XML or SQL access using HTTP in exactly the same manner.  

ADO equals effortless XML

Fortunately plain ADO does allow you to easily retrieve XML, today.

You can write a generic Visual Basic function, or even one in VB Script, based on the model of a SQL Select query as a parameter and a return value of a XML string.  Furthermore it allows you to easily retrieve the XML, use it, and update it back to the database.  This is functionality you are likely to use again and again, so it is valuable to put the functionality in a data access class.

Since there are so many interesting options available while writing this class, each worthy of its own article, I broke it down into three parts.  Perhaps in future articles, I will explore each part in more depth.

Get the XML from ADO

Call this class ClsDataAccess so it is clear what we intend to use it for.  The most obvious way to implement the class using a simple method GetRS, is still fairly awkward to use.

 Public Function GetRS(ByVal strSQL as String,ByVal strConnectionString as String) as ADODB.Recordset

The awkwardness comes from having the ConnectionStringproperty exposed to the developer, especially if the password is reasonably secure.

"provider=SQLOLEDB; data source=db3x.seriousconsulting.com; initial catalog=Pubs; UID=mtsusr01; PWD=38710z2c7993F82"

How secure can a password be if every developer, designer, content manager, and QA team member has access to a username and password with full read and write permissions on the production server?  Furthermore, changing values within the connection string does not allow the connection to be pooled as efficiently, reducing scalability.

A solution that simplifies reuse and increases security is to set the connection strings as enumerated constants.  Here I provide constants for only two database connections, but in practice, there may often be several.

'the db connectionstrings constants

Public Enum eCONNECTIONSTRING

   CS_Pubs = 0

   CS_NorthWind= 1

End Enum

A simple private function in ClsDataAccess that applies values to the enumerated constants may look like this:

Private Function EvalEnumCS(ConnectionString)

'this is a helper function used by the methods to evaluate the enum value

     If ConnectionString =  CS_ Pubs Then

          EvalEnumCS =  "provider=SQLOLEDB; data source = db3x.seriouscons

ulting.com; initial catalog = Pubs; UID = mtscsusr01; PWD =1eer5130q82F"

     ElseIf ConnectionString = CS_ NorthWind Then

          EvalEnumCS =  "provide r=SQLOLEDB; data source=db2x.ohgolly.com; initial catalog = NorthWind; UID = mtscsusr02; PWD = c4883H55433"

     End If

 Exit Function

By using enumerated constants the method is simpler to use; and by using a function to process the values of the constants, access can be changed in one place for the whole site.  Additionally developers do not need to know any passwords, they create an object from the ClsDataAccess class, pass in a SQL query as a parameter and pick a constant.

Figure 2. Using Enumerated Constants for Database Access

A subtle point that you may have missed is that the connection strings are using a DNS as the datasource property.  This allows the compiled component to be deployed to a development server, QA server, or a production server and hit the correct database without being recompiled.  This is perhaps the best way  to get around the serious shortcoming of having to recompile the class to access a different database in development versus production without having to pass the server name or DSN as an argument of the method.  Remember, passing the Connection String or a DSN as a parameter does not make the GetRS method especially useful.

Here is the GetRS method of the ClsDataAccess, with the enumerated constants and a function to evaluate the constants incorporated into the class.

Public Function GetRS(ByVal strSQL As String,ByVal ConnectionString As eCONNECTIONSTRING = CS_Pubs)

As ADODB.Recordset

'declare variables

Dim objConn as new ADODB.Connection

Dim objRS as new ADODB.Recorset

Dim strConnectionString as String

'set the connection string = to the value of the constant

strConnectionString = CStr(EvalEnumCS(ConnectionString))

'open Connection

objConn.open strConnectionString

'open the record

   'continue as before

This GetRS method is pretty good as a demonstrator, but it returns an ADO Recordset rather than XML. You may want to add error handling and keep it as a method in your data access class, adding a separate method to return XML.

Using Microsoft XML Parser (MSXML) 3.0 there are a couple of ways to get a XML document from the Recordset.  Since the goal is to get XML, and XML is a string, I save the Recordset object to an ADO stream object as XML.

'once the record set is open

objRS.save objADOStream, 1 'adPersistXML

Set objRS.ActiveConnection = Nothing

Conn.Close

' Put the Recordset Stream into a string variable.

strXML = objADOStream.ReadText(-1)  '-1=adReadAll

'return the XML string rather than the record set object

With ADO 2.5 and later, Recordset objects can be persisted into any object that implements the IStream interface. The obvious choice is the ADO Stream object, although the ASP response object also implements IStream.

I use the ADO stream object, which is regrettably infrequently used, so the XML does not have to be saved as a document before we can work with it.  The Recordset can also be saved directly into the XML DOM object. This is more scalable, as it skips having to save the Recordset into an ADO Stream and then loading the ADO Stream into the DOM object.   For demonstration purposes, it is clearer to do the extra step.   Now, you have a usable function that returns XML as a string in a standard ADO Recordset definition.  ADO even allows persistence of hierarchical Recordsets into XML, so you are not especially limited.

Get HTML from the XML

Just to give you an idea of the many uses of XML, lets display the XML as HTML on a web page. Since XML is just data in a text format, you have to transform it with a presentation style before it can be displayed as HTML.  If you write out the raw XML string to a web page the user's browser will not display anything. However, the XML is shown in Source View.

It may not be clear to you what you are seeing in the page source. The source is broken into two sections, a schema section followed by a data section.

The XML document starts with a definition of the record set schema and some additional Meta information. The simplest way to think of a schema is to think of the document as an instance of the schema in the same way an object is an instance of a class.

The actual Recordset data is contained in elements that look like this:

<z:row FirstName='Sean' LastName='Grimaldi' />

If you try working with the XML and experience unexpected problems remember that ADO, and almost all of Windows, is UTF-8 format, where as Java and XML are Unicode.

The Presentation = XML + XSL

In this instance we are using only using simple XSL, although you could also display the XML using Cascading Style Sheets (CSS).  

XSL becomes complex quickly, so it may be useful to keep it basic at first.  There are many excellent code samples and articles on XSL on the Internet, even if there are currently no tools as simple as Visual Basic for working with XSL.

It may be simpler to use a generic XSL style sheet since it will work on any ADO DB Recordset; and modify the XSL as the situation calls for.  An excellent example of a generic XSL style sheet can be in Michele Vivoda topxml.com article http://www.topxml.com/xsl/articles/xsl_ado/.

An ASP page that combines the XML and the XSL could be very short.

'get the XSL style sheet

styleFile = Server.MapPath("Genericxsl.xsl")

'create an XML DOM object, an XSL Dom object, and your Data Access object

Set XMLDoc = Server.CreateObject("Microsoft.XMLDOM")

Set XSLDoc = Server.CreateObject("Microsoft.XMLDOM")

Set DataAccess = server.CreateObject("ProDataAccess.ClsDataAccess")

XMLDoc.async = false

 'load the XML returned from your GetRS method into the XML object XMLDoc.loadXML(DataAccess.GetRs(strSQL,1))

 XSLDoc.async = false

'load the XSL stylesheet into the XSL object

XSLDoc.load(styleFile)

 'write our the HTML result of combining the two

Response.Write XMLDoc.transformNode(XSLDoc)

Combining the XML returning GetRS method with the XSL style sheet results in a plain little HTML table.  Since XSL is much more powerful than what the example has demonstrated, please remember that you could do much, much, more with the XML.  Microsoft Biztalk Server excels at generating XSL so one XML schema can be mapped to a different XML schema.  This means that if you can map fields from one XML document to fields in a generic XML document, you can write more abstract code that deals with one generic case.  This results in more code reuse, faster development, centralized error handling, and more maintainable code.

Get ADORS from the XML

Since you now know that XSL can transform one XML document into an XML document with a different schema, you may have realized that you can transform a very dissimilar XML document into an XML document that is valid to the ADO Recordset schema.  This means you could convert the ADO schema based XML document back into a Recordset, which could be updated to the server/Database.  This uses the source parameter of the ADO Recordset object.

' Open the Stream back into a RecordsetObject.

objRs.open  ADOStream

Almost Done

As I stated, this article is about making the most of ADO and XML until the full-blown Visual Basic.net becomes available.  It covers the Stream object, which is unfortunately commonly ignored.  The sample began showing how ADO could be used to get an XML document from the database.  Secondly the sample demonstrated how the XML document could be used to display records in an HTML table using XSLT.  Lastly, the sample showed how to get the XML into a Recordset object so that the database could be updated.

Obviously this example could be extended quite a bit.  As mentioned, to increase scalability the Stream object could be eliminated from the class. Other extensions, such as more sophisticated XSLT combined with CSS would be valuable in real-world situations.

I hope you reuse the concepts in this article often and to good measure.

Here are some resources you may find useful:

MSDN ADO Stream
http://msdn.microsoft.com/library/default.asp?URL=/library/psdk/dasdk/mdao1ajx.htm

UDDI.org
http://www.uddi.org/

W3C SOAP
http://www.w3.org/TR/SOAP/

W3C XSL
http://www.w3.org/Style/XSL/

TopXML
http://www.topxml.com/xsl/

Posted by 나비:D
:

BLOG main image
by 나비:D

공지사항

카테고리

분류 전체보기 (278)
Programming? (0)
---------------------------.. (0)
나비의삽질 (5)
Application (177)
C# (28)
JAVA (22)
ASP.NET (3)
C++ (19)
C (18)
.NET (0)
Visual Basic (12)
Flex (16)
Eclipse (8)
Delphi (16)
Visual Studio 2005 (5)
Embed (6)
Linux (2)
Mobile (1)
XML (1)
안드로이드 (2)
SQL (51)
Web (27)
etc. (14)
Omnia (0)
---------------------------.. (0)

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

달력

«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Total :
Today : Yesterday :