반응형

아래 코드는 특정 경로에 있는 폴더 내 모든 파일을 확인.

Option Explicit
Dim oFso
Dim oFolder
Dim oFile

Dim sFileName

' 특정 경로의 폴더 내 모든 파일을 확인
' path뒤에 경로만 바꿔주면 됌
Dim path
path = "C:\WDIR\EEVX.2.12\2_Update_list_file_export\projects\PCB\"


Set oFso = CreateObject("Scripting.FileSystemObject")

If (oFso.FolderExists(path)) Then
    Set oFolder = oFso.GetFolder(pathDate)

    For Each oFile in oFolder.Files
        sFileName = oFile.name
        wscript.echo sFileName
    Next

End If

폴더를 제외한 파일만 확인함.

 

 

 

 

 

 

 

 

 

반응형
반응형

아래 코드는 폴더를 생성, 파일을 생성, 파일에 글도 쓴다.

    Set fso = CreateObject("Scripting.FileSystemObject")

    ' 현재경로에 임시 폴더 생성, 이미 있는경우 경고 발생, 에러 무시 코드 넣기
    On Error Resume Next
    Set txtFile = fso.CreateFolder(".\TEMP")
    On Error GoTo 0

    ' 현재경로에 파일 생성
    Set txtFile = fso.CreateTextFile(".\test.txt", true)


    ' 값 쓰기 아래 
    txtFile.Writeline("hello world")

    
    txtFile.close

 

(결과)

빈 폴더가 생성됨.

파일이 생성되고 글자가 쓰여있음

 

반응형
반응형

딕셔너리 장점.

1. 데이터 검색,추가,수정,삭제 쉬움

2. 간단히 사용

3. 모든 데이터 (배열, 딕셔너리)를 넣어서 사용가능.

 

갖고있는 속성 (Property)

 - Count : 현재 저장 갯수 반환

 - Item("Key값") : "Key값" 을 이용해 할당되어있는 값을 반환

 - Key("Item값") : "Item값" 을 이용해 할당되어있는 Key값을 반환

 - CompareMode : Dictionary Object 에서 String(문자열) Key를 비교하는 모드.

 

갖고있는 매서드 (Method)

 - Add [key]: key 값 추가 (존재하면 에러 key값 중복x)

 - Add [Value] : item 값 추가

 - Remove [key] : 유저가 지정한 Key값 및 value 제거

 - RemoveAll : 모든 Key와 Value 제거

 - Exists(키값) : 키값이 존재하면 True 반환, 없으면 False 반환

 - Keys : 모든 key값을 배열(array)반환

 - Items : 모든 value값을 배열(array)로 반환

 

 

딕셔너리를 생성할 때는 아래와 같이 만든다.

' dictionary 만들때
dim oDict
Set oDict = CreateObject("scripting.Dictionary")

 

딕셔너리의 인자는 Key : item 으로 이루어져 있다.

Key와 item 은 서로 1:1 매칭이며, Key값은 중복되지 않으며 고유하다. 이를통해 item을 빠르게 찾을 수 있다.

생성한 dictionary에 key값과 item값을 추가하는 방법은 아래와 같다.

oDict.Add key값, item값 (여기서 oDict 은 Dictionaray object)

' key : item 으로 구성
' 1 : apple
' 2 : banana 
' "test" : "orange"
' 으로 매칭시켜놓음


dim oDict
Set oDict = CreateObject("scripting.Dictionary")

' key : item 으로 구성
' Add 매서드를 이용해 값 넣기 
oDict.Add 1,"apple"
oDict.Add 2,"banana"
oDict.Add "test", "orange"

' Item 프로퍼티(속성)을 이용해 넣는 방법
oDict.Item("example") = "juice"

msgbox oDict.item(1)
msgbox oDict.item(2)
msgbox oDict.item("test")

(실행결과) 위 key값들이 순서대로 출력

 

Key값 변경하기

key값  1을 item값을 제거하고, 새로운 값 "damm"을 넣음

' dictionary 만들때
dim oDict
Set oDict = CreateObject("scripting.Dictionary")

' key : item 으로 구성
oDict.Add 1,"apple"
oDict.Add 2,"banana"
oDict.Add "test", "orange"
' Item 프로퍼티(속성)을 이용해 넣는 방법
oDict.Item("example") = "juice"

' 해당 key값을 제거하고 새로운 item 값을 넣음
oDict.Remove 1
oDict.Add 1,"damm"

msgbox oDict.item(1)
반응형

(결과)

 

 

