Nuget 패키지 관리자에서 Universal Window Platform 다운그레이드 혹은 업그레이드 하시면 됩니다.

그러면 재설치되면서 Nuget에 있는 Refernce 재설정 됩니다.


큰 변화를 주지 않기 위해, 영향이 없는 정도에서만 올렸다 내리세요.


상당히 재설치 과정이 오래걸립니다.




Use a SQLite database in a UWP app - UWP app developer _ Microsoft Docs.pdf


SDK 버전 맞추는 거 유의하세요.



'Knowledge' 카테고리의 다른 글

[SQLite3] 튜토리얼 사이트  (0) 2018.04.15
[SQLite3] DataType  (0) 2018.04.15
[MS-SQL] 변수 및 테이블 변수 선언  (0) 2018.03.27
[MS-SQL] 사용자 추가  (0) 2018.03.23
[MS-SQL] 테이블 복사  (0) 2018.03.16

' 전역변수 선언은 이렇게 밖에다 할 수 있다.

' Global keyword는 vb6에서는 사용되지 않는다.


Public LogName As String


Private Sub AddItem_Init(key As String, value As String)

    

    Dim category As String

    Dim message As String

    

    LogName = "practice.ini"

    category = "General"

    message = "[key]:{key}   [value]:{value}"

    

    message = Replace(message, "{key}", key)

    message = Replace(message, "{value}", value)

    

    

    Call fn_WritePrivateProfileString(LogName, category, key, value)

    Call sb_SaveLog(App.EXEName, message)

    

End Sub

'Knowledge > Visual Basic 6+' 카테고리의 다른 글

[VB6] 상수 선언  (0) 2018.05.09
VB6 단축키  (0) 2018.04.19
[VB6] Replace Function - Visual Basic 6.0  (0) 2018.04.02
Visual Basic 문법  (0) 2018.03.27
[VB6] What is Me.Caption  (0) 2018.03.26

Replace Function - Visual Basic 6.0 (VB 6.0)

Returns a string in which a specified substring has been replaced with another substring a specified number of times.
Syntax:
Replace(expression, find, replace[, start[, count[, compare]]])
ParameterDescription
expressionRequired. String expression containing substring to replace.
findRequired. Substring being searched for.
replaceRequired. Replacement substring.
startOptional. Default 1. Position within expression where substring search is to begin.
countOptional. Default -1 (All). Number of substring substitutions to perform.
compareOptional. Default vbBinaryCompare (0). Numeric value indicating the kind of comparison to use when evaluating substrings.

Return Data type:
String
Example:

Dim St as String
St = "Chennaiiq"


StatementResultRemark
Replace(St, "n", "m")Chemmaiiq 
Replace(St, "N", "m")Chennaiiq 
Replace(St, "n", "M")CheMMaiiq 
Replace(St, "n", "m", 5)maiiq 
Replace(St, "n", "m", 4, 1)mnaiiq 
Replace("", "n", "m") Empty String
Replace(null, "n", "m")ErrorInvalid use of null
Replace(St, "", "m")Chennaiiq(Copy of Expression)
Replace(St, "n", "")Cheaiiq 
Replace(St, "n", "m", 20) Empty String
Replace(St, "n", "m", 1, 0)Chennaiiq 


'Knowledge > Visual Basic 6+' 카테고리의 다른 글

VB6 단축키  (0) 2018.04.19
[VB6] 전역변수 선언 (Not Global keyword)  (0) 2018.04.02
Visual Basic 문법  (0) 2018.03.27
[VB6] What is Me.Caption  (0) 2018.03.26
For...Next Statement (Visual Basic)  (0) 2018.03.13



출처: https://support.microsoft.com/ko-kr/help/837910/mouse-wheel-events-do-not-work-in-the-visual-basic-6-0-ide



간단히 dll 등록 후 사용할 경우, 아래 zip 파일을 이용한다.


VBA Mouse Wheel Fix.zip




컴파일 해서 쓰려면 아래 실행파일을 사용한다.


vb6mousewheel.exe


증상


Microsoft Visual Basic 6.0 IDE에서 마우스 휠을 사용 하 여 스크롤할 수 없습니다.

