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
- 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와 같은 값을 넣어서 활용하는 방법이다.
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 파일명을 넣으면 해당 파일을 연다. (로그 파일 열때 사용하면 좋음)
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!"
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)
하지만 중요한 작업의 경우, 또는 시간이 아주 오래걸리는 경우, 별것도아닌 사소한 에러로 종료가 되면 가슴이 아프다.
대표적으로 에러를 무시하고 진행하는 코드
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
' 다음 작업 계속...