返回列表 上一主題 發帖

[發問] 請問如何更改VB的連結檔案路徑

[發問] 請問如何更改VB的連結檔案路徑

這個VBA功能是將多個TXT內容全部會集到同一個EXCEL中
但是這程式必須跟TXT在同一個目錄
我試著修改成把程式放在C:\指定匯集D:\中的TXT
可是都沒成功
請問要怎麼修改才OK??
謝謝


Sub 匯入文字檔()
Dim xFile, uFile, uHead As Range, Jm&, Km&, X, xT, xL
Range("A:A").Clear '清除舊匯入資料
'-----------------------------------------------------
Application.ScreenUpdating = False
Do
    If xChk = 0 Then
       xFile = Dir(ThisWorkbook.Path & "\*.txt")
       If xFile = "" Then MsgBox "※找不到 TXT 檔案! ", 0 + 16: Exit Sub
       xChk = 1
    Else
       xFile = Dir
       If xFile = "" Then Exit Do
    End If
    '----------------------------------------------
    uFile = ThisWorkbook.Path & "\" & xFile
    Set uHead = Range("A65536").End(xlUp)
    If uHead <> "" Then Set uHead = uHead(3, 1)
    With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & uFile, Destination:=uHead)
         .AdjustColumnWidth = False
         .TextFileColumnDataTypes = Array(1)
         .Refresh BackgroundQuery:=False
         .Delete
    End With
    uHead.Interior.ColorIndex = 6
    '每筆第一格加〔黃色〕底
NEXT_LINE:
Loop
'-------------------------------------------------------
Application.ScreenUpdating = True
MsgBox "∼∼匯入完成∼∼ "
End Sub


匯入文字檔.zip (8.72 KB)

回復 4# GBKEE


    謝謝大大的修正

TOP

回復 3# v60i
  1. With Application.FileDialog(msoFileDialogFolderPicker)
  2. If .Show = 0 Then Exit Sub   '改這裡
  3. fd = .SelectedItems(1)
  4. End With
複製代碼

TOP

回復 2# Hsieh


    大大 如果我點出了選擇資料夾畫面後 如果按取消 會出現
剪貼簿01.jpg
點選偵錯
fd = .SelectedItems(1)
會反黃耶

TOP

回復 1# v60i
用資料夾對話方塊結果取代ThisWorkbook.Path
  1. Sub 匯入文字檔()
  2. Dim xFile, uFile, uHead As Range, Jm&, Km&, X, xT, xL
  3. Range("A:A").Clear '清除舊匯入資料
  4. '-----------------------------------------------------
  5. With Application.FileDialog(msoFileDialogFolderPicker)
  6. .Show
  7. fd = .SelectedItems(1)
  8. End With

  9. Application.ScreenUpdating = False
  10. Do
  11.     If xChk = 0 Then
  12.        xFile = Dir(fd & "\*.txt")
  13.        If xFile = "" Then MsgBox "※找不到 TXT 檔案! ", 0 + 16: Exit Sub
  14.        xChk = 1
  15.     Else
  16.        xFile = Dir
  17.        If xFile = "" Then Exit Do
  18.     End If
  19.     '----------------------------------------------
  20.     uFile = fd & "\" & xFile
  21.     Set uHead = Range("A65536").End(xlUp)
  22.     If uHead <> "" Then Set uHead = uHead(3, 1)
  23.     With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & uFile, Destination:=uHead)
  24.          .AdjustColumnWidth = False
  25.          .TextFileColumnDataTypes = Array(1)
  26.          .Refresh BackgroundQuery:=False
  27.          .Delete
  28.     End With
  29.     uHead.Interior.ColorIndex = 6
  30.     '每筆第一格加〔黃色〕底
  31. NEXT_LINE:
  32. Loop
  33. '-------------------------------------------------------
  34. Application.ScreenUpdating = True
  35. MsgBox "∼∼匯入完成∼∼ "
  36. End Sub
複製代碼
學海無涯_不恥下問

TOP

        靜思自在 : 欣賞別人就是莊嚴自己。
返回列表 上一主題