返回列表 上一主題 發帖

[發問] 請問如何自動匯入外部資料

回復 1# sandra_wang
試試看
  1. Sub 匯入文字檔_Ex()
  2.     Dim MyPath As String, TheDate As String, TheFile As String, ShName As String, Mystr As String, Rng As Range, E As Variant
  3.     MyPath = ThisWorkbook.Path & "\"                    '文字檔所在的目錄
  4.     TheDate = Format(Date - 1, "mm/dd")                 '取的日期
  5.     On Error Resume Next                                'DIR 找不到檔案會產生錯誤
  6.     TheFile = Dir(MyPath & "*MB-*" & TheDate & "*.log") '尋找檔案
  7.     If Err.Number > 0 Then MsgBox "找不到  " & TheDate & "  檔案": Exit Sub
  8.     Do While TheFile <> ""
  9.         On Error GoTo ShAdd                             '工作表中沒有 ShName會產生錯誤
  10.         ShName = Mid(TheFile, InStr(TheFile, "MB-"), InStr(TheFile, "_") - InStr(TheFile, "MB-"))
  11.         Set Rng = Sheets(ShName).Cells(Rows.Count, "A").End(xlUp)
  12.         If Rng <> "" Then Set Rng = Rng.Offset(1)
  13.         Open MyPath & TheFile For Input As #1        '開啟文字檔
  14.             Do While Not EOF(1)                      '不是檔案底部時 執行迴圈
  15.                 Input #1, Mystr                      '從已開啟的循序讀取資料,並將資料指定給變數。->mystr
  16.                 For Each E In Split(Mystr, Chr(10))
  17.                     Rng = E
  18.                     Set Rng = Rng.Offset(1)
  19.                 Next
  20.             Loop
  21.         Close #1                                 '關閉文字檔
  22.         TheFile = Dir
  23.     Loop
  24.     Exit Sub
  25. ShAdd:
  26.     ThisWorkbook.Sheets.Add.Name = ShName
  27.     Err.Clear
  28.     Resume
  29. End Sub
複製代碼

TOP

回復 3# jackie-ap
謝謝指正

TOP

回復 5# sandra_wang
   C:\Documents and Settings\97051909\桌面\SEL\
你有加上嗎?

TOP

        靜思自在 : 自己害自己,莫過於亂發脾氣。
返回列表 上一主題