Как запустить код VBA, который копирует диапазон ячеек из активного листа и вставляет его в новую рабочую книгу (только значения и форматирование, а не формулы)? - PullRequest
0 голосов
/ 16 апреля 2020

Я пытаюсь запустить макрос, в котором я нажимаю кнопку запуска, и активный лист обновляется путем извлечения данных из строки. Эти данные затем сохраняются в новой рабочей книге (только значения и форматирование). Я хочу, чтобы эта операция продолжалась до i-й строки, чтобы у меня были отдельные рабочие книги в конце выполнения. Для этого я сделал два диапазона имен: rng_counter, который хранит номер начальной строки, и rng_forms_count, который хранит номер конечной строки, и в моем l oop я увеличиваю этот rng_counter, пока он не станет равным rng_forms_count. Однако проблема, с которой я сталкиваюсь, заключается в том, что после успешного прохождения первой итерации код выдает ошибку «Ошибка диапазона метода object_global». Я также заметил, что каждый раз, когда я запускаю кнопку «Пуск», Excel автоматически устанавливает вычисление формулы как ручное, и rng_counter не обновляется. Я использую следующий код:

For i = Range("rng_counter").Value To Range("rng_forms_count").Value

    Range("rng_counter").Value = i
    Calculate
        If Worksheets("Reporting Form Template").Range("C9").RowHeight > 165.6 Then '***This part is to mention an issue that would come up in the report made
            MsgBox "There is an issue with the AEs of Respondent ID - " & Range("rng_ae_number") & ", the AE form would extend beyond the intended height of the form,(write down this Respondant ID and do it seperately, its report would not be generated) consider reducing the font size of AEDump to make sure the report comes in 2 pages instead of 3!"
        Else 
                Sheets("Reporting Form Template").Select
    Range("A1:Q14").Select
    Selection.Copy
    Workbooks.Add
    Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone _
        , SkipBlanks:=False, Transpose:=False
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

     End If
        Next i

Спасибо всем заранее!

Ответы [ 2 ]

0 голосов
/ 16 апреля 2020

ваша проблема заключается в

1) отсутствии полностью квалифицированных диапазонов вплоть до их рабочего листа и родителей рабочей книги

2) Workbooks.Add, что сделает вновь созданную рабочую книгу "активной "один и его первый рабочий лист" Активный "тоже

Итак, после того, как вы получили ваш комментарий, вы запускаете подпрограмму, активированную кнопкой ActiveX, и что Range("rng_counter") и Range("rng_forms_count") находятся в на том же листе, в то время как все остальные диапазоны отсутствуют, вы можете попробовать это (пояснение в комментариях):

Private Sub CommandButton1_Click()
    With Me ' reference the sheet with button

        Application.Calculation = xlCalculationAutomatic

        Dim i As Long
        For i = .Range("rng_counter").Value To .Range("rng_forms_count").Value

            If Worksheets("Reporting Form Template").Range("C9").RowHeight > 165.6 Then '***This part is to mention an issue that would come up in the report made
                MsgBox "There is an issue with the AEs of Respondent ID - " & .Range("rng_ae_number") & ", the AE form would extend beyond the intended height of the form,(write down this Respondant ID and do it seperately, its report would not be generated) consider reducing the font size of AEDump to make sure the report comes in 2 pages instead of 3!"
            Else

                .Range("rng_counter").Value = i 'update "rng_counter" named range in referenced sheet
                Calculate

                .Parent.Worksheets("Reporting Form Template").Range("A1:Q14").Copy ' copy a fully qualified range up to its workbook parent

                With Workbooks.Add ' open and reference a new workbook. this will become tha "active" one
                    With .Worksheets(1).Range("A1") ' reference referenced workbook first worksheet (which has become the "active" one) range A1
                        .PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
                        .PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
                    End With
                End With

            End If
        Next i
    End With
End Sub
0 голосов
/ 16 апреля 2020
Dim wBook As Workbook
For i = Range("rng_counter").Value To Range("rng_forms_count").Value

    Calculate
    If ThisWorkbook.Sheets("Reporting Form Template").Range("C9").RowHeight > 165.6 Then '***This part is to mention an issue that would come up in the report made
        MsgBox "There is an issue with the AEs of Respondent ID - " & i & ", the AE form would extend beyond the intended height of the form,(write down this Respondant ID and do it seperately, its report would not be generated) consider reducing the font size of AEDump to make sure the report comes in 2 pages instead of 3!"
    Else 
        ThisWorkbook.Sheets("Reporting Form Template").Range("A1:Q14").Copy
        Set wBook = Workbooks.Add()
        With wBook.Sheets(1).Range("A1:Q14")
            .PasteSpecial Paste:=xlPasteValuesAndNumberFormats      
            .PasteSpecial Paste:=xlPasteFormats
            .PasteSpecial Paste:=xlPasteColumnWidths
        End With
    End If
Next i
Application.Calculation = xlAutomatic
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...