麻辣家族討論版版's Archiver

x7776658 發表於 2021-11-11 21:25

請教VBA路徑變數設定

[i=s] 本帖最後由 x7776658 於 2021-11-11 21:26 編輯 [/i]

我是VBA初學者,需要請教各位VBA前輩們
指令碼如下,而我希望能夠將'D:\test\ i \[test.xlsx]工作表1'的i是變數,加入於迴圈之中
但執行結果不如預期,路徑無法變成變數

Sub 巨集1()

Dim i
For i = 1 To 2 Step 1
Range("a" & i & ":d" & i).Formula = "='D:\test\ i \[test.xlsx]工作表1'!A1:D1"
Range("a" & i & ":d" & i).Formula = Range("a" & i & ":d" & i).Value

Next

End Sub

samwang 發表於 2021-11-12 08:04

[b]回復 [url=http://forum.twbts.com/redirect.php?goto=findpost&pid=117666&ptid=23477]1#[/url] [i]x7776658[/i] [/b]


Sub test()
FPath = "D:\test\i\test.xlsx"
With Workbooks.Open(FPath)
    '您的主程式需求,因為您的寫法有問題
    '所以無法得知您實際的需求
    .Close
End With
End Sub

x7776658 發表於 2021-11-12 09:47

[b]回復 [url=http://forum.twbts.com/redirect.php?goto=findpost&pid=117668&ptid=23477]2#[/url] [i]samwang[/i] [/b]   

D:\test\   有兩個資料夾,分別是D:\test\1  及  D:\test\2,這兩個資料夾都有test.xlsx
[attach]34373[/attach]

我希望能把不同資料夾的excel資料(叫做test.xlsx)整合至一個excel ( 叫做total.xlsm),如下圖所示
[attach]34372[/attach]

謝謝

samwang 發表於 2021-11-12 12:10

[b]回復 [url=http://forum.twbts.com/redirect.php?goto=findpost&pid=117670&ptid=23477]3#[/url] [i]x7776658[/i] [/b]

可以提供附件,想要整合2個檔案的結果為什麼樣子,謝謝

x7776658 發表於 2021-11-12 12:30

[b]回復 [url=http://forum.twbts.com/redirect.php?goto=findpost&pid=117672&ptid=23477]4#[/url] [i]samwang[/i] [/b]
您好

D:\test\1\test.xlsx
[attach]34374[/attach]

D:\test\2\test.xlsx
[attach]34375[/attach]

整合至
D:\test\total.xlsm
[attach]34376[/attach]

謝謝

samwang 發表於 2021-11-12 13:07

[b]回復 [url=http://forum.twbts.com/redirect.php?goto=findpost&pid=117674&ptid=23477]5#[/url] [i]x7776658[/i] [/b]

請測試看看,謝謝

Sub test()
For i = 1 To 2
    FPath = "D:\test\" & i & "\test.xlsx"
    With Workbooks.Open(FPath)
         Arr = Range("a1:d1")
        .Close
    End With
    Range("a" & i).Resize(, 4) = Arr
Next
End Sub

x7776658 發表於 2021-11-12 13:14

[b]回復 [url=http://forum.twbts.com/redirect.php?goto=findpost&pid=117676&ptid=23477]6#[/url] [i]samwang[/i] [/b]

執行成功,謝謝大大無私分享

頁: [1]

麻辣家族討論版版為 麻辣學園 網站成員  由 昱得資訊工作室 © Since 1993 所提供