简体   繁体   English

VBA从一个Excel工作表复制到另一个Excel工作表?

[英]VBA copying from one excel sheet to another excel sheet?

I am basically copying one excel file sheet to a particular sheet of the excel file(same file as where I am writing the macro).I get the error- Run time error '9': Subscript out of range on the line WbTarget.Sheets("FPP").Range("A1:E654").PasteSpecial 我基本上是将一个excel文件工作表复制到excel文件的特定工作表中(与编写宏的位置相同)。我得到了错误-运行时错误'9':下标超出了WbTarget.Sheets行(“ FPP”)。Range(“ A1:E654”)。PasteSpecial
I am not that good in VBA-any help please? 我的VBA不够好-请帮忙吗?

Sub XMLR()
Dim output As String
output = CreateObject("WScript.Shell").Exec("R CMD BATCH  filepath.R").StdOut.ReadAll
Call XML
End Sub

Sub XML()
Dim wbTarget            
Dim wbThis              
Dim strName             
Set wbThis = Workbooks.Open("file.xlsx")
wbThis.Activate
strName = ActiveSheet.Name
Set wbTarget = ActiveWorkbook
Application.CutCopyMode = False
wbThis.Sheets("Sheet1").Range("A1:E654").Copy
wbTarget.Sheets("FPP").Range("A1:E654").PasteSpecial
Application.CutCopyMode = False
wbTarget.Save
wbTarget.Close
wbThis.Close
Set wbTarget = Nothing
Set wbThis = Nothing
End Sub

Slightly confusing, but try this: 有点混乱,但是请尝试以下操作:

Sub XML()

Dim wbTarget As Workbook
Dim wbThis As Workbook
Dim strName As String

Set wbThis = Workbooks.Open("file.xlsx")

ThisWorkbook.Sheets("FPP").Range("A1:E654").Value = wbThis.Sheets("Sheet1").Range("A1:E654").Value

wbTarget.Save
wbTarget.Close
wbThis.Close

Set wbTarget = Nothing
Set wbThis = Nothing

End Sub

The issue here is that both WbTarget and WbThis refer to the same workbook. 这里的问题是WbTarget和WbThis都引用同一工作簿。

You should change you declaration: 您应该更改声明:

Set wbTarget = ActiveWorkbook

to

Set wbTarget = Application.ThisWorkbook

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM