作者pomelolin (勇氣、智慧、善良)
看板Office
標題[問題] VBA workbooks不重新開啟檔案
時間Fri Aug 10 23:59:48 2018
(若是和其他不同軟體互動之問題 請記得一併填寫)
軟體:excel
版本:2013
這是別人寫的VBA, 現在想自己修改, 是從A檔案各個sheet不同位置
copy到B檔案各sheet不同位置, 有個表格是對照表
原本寫的檔案都得重新開啟A檔案和B檔案, 但其實原本都會同時開著,
不想每次run程式都要重開檔案, 上網研究好久, 依然不得其門而入
把Open刪掉, 程式就出現錯誤了@@
麻煩版上各位先進幫忙~~
Dim scWB As Workbook, tgWB As Workbook
Dim scWS As Worksheet, tgWS As Worksheet, ws As Worksheet
Dim row As Integer
Set ws = ThisWorkbook.Worksheets("XXX")
Set scWB = Application.Workbooks.Open(ws.Cells(1, 3).Value)
Set tgWB = Application.Workbooks.Open(ws.Cells(2, 3).Value)
For row = 4 To 63
If (Len(ws.Cells(row, 2).Value) > 0) Then
ws.Cells(row, 6).Value = "GO"
Set scWS = scWB.Worksheets(ws.Cells(row, 2).Value)
Set tgWS = tgWB.Worksheets(ws.Cells(row, 4).Value)
scWS.Range(ws.Cells(row, 3).Value).Copy
tgWS.Range(ws.Cells(row, 5).Value).PasteSpecial xlPasteValues
ws.Cells(row, 6).Value = "OK"
'scWB.Close
'tgWB.Close
End If
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 219.70.232.113
※ 文章網址: https://webptt.com/m.aspx?n=bbs/Office/M.1533916790.A.EF3.html
1F:→ soyoso: 1.迴圈於workbooks的集合,判斷workbook.name是否符合原文 08/11 00:34
2F:→ soyoso: 內的ws.cells(1,3)或cells(2,3),符合就set 變數= 08/11 00:35
3F:→ soyoso: workbooks(完整檔名) 08/11 00:37
4F:→ soyoso: 並設個變數(可數字、文字或布林),用於當迴圈執行完時都沒 08/11 00:40
5F:→ soyoso: 有符合的條件,再判斷該變數,來判斷是否要以workbooks. 08/11 00:41
6F:→ soyoso: open 08/11 00:41
7F:→ soyoso: 2.直接set 變數=workbooks(完整檔名),沒開啟變數會是 08/11 00:43
8F:→ soyoso: nothing,就可以判斷當變數is nothing時workbooks.open 08/11 00:44
9F:→ soyoso: 但因set 變數一個無開啟的檔案,會出現陣列索引超出範圍的 08/11 00:45
10F:→ soyoso: 錯誤訊息,因此上方要加上on error resume next 08/11 00:46