VBA - Копировать-Вставить в другую книгу - PullRequest
0 голосов
/ 30 мая 2019

Я пытаюсь скопировать определенные ячейки из одной рабочей книги в другую в конце таблицы. Я предполагаю, что проблема заключается в частом использовании ActiveWorkbook. Я получаю сообщение об ошибке «Объект не поддерживает это свойство или метод», и кажется, что макрос копирует ячейки из CurrentBook, а не загрузчика.

Как я могу исправить свой код?


Dim uploadfile As Variant
Dim uploader As Workbook
Dim CurrentBook As Workbook
Dim lastRow As Integer

Set CurrentBook = ActiveWorkbook

uploadfile = Application.GetOpenFilename()
    If uploadfile = "False" Then
        Exit Sub
    End If
Workbooks.Open uploadfile

Set uploader = ActiveWorkbook

With uploader
    Application.CutCopyMode = False
    Range("A1:J100").Copy
End With


CurrentBook.Activate
lastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
Range("A" & lastRow & ":J" & lastRow + 100).Select
Selection.Paste

uploader.Close

End Sub

Ответы [ 3 ]

0 голосов
/ 30 мая 2019

В VBA вы не должны использовать Ative.

Поэтому замените все Active, и вам придется использовать PasteSpecial, это лучше, чем Paste

Sub test()

Dim uploadfile As Variant
Dim uploader As Workbook
Dim CurrentBook As Workbook
Dim lastRow As Integer

Set CurrentBook = ThisWorkbook

uploadfile = Application.GetOpenFilename()
    If uploadfile = "False" Then
        Exit Sub
    End If
Set uploader = Workbooks.Open(uploadfile)

Application.CutCopyMode = False
uploader.Worksheets(1).Range("A1:J100").Copy

lastRow = CurrentBook.Worksheets(1).Cells(CurrentBook.Worksheets(1).Rows.Count, "A").End(xlUp).Row + 1
Range("A" & lastRow & ":J" & (lastRow + 100)).PasteSpecial xlPasteValues

uploader.Close

End Sub

Этот код работает для меня,

Добро пожаловать:)

0 голосов
/ 30 мая 2019

Ниже вы можете найти пример кода для копирования из одной рабочей книги в другую:

Option Explicit

Sub test()

    Dim wbSource As Workbook, wbDestination As Workbook

    'Set both workbooks by name to avoid conflicts
    Set wbSource = Workbooks("Book1")
    Set wbDestination = Workbooks("Book2")

    'Copy paste only values
    wbSource.Worksheets("Sheet1").Range("A1").Copy
    wbDestination.Worksheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteValues

End Sub
0 голосов
/ 30 мая 2019

Здесь, и только потому, что мне скучно на работе, тысячи таких сообщений:

Option Explicit
Sub CopyPaste()

    Dim uploadfile As String 'not Variant, the filename will be a string
    Dim wbCopy As Workbook 'Better than uploader As Workbook you need to declare variables easy to read
    Dim wbPaste As Workbook 'same as above
    Dim LastRow As Lon 'integer doesn't work (it will be a long delimited to integer) either Byte(0-255) or Long

    Set wbPaste = ThisWorkbook 'the workbook containing the code

    uploadfile = Application.GetOpenFilename()
    If uploadfile = "False" Then
        Exit Sub
    End If

    Set wbCopy = Workbooks.Open(uploadfile) 'declare your paste workbook like this

    ' Set uploader = ActiveWorkbook this way of referencing a workbook might give you errors, use the above

    With wbCopy.Sheets("MySheetName") 'reference always the worksheets, change MySheetName for the actual sheet name
        'Application.CutCopyMode = False this is useless here it's emptying the clipboard but below you copy something new
        .Range("A1:J100").Copy 'you missed the . on the beginning (when using With you need to use the dot to reference the with)
    End With

    With wbPaste.Sheets("MySheetName") 'reference always the worksheets, change MySheetName for the actual sheet name
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
        .Range("A" & LastRow).PasteSpecial xlPasteValues 'when you copy/paste you just need to find the first cell on the paste range, Excel will paste the whole range
    End With

    Application.CutCopyMode = False 'now you can use this to avoid warning message on closing the copy workbook
    wbCopy.Close Savechanges:=False

End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...