Key값 존재 여부 확인 후 값 넣기

Key값이 이미 존재 한다면 해당 Key에 새로운 값을 넣음

' dictionary 만들때
dim oDict
Set oDict = CreateObject("scripting.Dictionary")

' key : item 으로 구성
oDict.Add 1,"apple"
oDict.Add 2,"banana"
oDict.Add "test", "orange"
' Item 프로퍼티(속성)을 이용해 넣는 방법
oDict.Item("example") = "juice"

if oDict.exists(1) then
    oDict.item(1) = "pineapple"
End if

msgbox oDict.item(1)

 

아래 예시는 좀 더 복잡하게 Dictionary를 선언하여 Value값에 List와 같은 값을 넣어서 활용하는 방법이다.

VBScript는 List라는 Type이 없어서 Array를 사용한다.

https://ansan-survivor.tistory.com/1946

 

[Visual Basic] 비주얼베이직 스크립트 (VBScript), 딕셔너리 (Dictionary)에 List, Array (리스트, 배열) 활용

VBscript에서 Dictionary를 만들고 사용하는 간단한 방법과 설명은 아래 링크를 참고. https://ansan-survivor.tistory.com/1627 [Visual Basic] 비주얼베이직 스크립트 (VBScript), 딕셔너리 (Dictionary) 만들기 사용하기

ansan-survivor.tistory.com

 

 

 

(자세한 사항은 마소 docs 보기)

https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/dictionary-object

 

Dictionary object

Office VBA reference topic

docs.microsoft.com

 

 

반응형
반응형

 

DataSheetFileName에 파일명을 쓰면 해달 파일명으로 접근한다.
만약 파일명이 없으면 새로 생성.
 
"notepad.exe" 는 윈도우 환경변수에 저장된 메모장을 실행하는 명령어이다.
다른 프로그램 .exe 파일이 등록되면 해당 프로그램을 실행시킨다.
 
만약 환경변수에 저장되있지 않으면, Full Path를 쓰면 된다.
 
DataSheetFileName = "test"

' Example of how to launch a third party executable 
Dim Win 
Set win = CreateObject("WScript.shell") ' Create the windows object 
'Use the run method to launch an application on the specific datasheet 
win.run "notepad.exe " & DataSheetFileName

 

반응형

 

DataSheetFileName 에 특정 .txt 파일명을 넣으면 해당 파일을 연다. (로그 파일 열때 사용하면 좋음)

 

 

 

 

 

 

 

 

반응형
반응형

 

 

(아래 사이트 참고)

https://www.tutorialspoint.com/vbscript/vbscript_strings.htm

 

VBScript - Strings

VBScript - Strings Strings are a sequence of characters, which can consist of alphabets or numbers or special characters or all of them. A variable is said to be a string if it is enclosed within double quotes " ". Syntax variablename = "string" Examples s

www.tutorialspoint.com

 

(문자열 함수에 대한 자세한 옵션들 설명 자료)

https://www.promotic.eu/en/pmdoc/ScriptLangs/VBScript/PropMeth/InstrRev.htm

 

InstrRev - function of language VBScript

Description: Returns the position of an occurrence of one string within another, from the end of string. Syntax: Integer InstrRev(String string1, String string2, [Integer start], [Integer compare]) Parameters: string1(String) Text string being searched str

www.promotic.eu

 

 

 

VBScript 관련 문자열 처리 함수

InStr 지정된 부분 문자열의 첫 번째 항목을 반환합니다. 왼쪽에서 오른쪽으로 Search
InstrRev 지정된 부분 문자열의 첫 번째 항목을 반환합니다.
Lcase 문자열의 소문자를 반환합니다.
Ucase 문자열의 대문자를 반환합니다.
Left 문자열의 왼쪽에서 특정 수의 문자를 반환합니다.
Right 문자열의 오른쪽에서 특정 수의 문자를 반환합니다.
Mid 지정된 매개변수를 기반으로 문자열에서 특정 수의 문자를 반환합니다.
Ltrim 문자열의 왼쪽 공백을 제거한 후 문자열을 반환합니다.
Rtrim 문자열의 오른쪽 공백을 제거한 후 문자열을 반환합니다.
Trim 왼쪽, 오른쪽 (양쪽) 모두 공백을 제거한 후 문자열 값을 반환합니다.
Len 주어진 문자열의 길이를 반환합니다.
Replace 문자열을 다른 문자열로 바꾼 후 문자열을 반환합니다.
Space 지정된 공백 수로 문자열을 채웁니다.
StrComp 지정된 두 문자열을 비교한 후 정수 값을 반환합니다.
String 지정된 횟수만큼 지정된 문자가 있는 String을 반환합니다.
StrReverse 주어진 문자열의 문자 순서를 반대로 한 후 문자열을 반환합니다.

 

