-1

I have a macro that works manually and with Ctrl + I, but when I put a button, the macro doesn't work.

Sub Duplicar()
'Updateby Extendoffice 20160922
    Dim xRow As Long
    Dim VInSertNum As Variant
    xRow = 26
    Application.ScreenUpdating = False
    Do While (Cells(xRow, "A") <> "")
        VInSertNum = Cells(xRow, "K")
        If ((VInSertNum > 1) And IsNumeric(VInSertNum)) Then
           Range(Cells(xRow, "A"), Cells(xRow, "K")).Copy
           Range(Cells(xRow + 1, "A"), Cells(xRow + VInSertNum - 1, "K")).Select
           Selection.Insert Shift:=xlDown
           xRow = xRow + VInSertNum - 1
        End If
        xRow = xRow + 1
    Loop
    Application.ScreenUpdating = False
End Sub
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

1 Answers1

2

You need to reference in which worksheet your Cells() and Range() are. Otherwise, Excel cannot know that and starts guessing which worksheet you mean (and it fails guessing).

So set a variable to a worksheet

Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")

and use it to reference all Cells(), Range(), Rows(), etc. For example, like

Do While ws.Cells(xRow, "A").Value <> ""

Do this for all of them.

Also see How to avoid using Select in Excel VBA. Instead of using .Select, always use the range directly. For example, instead of:

Range("A1").Select
Selection.Insert

do directly

Range("A1").Insert

Finally your last line should be Application.ScreenUpdating = True, not False.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73