[英]Copy data from another workbook to an active cell
我需要更改我的代码,以便从另一个文件复制的选择粘贴到打开的工作簿中的活动单元格:
Sub Get_Data_From_File()
`Dim FiletoOpen As Variant
Dim OpenBook As Workbook
Application.ScreenUpdating = False
FiletoOpen = Application.GetOpenFilename(Title:="Browse for your file & Import Range", FileFilter:="Excel Files(*.xlsx),*xlsx*")
If FiletoOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FiletoOpen)
OpenBook.Sheets(1).Range("D1:D100").Copy
ThisWorkbook.Worksheets("Sheet1").ActiveCell.PasteSpecial xlPasteValues
OpenBook.Close False
End If
Application.ScreenUpdating = True
End Sub
我试图改变这一行: ThisWorkbook.Worksheets("Sheet1").ActiveCell.PasteSpecial xlPasteValues
到ActiveCell.PasteSpecial xlPasteValues
另外,我尝试定义一个范围,如本例所示: ThisWorkbook.Worksheets("Sheet1").Range("J4").PasteSpecial xlPasteValues
这有效。 但是,我不想复制到该范围,而是复制到我打开的工作簿中的活动选定单元格。
有什么建议吗?
ActiveCell
是应用程序的属性,而不是工作表,这就是为什么您无法按照最初编写的方式访问它的原因。 我正在试验您的代码,看起来当打开工作表时, ActiveCell
成为打开工作表的A1
。
那么像这样的东西怎么样:
' ++ make a note of current active cell before opening file
Dim r As Range
Set r = ActiveCell
FiletoOpen = Application.GetOpenFilename(Title:="Browse for your file & Import Range", FileFilter:="Excel Files(*.xlsx),*xlsx*")
...
'-- ThisWorkbook.Worksheets("Sheet1").ActiveCell.PasteSpecial xlPasteValues
'++ Copy to saved range
r.PasteSpecial xlPasteValues
完成子:
Option Explicit
Sub Get_Data_From_File()
Dim FiletoOpen As Variant
Dim OpenBook As Workbook
Application.ScreenUpdating = False
' ++ make a note of current active cell before opening file
Dim r As Range
Set r = ActiveCell
FiletoOpen = Application.GetOpenFilename(Title:="Browse for your file & Import Range", FileFilter:="Excel Files(*.xlsx),*xlsx*")
If FiletoOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FiletoOpen)
OpenBook.Sheets(1).Range("D1:D100").Copy
'-- ThisWorkbook.Worksheets("Sheet1").ActiveCell.PasteSpecial xlPasteValues
'++ Copy to saved range
r.PasteSpecial xlPasteValues
OpenBook.Close False
End If
Application.ScreenUpdating = True
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.