2017年2月6日 星期一

VBA: 檔案處理

## 檔案處理
## 開啟檔案  
  Workbooks.Open Filename:= _
    "D:\20140325\test.xls"

## 關閉檔案  
Windows(szOriginalFileName).Activate
ActiveWindow.Close False

## 使用循序模式寫入檔案()
Open "MyFile.txt" For Output As #1
For inputData = 1 To 4
Print #1, inputData
Next inputData
Close #1


## 使用循序模式讀取檔案
EX1.
Open "MyFile.txt" For Input As #1
For retu = 1 To 4
Input #1, x
Cells(1, retu) = x
Next retu
Close #1

EX2.
' Open the file for Input.
Open "TEXTFILE.TXT" For Input As #1
' Read each line of the text file into a single string
' variable.
Do While Not EOF(1)
   Line Input #1, LineofText
   MsgBox LineofText
Loop
' Close the file.
Close #1



## 讀取特定目錄內的檔名
Private Sub readFileName()
    Dim szWorkPath As String   ' 目前工作檔案目錄
    Dim szFileName As String   ' 讀到的檔案名稱
    Dim szDirString As String  ' DIR 搜尋檔案的字串
    szWorkPath = ThisWorkbook.Path
    szDirString = szWorkPath & "\data\*.pdf"
    n = 0
    'Sheet3.Cells.Delete  '將之前的結果清除
    szFileName = Dir(szDirString, vbDirectory)
    szData = ""
    While szFileName <> ""
      n = n + 1
        szData = szData + "##" + szFileName
      szFileName = Dir() '讀取下一個檔案
    Wend
    MsgBox (n & szData)
End Sub

## 執行功能前的確認視窗
Dim szYesNo
szYesNo = MsgBox("確定執行發送功能 ?", vbYesNo, "發送視窗")
If szYesNo = vbYes Then
  MsgBox "Hello"
Else
  MsgBox "Naff Off"
End If

沒有留言:

張貼留言