원인


Visual Basic 6.0 IDE에서 마우스 휠을 사용 하 여 스크롤을 기본적으로 지원 하지 않은 때문에이 문제가 발생 합니다.

해결 방법


이 문제를 해결 하려면 다음 방법 중 하나를 사용 합니다.

방법 1

추가 기능 DLL 및 추가 기능 DLL을 만드는 데 사용 되는 코드를 포함 하는 VB6 마우스 Wheel.exe 파일을 다운로드 합니다.
  1. VB6 마우스 Wheel.exe 파일을 다운로드 합니다. 파일은 Microsoft 다운로드 센터에서 다운로드할 수:
    Download 지금 VB6MouseWheel.EXE 패키지 다운로드

    Microsoft 지원 파일을 다운로드하는 방법에 대한 자세한 내용을 보려면 Microsoft 기술 자료의 다음 문서 번호를 클릭합니다.
    119591 온라인 서비스 로부터 Microsoft 지원 파일을 구하는 방법
    Microsoft는 이 파일에 대해 바이러스 검사를 시행하였습니다. Microsoft는 파일이 게시된 날짜에 사용할 수 있었던 최신 바이러스 검색 소프트웨어를 사용했습니다. 파일은 파일을 무단으로 변경할 수 없도록 보안이 강화된 서버에 저장됩니다.
  2. 시작실행을 차례로 누르고 형식 regsvr32 < 경로 > \VB6IDEMouseWheelAddin.dll을 선택한 다음 확인을 누릅니다.
  3. Visual Basic 6.0을 시작 합니다.
  4. 추가 기능을 클릭합니다 하 고을 클릭합니다
    관리자 추가 기능에서합니다.
  5. 추가 기능 관리자 목록에서 클릭
    MouseWheel Fix.
  6. 로드/언로드 확인란을 선택한 다음 시작할 때 로드 확인란을 선택 취소 합니다.
  7. 확인을 클릭합니다.



변수

변수란 값을 담아두는 것이라고 모두 알고 있으실 겁니다.

우선 간단하게 변수를 생성하고 설정하는 방법을 알아보겠습니다.

--변수 생성
--declare 변수명 타입
DECLARE @name varchar(20)

--변수에 값 할당
SET @name = 'Kendrick'

--혹은
--userid가 sonim1일 때 이름이 Kendrick일 경우  
SELECT @name = P.name FROM tblPerson P WHERE userid = 'sonim1'

SET을 하던 SELECT를 하던 동일한 값이 @name 변수에 할당되는 쿼리입니다.

아래는 @name 변수를 이용해서 이어서 해당 user의 가입일을 알아보겠습니다.

SELECT CreateDate -- 생성일 필드
FROM  tblPerson P
WHERE P.name = @name

이정도면 변수의 사용법은 충분히 이해되실것 입니다.

테이블 변수

이제 알아볼 항목은 테이블 변수입니다.
변수에서는 값뿐이 아니라 여러행으로 떨어지는 결과를 담아 둘 수 있습니다.

예를 보 시죠

--테이블 변수 생성, 자료형 대신에 테이블 스키마가 들어가 있다.
DECLARE @userData TABLE(
     name varchar(30) NOT NULL,
     CreateDate datetime NOT NULL
);

--Insert Into Select 문을 이용하여 k로 시작하는 회원의 리스트를 할당해보자
INSERT INTO @userData
SELECT name, CreateDate 
FROM tblPerson
WHERE name like 'k%'

--할당 후에는 변수를 이용하여 테이블처럼 사용가능하다.
SELECT * FROM @userData

변수와 테이블 변수에 대해서 간단하게 알아보았습니다.
테이블 변수를 이용하여 쿼리의 복잡성을 떨어트릴수 있으며, 속도 개선에 많은 도움이 될 것입니다.

테이블 변수와 임시 테이블의 차이점