반응형

 

1. InStr

  왼쪽부터 "dich" 라는 글자를 찾아 첫 단어의 위치를 리턴

Dim strName 
strName = "Ich liebe dich so wie du mich Am a bend und am morgen"

a = InStr(strName, "dich")

msgbox a

2. Lcase , Ucase

Dim strName 
strName = "Ich liebe dich so wie du mich Am a bend und am morgen"

a = Lcase(strName)
b = Ucase(strName)

msgbox a & vbCrLf & b

  문자열을 대소문자로 출력

 

3. Left, Right, Mid

Dim strName 
strName = "Ich liebe dich so wie du mich Am a bend und am morgen"

a = Left(strName, 3)
b = Right(strName, 5)
c = Mid(strName, 6, 10)

' vbCrLf 줄바꿈 케리지 리턴
msgbox a & vbCrLf & b & vbCrLf & c

  좌측 우측으로 부터 지정 갯수만큼 출력

  중앙의 시작과 끝 부분 지정으로 출력

 

4. Ltrim, Rtrim, Trim

   왼쪽 끝, 오른쪽 끝의 공백을 제거,  양쪽모두 공백 제거

Dim strName 
strName = "    Ich liebe    "


' 왼쪽 공백제거
a = LTrim(strName)
' 오른쪽 공백을 제거
b = Rtrim(strName)
' 왼쪽, 오른쪽 끝 모든 공백 제거
c = Trim(strName)

' vbCrLf 줄바꿈 케리지 리턴
msgbox strName & vbCrLf & a & vbCrLf & b & vbCrLf & c

 

5. Len

  문자열의 갯수를 반환

Dim strName 
strName = "Ich liebe"


a = Len(strName)

msgbox a

 

6. Replace

    특정 문자열을 대체함

Parameters:

(String) Text string containing substring to replace
(String) Substring being searched for
(String) Replacement substring
[optional](Integer) 문자열 검사를 시작할 위치. 미지정시 1로 세팅.
[optional](Integer) 검사할 문자열의 갯수 지정. 미설정시 -1로 세팅(모든 항목을 검사를 의미)
[optional](Integer) Numeric value indicating the kind of comparison to use when evaluating substrings. If not set, then a binary comparison is performed.
vbBinaryCompare - perform a binary comparison
vbTextCompare - perform a textual comparison
' 소문자 a를 대문자 P로 변경
a = Replace("AaBbBaAaA", "a", "P")
msgbox a

 3번째부터 끝(-1)까지 검사 중, a를 P로 변경

' Replace()
a = Replace("AaBbBaAaA", "a", "P", 3, -1)

msgbox a

 

7. Space

  지정한 갯수만큼 공백이 채워짐

Dim strName 
strName = "Ich liebe"

repStr = "damm"

a = Space(10)

msgbox strName & a & repStr

 

8. StrComp

  두 문자열 비교 동일한지 다른지, 긴지 적은지

Dim str1, str2 

' 두 문자열이 동일하면 0을 리턴
str1 = "weAreSame"
str2 = "weAreSameABCD"

a = StrComp(str1, str2)

msgbox a

 

9. String

  문자열을 지정한 갯수만큼 복사하여 반환

' 지정된 문자를 숫자만큼 복제하여 반환
a = String(5, "*")
b = String(10, "!")

msgbox a & " " & b

 

 

10. 문자열을 역순으로 뒤집음

Dim s
s = StrReverse("VBScript")   ' s contains "tpircSBV"
msgbox s

 

 

반응형
반응형

 

<경로에 파일 생성하여 쓰기>

Dim  fso, fileName, filePath, storing, str, LogFile

' 저장하고자 하는 파일 명, 저장 경로 설정
fileName = "myLog.txt"
filePath = "c:\LogFiles\"
storing = filePath & fileName

' string도 내용 안에 넣을 수 있음. (24번 줄에 추가함)
str ="Hello World"

' 특정 경로에 파일 생성하여 로고 생성
Set fso = CreateObject("Scripting.FileSystemObject")

MsgBox "Logfile path is " & filePath & fileName,,"Check your Path"

' LogFile에 파일생성 후 Write가 가능하도록 object 생성
' WriteBlankLines(아래칸이동)
' vbCrLf : 케리지 리턴 (엔터키)
' WriteLine vs Write : WriteLine는 출력 이후 줄을 바꿉니다. Write 는 출력만 합니다.

