2017-08-10 15 views
1

前回の質問は徹底して、新しいトピックが生まれました。 ここで、コピーしたセルをコピーして、最初のファイルに移したいと思っています(マクロがあるThisWorkbookなど)。VBAを使用して同じ行で異なる列にコピーしたデータを貼り付けます

私が試みたのは、ブロック演算子 "FOR"と同じ行を保持し、カーソルを数行戻してそこに貼り付けることでした。しかし、エラーが発生しました。私がstatitの方法で "Range(" C10 ")"を使うときは、プログラムはそこに貼り付けるために異なるセルを持たなければなりません。では、どうすればそれに対処できますか?

ありがとうございます!

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 
+1

「Dim wbResults、oWB As Workbook」は「wbResults」が「Variant」であるため、特に「Dim wbResults As Workbook」を使用する必要があります。また、 'Set wbResults = ThisWorkbook'も決してありません。 –

答えて

0

ちょっとした修正です。このようにしてみてください。

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

それが動作する場合は、コメントで述べたように、その後、ThisWorkbookwbResultsを設定してみてください。


wbResultsを指定のブックに設定する必要があります(コメント内に記載されています)。 Set wbResults = ThisWorkbookが可能です。さらにVBADim a,b,c as Longには、最後の値がLongに設定され、残りの2つはVariantに設定されます。

関連する問題