임시테이블테이블 변수
존재 기간명시적으로 삭제를 안할 시에는 세션 연결 기간동안 존재명시적으로 삭제를 안할 시에는 배치 처리기간 동안 존재
저장소TempdbTempdb
쿼리비용대용량에서는 쿼리 비용 유리소용량에서 쿼리 비용 유리
장단점대용량 데이터 처리에 유리소용량 데이터 처리에서 유리
세션 단위 처리시에 사용저장 프로시져에서 테이블 변수 사용하면 임시 테이블 사용할 떄보다 저장 프로시저를 다시 컴파일하는 일이 줄어듦
배치 처리 단위인 저장 프로시져에서 사용 유리

마치며

잘못 사용하면 성능상 문제가 있겠지만 잘 사용하면 너무나 유용한 기능입니다. 물론 말은 쉽습니다. 하하
사실 잘못 사용하기가 더 어려운 기능이겠네요. !!
좋은 하루 되세요

테이블 변수 임시 테이블 차이점 표 출처 : RunHanii 블로그

'Knowledge' 카테고리의 다른 글

[SQLite3] DataType  (0) 2018.04.15
[WUP] SQLite 관련 Tutorial  (0) 2018.04.14
[MS-SQL] 사용자 추가  (0) 2018.03.23
[MS-SQL] 테이블 복사  (0) 2018.03.16
[MS-SQL] date와 Datetime의 차이점  (1) 2018.03.16

VB6 문법 모음 페이지


# Call Statement

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/call-statement


# Error Statement

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/error-statement


# DO...Loop Statement

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/do-loop-statement


# Exit Statement

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/exit-statement

프로젝트 탭의 참조, 구성요소를 이용하면 된다.



1. DLL을 등록하는 방법



2. OCX 등록하는 방법




vb6 What is Me.Caption


Hi, starting out in vb and working through some exercises and am confronted with a line of code

OldCaption = Me.Caption

The question is what is Me."xxxxxxxxx" and what applications can it be used for.


Many thanks in advance...Andy


--------------------------------------------------------------------------------------------------------------------------------


What is Me?

Me is the form itself. It is just a shorthand of using the form name. So Me.Caption and Formname.Caption is the same.



  OldCaption = Me.Caption

Above code simply saves the caption of the form to a variable named OldCaption.


hongjun


이름

헨리 데이비드 소로,Henry David Thoreau

생몰년도

1817년 7월 12일 ~ 1862년 5월 6일

1. 개요[편집]

시대를 앞서간 작가
미국의 유명 작가이자 사상가.

유명한 작품으로는 월든이 있다.

훗날 그의 사상은 우리나라의 법정스님과 러시아의 대문호 레프 톨스토이, 인도의 국부 마하트마 간디, 미국의 마틴 루터 킹목사, 故넬슨 만델라 남아공 대통령을 비롯한 많은 이들에게 영향을 주었다.

매사추세츠 주의 콩코드에서 태어났으며, 하버드 대학교를 졸업했다. 멕시코 전쟁에 반대해 인두세 납부를 하지 않았다가 감옥에 투옥된 적이 있다.

2. 생태주의[편집]

자연과 사회 문제에 대해 관심이 많았으며, 강연을 하기도 했다.

당시 산업혁명 직후 아메리카 드림등 노동과 성공에만 관심을 쏟던 세태와 달리 직접 숲에서 집을 만들고 혼자서 자립해서 살았다. 당연히 당시 사람들에겐 외면을 받았지만 계속된 노동과 반복에 질린 현대인들에게 월든이 힘이 되어주면서 현대에 와서야 비로소 빛을 바라보기 시작했다.

실천적 초월주의자인 소로우는 미국적 삶의 주류에 정면으로 반기를 든 실험적 삶을 산 사람이었다. 하지만, 당대 생활양식의 비판 근거를 미국적 이념에서 찾았기에 그는 미국적 특성이 강한 작가라고도 여겨진다. 산업화와 근대화에 사로잡힌 근대적인 삶의 양식을 거부하고 비판한 그는 내면의 풍요로움, 검소한 삶, 자급자족의 삶을 강조하였다. 이외에도, 그는 자연친화적인 삶을 중시하고 전쟁과 노예제도를 비롯한 물질문명과 인간의 이기와 탐욕을 싫어하고 반대하며 옳지 못한 정부와 사회에 대해선 합법적이면서도 간접, 소극적으로라도 반대, 저항하고 맞설 것을 주장하는 시민 불복종 운동을 주장한 생태주의자였다.

