Page 1 of 1

Loop Path Name When Open File

Posted: Thu Mar 25, 2021 10:14 am
by parakorn
เรียนอาจารย์และเพื่อนสมาชิกครับ

รบกวนสอบถามถ้าหากต้องการกวาดชื่อไฟล์ ไปไว้ในไฟล์ที่เราเตรียมไว้ ต้องปรับโค้ดประมาณไหนให้ใช้งานได้ครับ

Code: Select all

Option Explicit

Sub LoopThroughFiles()
Dim a As Integer
Dim StrFile As String
Dim mysource As String

mysource = Dir("\\'##.#.###.###'\C:\Users\Desktop\[TestLoopNameFile.xlsm]") 
'File ที่เราจะนำ Path ไปวางตั้ง แต่ A1 ลงไป ถ้าเป็นไปได้อยากปรับโค้ดให้สามารถเข้าไปวางโดยไม่ต้องเปิดไฟล์ด้วยครับ

StrFile = Dir("c:\TestLoop\*") ' โฟล์เดอรที่เราจะไล่เก็บ Path

Do While Len(StrFile) > 0
    'Debug.Print StrFile
    'StrFile = Dir
    mysource.Sheet1!Range("A" & a) = StrFile
    a = a + 1
Loop

End Sub

Re: Loop Path Name When Open File

Posted: Thu Mar 25, 2021 12:04 pm
by snasui
:D ตัวอย่างการปรับ Code ครับ

ต้องนำ Code ไปไว้ใน Event ที่ชื่อว่า Workbook_Open ครับ

Code: Select all

Sub LoopThroughFiles()
    Dim a As Integer
    Dim StrFile As String
    Dim mysource As String
    Dim wb As Workbook
    mysource = "\\##.#.###.###\C:\Users\Desktop\TestLoopNameFile.xlsm"
    Set wb = Workbooks.Open(Filename:=mysource, UpdateLinks:=False, ReadOnly:=True)
    
    StrFile = Dir("c:\TestLoop\*") '
    Do While Len(StrFile) > 0
        a = a + 1
        wb.Worksheets("Sheet1").Range("A" & a) = StrFile
        StrFile = Dir()
    Loop
End Sub

Re: Loop Path Name When Open File

Posted: Thu Mar 25, 2021 7:05 pm
by parakorn
snasui wrote: Thu Mar 25, 2021 12:04 pm :D ตัวอย่างการปรับ Code ครับ

ต้องนำ Code ไปไว้ใน Event ที่ชื่อว่า Workbook_Open ครับ

Code: Select all

Sub LoopThroughFiles()
    Dim a As Integer
    Dim StrFile As String
    Dim mysource As String
    Dim wb As Workbook
    mysource = "\\##.#.###.###\C:\Users\Desktop\TestLoopNameFile.xlsm"
    Set wb = Workbooks.Open(Filename:=mysource, UpdateLinks:=False, ReadOnly:=True)
    
    StrFile = Dir("c:\TestLoop\*") '
    Do While Len(StrFile) > 0
        a = a + 1
        wb.Worksheets("Sheet1").Range("A" & a) = StrFile
        StrFile = Dir()
    Loop
End Sub
ขอบคุณครับผม สวยงามครับอาจารย์ :cp: :cp: