ซ่อมคอมพิวเตอร์นอกสถานที่ รามตำแหง บางกะปิ 083-792-5426

วันพุธที่ 18 กรกฎาคม พ.ศ. 2555

Microsoft Excel Tips and Tricks: การสร้าง Folder ใหม่โดยใช้ VBA

กรณีที่เราต้องส่งไฟล์ให้กับผู้ใช้งาน โดยกำหนดไว้ล่วงหน้าว่าจะต้องให้ผู้ใช้งาน Save File ไว้ใน Folder ที่กำหนดไว้ใน Code VBA เท่านั้น หากยังไม่มี Folder ดังกล่าวให้สร้าง Folder ขึ้นมาก่อนแล้วค่อย Save File
โดยสมมุติว่าให้ Save File ชื่อ Test.xls ไว้ที่ D:\Program\Master\File สามารถใช้ VBA ตามด้านล่างครับ
Option Explicit 
Function FolderExist(Path As String) As Boolean
On Error Resume Next
If Not Dir(Path, vbDirectory) = vbNullString Then
FolderExist = True
End If
On Error GoTo 0
End Function
Sub TestFolder()
If FolderExist("D:\Program\Master\File") Then
ChDir "D:\Program\Master\File"
ThisWorkbook.SaveAs ("Test.xls") 'Save file name as "Test"
Else
On Error Resume Next
MkDir "D:\Program\"
MkDir "D:\Program\Master"
MkDir "D:\Program\Master\File"
ChDir "D:\Program\Master\File"
ThisWorkbook.SaveAs ("Test.xls") 'Save file name as "Test"
End If
End Sub

การเรียกใช้งานจะเรียก TestFolder ซึ่งจาก Code ด้านบนเป็นการสร้าง Folder หลักขึ้นมาก่อนแล้วค่อยสร้าง Folder ย่อย จากนั้นค่อย Save File ใน Folder ย่อยนั้น

0 ความคิดเห็น:

แสดงความคิดเห็น

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design Downloaded from Free Blogger Templates Download | free website templates downloads | Vector Graphics | Web Design Resources Download.