2017-08-25 130 views
1

我是VBA新手。我正在嘗試將一個工作簿中的列複製到另一個工作簿中。下面是我試圖使用的子,但得到「運行時錯誤9 - 下標超出範圍」的錯誤。有什麼建議麼?VBA:複製範圍。運行時錯誤9 - 下標超出範圍

Sub copydata(wbSource As String, wsSource As String, rangeSource As String, wbDest As String, wsDest As String, rangeDest As String) 
    Workbooks(wbSource).Worksheets(wsSource).Range(rangeSource).copy Destination:=Workbooks(wbDest).Worksheets(wsDest).Range(rangeDest) 
End Sub 

Sub result() 
    ' I also tried to set wsSource and wsDest to 1 but still doesn't work 
    Call copydata("es.csv", "es", "A:B", "Workbook1.xlsm", "result", "A:B") 
End Sub 

感謝

編輯: 他們是在同一個目錄。我該模塊中創建Workbook1.xlsm

enter image description here

+0

一個工作簿/工作表不存在。 –

+0

請檢查編輯 –

+0

這是不夠的,他們是'在同一個文件夾'。它們必須位於同一工作空間中,才能在不使用完全限定的外部引用的情況下引用另一個工作簿(例如.csv)。 – Jeeped

回答

1

他們必須同時打開,當你複製,它們都在同一個文件夾並不重要。

你應該打開它們,然後你可以複製數據。

檢查兩片材名稱(ES爲es.csv,導致對其Workbook1.xslm)

Sub copydata(wbSource As String, wsSource As String, rangeSource As String, 
wbDest As String, wsDest As String, rangeDest As String) 
    Workbooks(wbSource).Worksheets(wsSource).Range(rangeSource).Copy 
Destination:=Workbooks(wbDest).Worksheets(wsDest).Range(rangeDest) 
End Sub 

Sub result() 
    ' I also tried to set wsSource and wsDest to 1 but still doesn't work 
    If Not IsWorkbookOpen("es.csv") Then OpenWorkbook ("es.csv") 
    End If 
    Call copydata("es.csv", "es", "A:B", "Workbook1.xlsm", "result", "A:B") 
End Sub 

Sub OpenWorkbook(fileName As String) 
    Dim activePath As String 
    activePath = Application.ActiveWorkbook.Path 
    Application.Workbooks.Open (activePath & Application.PathSeparator & 
fileName) 
End Sub 

Private Function IsWorkbookOpen(wbName As String) As Boolean 
    Dim wb As Workbook 

    On Error GoTo Handler 
    Set wb = Workbooks(wbName) 
    If wb.Name = wbName Then 
     Set wb = Nothing 
     IsWorkbookOpen = True 
    Else 
Handler: 
     IsWorkbookOpen = False 
    End If 
End Function 
+0

哦,是的。我不知道我需要先打開所有文件。無論如何,有沒有什麼功能可以在不打開所有文件的情況下進行復制? –

+0

如果它是一個csv文件,您可以使用ActiveWorkbook.Queries方法https://msdn.microsoft.com/en-us/vba/excel-vba/articles/queries-add-method-excel – exSnake

+0

確定。非常感謝。 –