그렇긴 한데, 1844년 4월경 피시 차우더 수프를 만들던 중 콩코드의 숲 300 에이커(약 1,200,000m2)를 태워먹은 적이 있다. 

3. 명언[편집]

새로운 옷을 요구하는 산업을 조심해라.(I say, beware of all enterprises that require new clothes.)

잔물결 소리에 귀기울이는 사람은 무슨 일이 있어도 절망하지 않으리. (He who hears the rippling of rivers in these degenerate days will not utterly despair.)[1]

4. 작품[편집]

  • 콩코드 강과 메리맥 강에서의 일주일 (1849)[2]

  • 시민 불복종 (1849)

  • 월든 (1854)
    국내 출간된 번역본에선 이름이 헨리 데이빗 소로우로 되어 있다.

5. 매체에서의 등장[편집]

  • 폴아웃 4 - 시대가 2270년도이다 보니 당연히 직접 등장하진 않지만 배경이 콩코드라서 작중에서 소로가 살았던 오두막이 등장한다. 핵폭탄이 떨어졌음에도 오두막은 살아남았다. 오두막 근처 스피커로 소로에 대한 간략한 소개를 들을 수도 있으니, 관심있다면 듣는 것도 좋다. 다만 전쟁 전에 이미 그의 오두막은 기념품 상점으로 변했었고, 호수는 물이 상당히 마른데다 쓰레기도 많이 있으며 지하 땅굴에는 작중의 도적패인 레이더(폴아웃 시리즈)도 살고 있다. 동료 중 하나인 코즈워스는 '핵전쟁이 지나고 나서야 우리가 소박한 삶을 되찾게 되리란걸 소로는 생각조차 못했을 것 이다.'라고 씁쓸한 한마디를 한다. 그 외의 동료들도 한마디 씩은 하는데, 퀴리(폴아웃 4)와 파이퍼 라이트닉 발렌타인 등 선 성향은 대체적으로 긍정적인 말을 하지만 악 성향은 비꼬거나 비웃는 말을 한다. 가장 백미는 팔라딘 댄스의 '나 이 작가 알어. 숲속으로 살아남기인가 하는 책 쓴 사람 아냐?'(...)


[1] 월든의 대사. 평론가 이동진이 영화 문라이트의 평에서 인용하기도 했다.[2] 주변인의 권유로 소로가 처음 낸 책인데 말그대로 폭망해버려 소로가 남은 책을 다 사야만했다


'메모' 카테고리의 다른 글

[스크랩] 로크와 홈스 사회계약설  (0) 2018.03.25
디자인 0130  (0) 2018.01.30
아이디어 0117  (0) 2018.01.17

서양철학 여행

[김홍일쌤의 서양철학 여행] (33) 로크의 사회계약설(상): 통치론


저항권의 정당성 입증

로크가 《통치론》에서 제시한 사회계약 원리들 중 백미는 무엇보다 국민의 저항권을 인정한 데 있다. 로크가 《통치론》을 저술한 실질적인 목적은 저항권의 정당성을 입증하는 데 있었다. 저항권이란 정부가 처음 만들어질 당시의 목적을 제대로 수행하지 않는다면, 즉 구성원의 생명과 재산, 자유를 보호하지 않는다면 무력을 사용해서라도 저항할 수 있다는 논리다. 당시 전제 군주가 무소불위의 권력을 휘두르고, 그의 권력에 대한 도전은 신성모독죄로 간주되던 시대에 대범하게도 로크는 국민의 저항을 권리로서 인정했던 것이다.