Set LogFile = fso.CreateTextFile(storing, True)
LogFile.Write("This is a test write to the logfile")
LogFile.WriteBlankLines(3)
LogFile.Write("The Value of string 3 is " & str & vbCrLf)
LogFile.WriteBlankLines(2)
LogFile.WriteLine("Closing the Logfile")
LogFile.Write("end")
LogFile.close

MsgBox "Log file was successfully created.",,"Done!"
반응형

(결과)

어느 경로에 생성되었는지 알림
생성이 되었다고 알림

    str에 추가한 문자열도 잘 들어가있음, 문자열 변경 후 end도 잘 들어감

 

 

 

반응형
반응형

(윈도우 상에서 드라이브 맵핑 하는 방법은 아래를 참고...)

https://ansan-survivor.tistory.com/873

 

[Windows] 네트워크 경로(공유 폴더)를 나만의 드라이브(D: E: F: ... X: Y: Z: 등등)로 잡기

IP주소나 UNC주소로 잡기도 불편한 경우가 있다. 이 경우 마치 드라이브연결한것처럼 나만의 드라이브 예를들면 Z: 나 X: 로 잡히게끔 만들 수 있다. 예를 들면 리눅스로 smb계정을 만들어 윈도우랑

ansan-survivor.tistory.com

 

 

(아래 튜토리얼 참고)

https://www.tutorialspoint.com/vbscript/vbscript_fso_objects.htm

 

VBScript FileSystem Objects

VBScript FileSystem Objects What are FSO Objects? --> As the name suggests, FSO Objects help the developers to work with drives, folders and files. In this section, we will discuss − Objects and Collections Sr.No. Object Type & Description 1 Drive Drive

www.tutorialspoint.com

 

OS에서 특정 드라이브를 읽고 그 용량을 kbyte 단위로 출력해주는 코드

Dim oFS, drive, space
Set oFS = CreateObject("Scripting.FileSystemObject")

dim driveName 
driveName = "C:\" 

Set drive = oFS.GetDrive(oFS.GetDriveName(driveName))

space = driveName & UCase(drvPath) & " - " 
space = space & drive.VolumeName   & "  "
space = space & "Free Space: " & FormatNumber(drive.FreeSpace/1024, 0) 
space = space & " Kbytes"

msgbox("driveName : " & space)
반응형


(결과)

만약 다른 드라이브라면, drivename에 드라이브 명만 바꾸면 된다.

 

반응형
반응형

Runtime 도중 에러가 발생하면 모든 작업이 중단되고 비정상 종료가 된다.

하지만 중요한 작업의 경우, 또는 시간이 아주 오래걸리는 경우, 별것도아닌 사소한 에러로 종료가 되면 가슴이 아프다.

 

대표적으로 에러를 무시하고 진행하는 코드

On Error Resume Next

이 스위치를 off 시키는 코드

On Error GoTo 0

 

 

에러 핸들링을 위한 예제 코드

아래는 0으로 나눠 고의로 에러를 일으키는 예시이다.

에러가 발생하면 Err.Number에는 에러넘버가 들어가고 그때 발생한 에러의 설명 Err.Description을 출력한다.

해당 에러를 다시 클리어 하고 Err.Clear  계속 진행한다.

On Error Resume Next

' 0으로 나누는 예시
result = 10 / 0

' 오류 체크
If Err.Number <> 0 Then
    ' 오류 발생 시 실행할 작업
    WScript.Echo "오류 발생: " & Err.Description
    ' 오류 정보 초기화
    Err.Clear
End If

On Error GoTo 0
' 다음 작업 계속...

 

 

 

* On Error GoTO 0 와 Err.Clear 차이점.

  • On Error GoTo 0: 오류 처리를 기본 상태로 되돌림.
  • Err.Clear: 현재 오류 정보를 초기화하여 오류 번호와 설명을 비움.

 

 

Error Handling에 대한 자료들

https://www.tutorialspoint.com/vbscript/vbscript_error_handling.htm

 

VBScript - Error Handling

VBScript - Error Handling There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors. Syntax errors Syntax errors, also called parsing errors, occur at interpretation time for VBScript. For example, the fo

www.tutorialspoint.com

 

VBScript 관련 에러 메세지 종류

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

 

Visual Basic error messages

Learn more about: Error messages in Visual Basic

docs.microsoft.com

 

 

반응형
12345

+ Recent posts