我是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中创建模块
答案 0 :(得分:1)
复制时它们必须都是打开的,它们都在同一个文件夹中并不重要。
您应该打开它们,然后才能复制数据。
检查两个工作表名称(es.csv的es,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