홉스와 마찬가지로 로크 역시 인간의 자연상태를 전제로 자신의 사회계약 논의를 전개한다. 그러나 로크가 보기에 ‘만인의 만인에 대한 투쟁’과 같은 홉스의 자연상태를 보는 가정에는 난점을 가지고 있다. 왜냐하면 합리적인 이기주의자가 자연상태에서 계약하는 이유는 계약을 통해 자기 자신 특히 자신의 생명과 자유와 재산을 더 잘 보호하려는 의도에서라는 것이다. 그런데 자연상태에서 누리던 평등을 포기하고 절대 군주의 지배 아래 예속된다는 홉스의 추론은 합리성의 관점에서 볼 때 설득력이 떨어진다. 왜냐하면 자신의 처지가 더 나빠지는 계약에 합의하는 합리적인 존재는 생각하기 어렵기 때문이다.

군주도 이기적인 인간일 뿐

로크가 보기에 홉스의 추론은 논리적 일관성이 없다. 로크에 의하면 홉스의 사회계약이란 사회 구성원 간에 성립하는 것으로서 그 속에 군주는 포함되지 않는다. 그러나 군주도 하나의 이기적인 인간에 불과하다. 이러한 군주가 재판관이 되고 군주가 임의로 사람들을 해친다면 이는 오히려 자연상태보다 못한 상황이 된다. 이와 같은 절대 군주제 아래에서 살아간다는 것은 말하자면 자연상태 속의 여우를 피하려다가 오히려 사자에게 잡아먹히는 것과 다를 바 없다. 이 경우 군주와 사회 구성원의 관계는 여전히 자연상태에 있게 돼 전쟁이 계속된다는 문제가 있다.

따라서 홉스의 사회계약설에서는 군주의 이기심 문제를 해결하기 위해 군주와 사회 구성원 간에 다시 하나의 계약이 요청된다. 그런데 그렇게 되면 이 계약 이행을 보장하기 위해 계약을 감시할 더 높은 또 다른 하나의 군주가 필요하게 된다. 문제는 이러한 과정은 무한정 계속돼야 한다. 따라서 홉스의 사회계약 추론은 무한소급의 오류에 빠진다.

이러한 난점을 피하기 위해 로크는 자연상태를 자유롭고 평등한 상태라고 가정한다. 자연상태가 이처럼 평화롭고 목가적이라면 홉스와 달리 로크에게 있어서 사람들이 계약을 통해 국가나 정부를 수립하는 합리적인 이유는 무엇인가? 로크에 의하면 자연상태의 질서가 갖는 불완전성 때문이다. 즉 사람들이 저마다 자신의 행위가 옳다고 주장할 경우 자연상태에서는 이를 중재할 재판관이 없기 때문에 모두가 불안한 상태에서 지내야만 한다는 것이다. 이를 해소하기 위해 정치 공동체인 정부를 만들 수밖에 없으며, 이때 자신의 권리를 대리자인 정부에 일부 양도하기로 계약을 맺는다. 여기서 양도의 대상이 되는 권리는 ‘소유권’을 지키기 위한 이차적 권리인 ‘처벌권’이다. 원래의 권리인 소유권은 전혀 양도되지 않는다.

홉스의 계약설 문제 해소

이렇게 보면 로크는 통치권을 절대 군주로부터 국민에게로 옮김으로써 홉스의 사회계약설이 안고 있는 문제를 해결하고자 했다. 이제 로크에게 있어서 정부는 더 이상 통치자가 아니다. 정부는 사람들의 소유권을 보호하기 위해 부분적으로 양도받은 권한을 갖고 있는 국민의 대리자로서 의미를 갖는다. 권력의 주인은 국민이므로 국민은 통치받는 사람인 동시에 통치자가 된다.

절대왕정 시기 로크의 사회계약 사상은 가히 혁명적이었으며, 명예혁명 이전 로크의 《통치론》은 당연하게도 불온서적으로 지정됐다. 그러나 《통치론》의 내용들은 프랑스에 전해져 프랑스 혁명을 일으키는 도화선이 됐으며, 미국에 전해져 미국 혁명을 정당화하는 이론적 도구가 됐다. 절대 권력에서 사람들이 해방된 것이 그리 오래전 일이 아니란 점에서 오늘날 우리가 향유하는 모든 자유와 권리는 공기처럼 당연한 것이 아니라는 것을 다시 생각하게 된다.

◆기억해주세요

