首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用VBA粘贴在同一行但不同列上复制的数据

用VBA粘贴在同一行但不同列上复制的数据
EN

Stack Overflow用户
提问于 2017-08-10 09:23:30
回答 1查看 590关注 0票数 1

彻底的我以前问的问题,新的话题诞生了。现在,我有几个复制的单元格,我想将它们粘贴到初始文件中(例如宏所在的ThisWorkbook )。

我尝试的是将同一行保留在块运算符"FOR“中,将光标移回少数列并粘贴到所选内容中。但是出现了一个错误。当我使用统计的方式“范围(”“C10”),但每次程序必须有不同的单元格粘贴在那里。那么,我该如何应对呢?

提前谢谢你!

代码语言:javascript
运行
复制
Option Explicit

Sub FileFinder()
' Excel variables:
Dim wbResults, oWB As Workbook
Dim Sht As Worksheet
Dim RngS As Range
Dim sDir As String
Dim LastRow, i, Col As Long
'Optimizing CPU speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
' set the worksheet object
Col = 25
Set Sht = Worksheets("Accounts source data")
With Sht
    ' find last row with data in Column "Y" (Col = 25)
    LastRow = .Cells(.Rows.Count, 25).End(xlUp).Row
    For i = 3 To LastRow
        If .Cells(i, Col) = "In Scope" Then
            ' Set the range directly, no need to use `Select` and `Selection`
            Set RngS = .Cells(i, Col).Offset(, -22)
            ' Search, in same directory where the file is located, the file with that account (file comes with account number as name)
            sDir = Dir$(ThisWorkbook.Path & "\" & RngS.Value & ".xlsx", vbNormal)
            Set oWB = Workbooks.Open(ThisWorkbook.Path & "\" & sDir)
            oWB.Worksheets("Report").Range("B27:B30").Copy

            'My error appears here: Run-time Error 424: Object required
            'If I replace "Cells(i, Col).Offset(, -11)" from below with "Range("C10")" the code works perfectly. But this is not the desired result
            wbResults.Worksheets("Accounts source data").Cells(i, Col).Offset(, -11).PasteSpecial Paste:=xlPasteAll, Transpose:=True
            oWB.Close SaveChanges:=False

            ' clear objects
            Set RngS = Nothing
            Set oWB = Nothing
        End If

    Next i
End With
'End optimizing CPU speed
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-10 09:39:42

只是个简单的解决办法。就像这样:

ThisWorkbook.Worksheets("Accounts source data").Cells(i, Col).Offset(, -11).PasteSpecial Paste:=xlPasteAll, Transpose:=True

如果它有效,那么尝试将wbResults设置为ThisWorkbook,如注释中提到的那样。

您需要将wbResults设置为指定的工作簿,如注释中所示。Set wbResults = ThisWorkbook是一种可能的方法。此外,在VBA Dim a,b,c as Long中,仅将最后一个值设置为Long,其余两个设置为Variant

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45609547

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档