无法复制其他工作簿中的选择

时间:2018-11-13 13:58:42

标签: excel vba copy selection paste

我一直试图从同一Excel实例中的另一个工作簿中复制数据,但没有成功。 我需要复制在另一个打开的工作簿上所做的选择,并将其粘贴到活动工作簿上。原来,当我运行VBA代码时,选择副本丢失了(行进的蚂蚁消失了)。

我已经尝试过下面的代码及其变体,但是它永远无法正常工作。

def parse_word(self, response):

     # look for all tags on this site
     tagscount = response.xpath('someXpath').extract()

     # check if there is a nextPage
     nextPage = response.css('somecssSelector').extract()
     lastPage = response.css('somecssSelector').extract()

     # Open every tagsite and crawl it if all tags are gained
     if not nextPage or lastPage:

         for tag in tagscount:

             # call parse method for article crawling
             data = scrapy.Request(url=tag, callback=self.parse_subpage)
             yield data

     # If there is a nextPage with tags request with this method recursively
     else:

         # a little bit of formatting for linktype
         nextPageStr = str(nextPage)
         cutNextPageStr = nextPageStr.replace("[","")
         cutNextPageStr = cutNextPageStr.replace("]", "")
         cutNextPageStr = cutNextPageStr.replace("'", "")
         link = urljoin(response.url, cutNextPageStr)

         # Call this method again --> here i want to set a parameter tagscount or something like this
         data = scrapy.Request(url=link, callback=self.parse_word)
         yield data

谢谢!

1 个答案:

答案 0 :(得分:1)

正如人们在评论中提到的那样,您需要删除On Error Resume Next,因为它可以防止出现错误消息。

您也不能使用Workbook.Worksheet.Selection,这个平原不存在。

因此,假设您在目标工作簿中有该宏,则您的函数可以(但不应!)看起来像这样:

Private Sub PasteCorrection()

    Selection.Copy
    ThisWorkbook.Worksheets(1).Range("C7").Select
    ActiveSheet.Paste

End Sub

不,它看起来不应该那样,因为正如另一位评论者所说,您应尽可能避免选择。下面的功能将实现相同的功能,但速度更快,而且不会碰到剪贴板。

Private Sub PasteCorrection()

    ThisWorkbook.Worksheets(1).Range("C7").Value = Selection.Value

End Sub

更好的是,如果您知道范围是相同的,则可以使用以下内容:

Private Sub PasteCorrection()

    ThisWorkbook.Worksheets(1).Range("C7").Value = Workbooks(2).Worksheets(1).range("C7").Value

End Sub

您当然应该修改“ C7”以满足您的特定需求。


更新

如果宏位于原始工作簿的VBA内,则代码应不同。假设您知道目标工作簿的文件名。

Private Sub PasteCorrection()

    Selection.Copy
    Workbooks("FileNameWithoutExtension").Worksheets(1).Paste

End Sub

如果您不知道目标BUT的名称,则只打开了两个工作簿:

Private Sub PasteCorrection()

    Selection.Copy
    If ThisWorkbook Is Workbooks(1) Then
        Workbooks(2).Worksheets(1).Paste
    else
        Workbooks(1).Worksheets(1).Paste
    End If

End Sub