<통치론>의 내용들은 프랑스에 전해져 프랑스 혁명을 일으키는 도화선이 됐으며, 미국에 전해져 미국 혁명을 정당화하는 이론적 도구가 됐다.

김홍일 < 서울과학고 교사 > 

'메모' 카테고리의 다른 글

[스크랩] 데이비드 헨리 소우로  (0) 2018.03.26
디자인 0130  (0) 2018.01.30
아이디어 0117  (0) 2018.01.17

[MSSQL] 사용자 추가.pdf


'Knowledge' 카테고리의 다른 글

[WUP] SQLite 관련 Tutorial  (0) 2018.04.14
[MS-SQL] 변수 및 테이블 변수 선언  (0) 2018.03.27
[MS-SQL] 테이블 복사  (0) 2018.03.16
[MS-SQL] date와 Datetime의 차이점  (1) 2018.03.16
Encoding URL  (0) 2018.03.07

MS-SQL 테이블 복사


1. 테이블을 생성하면서 테이블의 데이타 복사


select * into 생성될테이블명 from 원본테이블명


테이블 구조만 복사하겠다면

select * into 생성될테이블명 from 원본테이블명 where 1=2


2. 테이블이 이미 생성되어 있는경우 데이타만 복사


insert into 카피될테이블명 select * from 원본테이블명


특정 데이타만 복사 하겠다면

insert into 카피될테이블명 select * from 원본테이블명 where 검색조건




출처: http://iberis.tistory.com/10 [Iberis]

'Knowledge' 카테고리의 다른 글

[MS-SQL] 변수 및 테이블 변수 선언  (0) 2018.03.27
[MS-SQL] 사용자 추가  (0) 2018.03.23
[MS-SQL] date와 Datetime의 차이점  (1) 2018.03.16
Encoding URL  (0) 2018.03.07
PSTN  (0) 2018.03.04

날짜 및 시간 데이터 형식 및 함수(Transact-SQL)

이 항목은 다음에 적용됩니다.예SQL Server(2012부터)아니요Azure SQL Database아니요Azure SQL Data Warehouse 아니요병렬 데이터 웨어하우스

이 항목의 다음 섹션에서는 Transact-SQL의 모든 날짜/시간 데이터 형식 및 함수에 대한 개요를 제공합니다.

날짜 및 시간 데이터 형식

Transact-SQL 날짜 및 시간 데이터 형식이 다음 표에 나열 되어 있습니다.

데이터 형식형식범위정확도저장소 크기(바이트)사용자 정의 초 소수 부분 자릿수표준 시간대 오프셋
timehh:mm:ss[.nnnnnnn]00:00:00.0000000부터 23:59:59.9999999까지100나노초3 ~ 5아니요
dateYYYY-MM-DD0001-01-01부터 31.12.99까지1일3아니요아니요
smalldatetimeYYYY-MM-DD hh:mm:ss1900-01-01부터 2079-06-06까지1분4아니요아니요
datetimeYYYY-MM-DD hh:mm:ss[.nnn]1753-01-01부터 9999-12-31까지0.00333초8아니요아니요
datetime2YYYY-MM-DD hh:mm:ss[.nnnnnnn]0001-01-01 00:00:00.0000000부터 9999-12-31 23:59:59.9999999까지100나노초6 ~ 8아니요
datetimeoffsetYYYY-월-일 h:mm: ss [.nnnnnnn] [+ |-] hh: mm0001-01-01 00:00:00.0000000부터 9999-12-31 23:59:59.9999999까지(UTC)100나노초8 ~ 10

Note

Transact-SQL rowversion 데이터 형식이 날짜 또는 시간 데이터 형식 않습니다. 타임 스탬프 에 대 한 사용 되지 않는 동의어 rowversion합니다.

날짜 및 시간 함수

다음 표에는 Transact-SQL 날짜 및 시간 함수가 나와 있습니다. 결정성에 대 한 자세한 내용은 참조Deterministic and Nondeterministic Functions합니다.

시스템 날짜 및 시간 값 가져오기 함수

모든 시스템 날짜 및 시간 값은 SQL Server 인스턴스가 실행 중인 컴퓨터 운영 체제에서 가져옵니다.

정밀도가 높은 시스템 날짜 및 시간 함수

SQL Server 2017GetSystemTimeAsFileTime() Windows API를 사용 하 여 날짜 및 시간 값을 가져옵니다. 정확도는 SQL Server 인스턴스가 실행되고 있는 컴퓨터의 하드웨어와 Windows 버전에 따라 달라집니다. 이 API의 정밀도는 100나노초로 고정됩니다. GetSystemTimeAdjustment() Windows API를 사용 하 여 정확도 확인할 수 있습니다.

'Knowledge' 카테고리의 다른 글

[MS-SQL] 사용자 추가  (0) 2018.03.23
[MS-SQL] 테이블 복사  (0) 2018.03.16
Encoding URL  (0) 2018.03.07
PSTN  (0) 2018.03.04
C# Winforms Message Box  (0) 2018.03.04

For...Next Statement (Visual Basic)

Repeats a group of statements a specified number of times.

Syntax

For counter [ As datatype ] = start To end [ Step step ]  
    [ statements ]  
    [ Continue For ]  
    [ statements ]  
    [ Exit For ]  
    [ statements ]  
Next [ counter ]  

Parts

PartDescription
counterRequired in the For statement. Numeric variable. The control variable for the loop. For more information, see Counter Argument later in this topic.
datatypeOptional. Data type of counter. For more information, see Counter Argument later in this topic.
startRequired. Numeric expression. The initial value of counter.
endRequired. Numeric expression. The final value of counter.
stepOptional. Numeric expression. The amount by which counter is incremented each time through the loop.
statementsOptional. One or more statements between For and Next that run the specified number of times.
Continue ForOptional. Transfers control to the next loop iteration.
Exit ForOptional. Transfers control out of the For loop.
NextRequired. Terminates the definition of the For loop.

Note

The To keyword is used in this statement to specify the range for the counter. You can also use this keyword in the Select...Case Statement and in array declarations. For more information about array declarations, see Dim Statement.

Simple Examples

You use a For...Next structure when you want to repeat a set of statements a set number of times.

In the following example, the index variable starts with a value of 1 and is incremented with each iteration of the loop, ending after the value of index reaches 5.

VB
For index As Integer = 1 To 5
    Debug.Write(index.ToString & " ")
Next
Debug.WriteLine("")
' Output: 1 2 3 4 5

In the following example, the number variable starts at 2 and is reduced by 0.25 on each iteration of the loop, ending after the value of number reaches 0. The Step argument of -.25 reduces the value by 0.25 on each iteration of the loop.

VB
For number As Double = 2 To 0 Step -0.25
    Debug.Write(number.ToString & " ")
Next
Debug.WriteLine("")
' Output: 2 1.75 1.5 1.25 1 0.75 0.5 0.25 0 

Tip

A While...End While Statement or Do...Loop Statement works well when you don't know in advance how many times to run the statements in the loop. However, when you expect to run the loop a specific number of times, a For...Next loop is a better choice. You determine the number of iterations when you first enter the loop.

Nesting Loops

You can nest For loops by putting one loop within another. The following example demonstrates nested For...Next structures that have different step values. The outer loop creates a string for every iteration of the loop. The inner loop decrements a loop counter variable for every iteration of the loop.

VB
For indexA = 1 To 3
    ' Create a new StringBuilder, which is used
    ' to efficiently build strings.
    Dim sb As New System.Text.StringBuilder()

    ' Append to the StringBuilder every third number
    ' from 20 to 1 descending.
    For indexB = 20 To 1 Step -3
        sb.Append(indexB.ToString)
        sb.Append(" ")
    Next indexB

    ' Display the line.
    Debug.WriteLine(sb.ToString)
Next indexA
' Output:
'  20 17 14 11 8 5 2
'  20 17 14 11 8 5 2
'  20 17 14 11 8 5 2

When nesting loops, each loop must have a unique counter variable.

You can also nest different kinds control structures within each other. For more information, see Nested Control Structures.

Exit For and Continue For

The Exit For statement immediately exits the ForNext loop and transfers control to the statement that follows the Next statement.

The Continue For statement transfers control immediately to the next iteration of the loop. For more information, see Continue Statement.

The following example illustrates the use of the Continue For and Exit For statements.

VB
For index As Integer = 1 To 100000
    ' If index is between 5 and 7, continue
    ' with the next iteration.
    If index >= 5 And index <= 8 Then
        Continue For
    End If

    ' Display the index.
    Debug.Write(index.ToString & " ")

    ' If index is 10, exit the loop.
    If index = 10 Then
        Exit For
    End If
Next
Debug.WriteLine("")
' Output: 1 2 3 4 9 10

You can put any number of Exit For statements in a ForNext loop. When used within nested ForNextloops, Exit For exits the innermost loop and transfers control to the next higher level of nesting.

Exit For is often used after you evaluate some condition (for example, in an If...Then...Else structure). You might want to use Exit For for the following conditions:

  • Continuing to iterate is unnecessary or impossible. An erroneous value or a termination request might create this condition.

  • A Try...Catch...Finally statement catches an exception. You might use Exit For at the end of the Finally block.

  • You have an endless loop, which is a loop that could run a large or even infinite number of times. If you detect such a condition, you can use Exit For to escape the loop. For more information, see Do...Loop Statement.

Technical Implementation

When a For...Next loop starts, Visual Basic evaluates start, end, and step. Visual Basic evaluates these values only at this time and then assigns start to counter. Before the statement block runs, Visual Basic compares counter to end. If counter is already larger than the end value (or smaller if step is negative), the For loop ends and control passes to the statement that follows the Next statement. Otherwise, the statement block runs.

Each time Visual Basic encounters the Next statement, it increments counter by step and returns to the Forstatement. Again it compares counter to end, and again it either runs the block or exits the loop, depending on the result. This process continues until counter passes end or an Exit For statement is encountered.

The loop doesn't stop until counter has passed end. If counter is equal to end, the loop continues. The comparison that determines whether to run the block is counter <= end if step is positive and counter >= end if step is negative.

If you change the value of counter while inside a loop, your code might be more difficult to read and debug. Changing the value of start, end, or step doesn't affect the iteration values that were determined when the loop was first entered.

If you nest loops, the compiler signals an error if it encounters the Next statement of an outer nesting level before the Next statement of an inner level. However, the compiler can detect this overlapping error only if you specify counter in every Next statement.

Step Argument

The value of step can be either positive or negative. This parameter determines loop processing according to the following table:

Step valueLoop executes if
Positive or zerocounter <= end
Negativecounter >= end

The default value of step is 1.

Counter Argument

The following table indicates whether counter defines a new local variable that’s scoped to the entire For…Nextloop. This determination depends on whether datatype is present and whether counter is already defined.

Is datatypepresent?Is counteralready defined?Result (whether counter defines a new local variable that’s scoped to the entire For...Next loop)
NoYesNo, because counter is already defined. If the scope of counter isn't local to the procedure, a compile-time warning occurs.
NoNoYes. The data type is inferred from the start, end, and step expressions. For information about type inference, see Option Infer Statement and Local Type Inference.
YesYesYes, but only if the existing counter variable is defined outside the procedure. That variable remains separate. If the scope of the existing counter variable is local to the procedure, a compile-time error occurs.
YesNoYes.

The data type of counter determines the type of the iteration, which must be one of the following types:

  • A Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.

  • An enumeration that you declare by using an Enum Statement.

  • An Object.

  • A type T that has the following operators, where B is a type that can be used in a Booleanexpression.

    Public Shared Operator >= (op1 As T, op2 As T) As B

    Public Shared Operator <= (op1 As T, op2 As T) As B

    Public Shared Operator - (op1 As T, op2 As T) As T

    Public Shared Operator + (op1 As T, op2 As T) As T

You can optionally specify the counter variable in the Next statement. This syntax improves the readability of your program, especially if you have nested For loops. You must specify the variable that appears in the corresponding For statement.

The start, end, and step expressions can evaluate to any data type that widens to the type of counter. If you use a user-defined type for counter, you might have to define the CType conversion operator to convert the types of start, end, or step to the type of counter.

+ Recent posts