Run-time error '-2147417848 (80010108)': Method 'Insert' of object 'Range' failed - excel

I am attempting to track changes in our financial models. The aim is to identify who is back solving.
I have written code that executes until I switch from one sheet to only one other specific sheet.
Sub tracker()
Dim Cell As Range
For Each Cell In Sheets("Input check IC").Range("AI2:AI128")
If Cell.Value <> 0 Then
With Sheets("Copy IC")
Sheets("Change tracker").Range("C10000").End(xlUp).Offset(1, 0).Resize(, 33).Value = .Range(.Cells(Cell.Row, "A"), .Cells(Cell.Row, "AG")).Value
End With
End If
Next
For Each Cell In Sheets("Input check IC").Range("AI2:AI128")
If Cell.Value <> 0 Then
With Sheets("Live IC")
Sheets("Change tracker").Range("C10000").End(xlUp).Offset(1, 0).Resize(, 33).Value = .Range(.Cells(Cell.Row, "A"), .Cells(Cell.Row, "AG")).Value
End With
End If
Next
'Live IC
Sheets("Live IC").Range("B2:AG128").Copy
Sheets("Copy IC").Range("B2").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
End Sub
I have a duplicate code for "RC" where: IC = investment case ; RC = reference case. RC is called from tracker 2 in a separate module.
The code executes perfectly when I go to any sheet in the workbook, other than RC (from IC)/ IC (from RC). I might add the code is called when the sheet is deactivated. I feel the code is stuck in a loop when I deactivate/active IC/RC in succession.
It runs until the following error
Run-time error '-2147417848 (80010108)': Method 'Insert' of object 'Range' failed'

Copy Ranges
Assuming that all worksheets are in the workbook containing this code.
Note that arrays will handle this more efficiently. Consider it as a lesson in ranges.
Not tested.
The Code
Option Explicit
Sub tracker()
Dim wb As Workbook: Set wb = ThisWorkbook
Dim cws As Worksheet: Set cws = wb.Worksheets("Input check IC")
Dim dst As Worksheet: Set dst = wb.Worksheets("Change tracker")
Dim sws As Variant: ReDim sws(1 To 2)
Set sws(1) = wb.Worksheets("Copy IC")
Set sws(2) = wb.Worksheets("Live IC")
Dim crg As Range: Set crg = cws.Range("AI2:AI128")
Dim drg As Range
Set drg = dst.Cells(dst.Rows.Count, "C").End(xlUp) _
.Resize(, 33).Offset(1, 0)
Dim srg As Range
Dim n As Long
Dim i As Long
For n = 1 To 2
Set srg = sws(n).Range("A2").Resize(crg.Rows.Count, 33)
For i = 1 To crg.Cells.Count
If crg.Cells(i).Value <> 0 Then
drg.Value = srg.Rows(i).Value
Set drg = drg.Offset(1)
End If
Next i
Next n
'Live IC
sws(1).Range("B2:AG128").Value = sws(2).Range("B2:AG128").Value
End Sub

Related

VBA Help to find a column based on header value and cupy it to an other worksheet

I have this basic code to find the needed coumns in a table and copy them to an other worksheet. My problem is that every time I want to modify it to not to copy&paste the header it returns error. This is my code:
Sub CopyColumns()
Dim wsSource, wsResult As Worksheet
Dim Name, UniqueId, OperatingStatus As Long
Set wsSource = ThisWorkbook.Sheets("Source")
Set wsResult = ThisWorkbook.Sheets("Result")
Name = wsSource.Rows(1).Find("#BASEDATA#name").Column
UniqueId = wsSource.Rows(1).Find("#BASEDATA#uniqueId").Column
OperatingStatus = wsSource.Rows(1).Find("#BASEDATA#operatingStatus").Column
If Name <> 0 Then
wsSource.Columns(Name).Copy Destination:=wsResult.Columns(3)
End If
If UniqueId <> 0 Then
wsSource.Columns(UniqueId).Copy Destination:=wsResult.Columns(4)
End If
If OperatingStatus <> 0 Then
wsSource.Columns(OperatingStatus).Copy Destination:=wsResult.Columns(1)
End If
End Sub
Any ideas how to solve it?
I tried is to copy like this using offset:
If targetColName <> 0 Then
wsSource.Columns(targetColName).Offset(1, 0).Resize(wsSource.Rows.Count - 1).Copy _ Destination:=wsResult.Columns(3).Offset(1, 0)
It gives Error: Application-defined ot object-defined error
Thanks!
offset and resize not working
You can break out the "copy column if found" into a separate sub:
Sub CopyColumns()
Dim wsSource, wsResult As Worksheet
Set wsSource = ThisWorkbook.Sheets("Source")
Set wsResult = ThisWorkbook.Sheets("Result")
CopyIfExists wsSource.Rows(1), "#BASEDATA#name", wsResult, 3
CopyIfExists wsSource.Rows(1), "#BASEDATA#uniqueId", wsResult, 4
CopyIfExists wsSource.Rows(1), "#BASEDATA#operatingStatus", wsResult, 1
End Sub
'Look for `colName` in `headerRow`, and if found copy the whole
' column to column `destColNum` on `destSheet`
Sub CopyIfExists(headerRow As Range, colName As String, destSheet As Worksheet, destColNum As Long)
Dim f As Range
Set f = headerRow.Find(what:=colName, lookat:=xlWhole) 'or xlPart
If Not f Is Nothing Then
f.EntireColumn.Copy destSheet.Cells(1, destColNum)
End If
End Sub
When using find, you should check you got a match before trying to do anything with the matched cell.
Copy Columns
Option Explicit
Sub CopyColumnsToResult()
Dim sColNames(): sColNames = Array("#BASEDATA#name", _
"#BASEDATA#uniqueId", "#BASEDATA#operatingStatus")
Dim dCols(): dCols = Array(3, 4, 1)
Dim sws As Worksheet: Set sws = ThisWorkbook.Sheets("Source")
Dim shrg As Range: Set shrg = sws.Rows(1)
Dim slCell As Range: Set slCell = shrg.Cells(shrg.Cells.Count) ' last cell
Dim dws As Worksheet: Set dws = ThisWorkbook.Sheets("Result")
Dim shCell As Range, c As Long
For c = LBound(sColNames) To UBound(sColNames)
Set shCell = shrg.Find(sColNames(c), slCell, xlFormulas, xlWhole)
If Not shCell Is Nothing Then ' header cell found
sws.Columns(shCell.Column).Copy dws.Columns(dCols(c))
End If
Next c
MsgBox "Columns copied.", vbInformation
End Sub

Excel VBA - worksheet/range reference does not work properly [duplicate]

This question already has answers here:
Excel VBA, getting range from an inactive sheet
(3 answers)
Why does Range work, but not Cells?
(1 answer)
Closed 4 months ago.
I have problem with the worksheet/range initiating and I can't see why my code doesn't work. I was debugging and it seems like I had to be on a certain worksheet to make the related references to work. Can anyone please let me know what did I do wrong?
Sub salesImport()
Application.ScreenUpdating = False
'Excel workbook, the source and target worksheets, and the source and target ranges.
Dim wbBook As Workbook
Dim wsSource As Worksheet
Dim wsTarget As Worksheet
Dim rnSource As Range
Dim rnTarget As Range
Dim rng As Range
Dim cIndex, rIndex1, rIndex2, rIndex3, iR, iC As Integer
Dim rowC, columnC As Integer
'Initialize the Excel objects
Set wbBook = ThisWorkbook
With wbBook
Set wsSource = .Worksheets("Sales")
Set wsTarget = .Worksheets("Summary-Official")
End With
'On the source worksheet, set the range to the data stored
With wsSource
rowC = .Cells.SpecialCells(xlCellTypeLastCell).row
columnC = .Range("A1").SpecialCells(xlCellTypeLastCell).Column
Set rnSource = .Range(Cells(1, 1), Cells(rowC, columnC))
End With
With wsTarget
Set rnTarget = .Range("B98:AM122")
End With
rIndex1 = 6 'month
rIndex2 = 10 'plant
rIndex3 = 17 'sales
iR = 0
iC = 0
For Each Column In rnSource
Column.Cells(rIndex1, 1).Select
Dim m As String: m = Column.Cells(rIndex1, 1).Value
Select Case Month(DateValue("01 " & m & " 2012"))
Case 1
iC = 6
Case 2
iC = 7
Case 3
iC = 8
Case 4
iC = 9
End Select
iR = findrow2(Column.Cells(rIndex2, 1), rnTarget)
If iR <> 0 Then
rnTarget.Cells(iR - 97, iC).Value = Column.Cells(rIndex3, 1).Value
End If
'MsgBox ("got here")
Next Column
Application.ScreenUpdating = True
End Sub
Thanks!
With wsSource
'...
Set rnSource = .Range(Cells(1, 1), Cells(rowC, columnC))
End With
should be
With wsSource
'...
Set rnSource = .Range(.Cells(1, 1), .Cells(rowC, columnC))
End With
...otherwise your Cells() calls default to the activesheet, which may not be wsSource

How to switch the code from Select Range (Input Box) to Row Count?

Current Code is provided below. The user selects the Range of cells from which unique values needs to be found out. Instead of this, I know the Range of cells which is entire Column B of Sheet Database. I tried switching the code by the code below but it's giving "Run-time error '424': Object Required" where I am trying to count the number of rows with data.
Sheets("Database").Activate
last_row = Cells(Row.Count, "B").End(xlUp).Row <- Error
Set rngTarget = Sheets("Database").Range("B2:B" & last_row)
If rngTarget Is Nothing Then Exit Sub
Current Code:
strPrompt = "Select the Range from which you'd like to extract uniques"
On Error Resume Next
Set rngTarget = Application.InputBox(strPrompt, "Get Range", Type:=8)
On Error GoTo 0
If rngTarget Is Nothing Then Exit Sub
Changed Code: (Doesn't work - Gives Run-Time Error)
Sheets("Database").Activate
last_row = Cells(Row.Count, "B").End(xlUp).Row <- Error
Set rngTarget = Sheets("Database").Range("B2:B" & last_row)
If rngTarget Is Nothing Then Exit Sub
rngTarget function should contain the range of cells from which unique values needs to be found out.
Update 1
Complete Code for reference:
Public Sub WriteUniquesToNewSheet()
Dim wksUniques As Worksheet
Dim rngUniques As Range, rngTarget As Range
Dim strPrompt As String
Dim varUniques As Variant
Dim lngIdx As Long
Dim last_row As Long
Dim colUniques As Collection
Set colUniques = New Collection
'Prompt the user to select a range to unique-ify
'strPrompt = "Select the Range from which you'd like to extract uniques"
'On Error Resume Next
' Set rngTarget = Application.InputBox(strPrompt, "Get Range", Type:=8)
'On Error GoTo 0
'If rngTarget Is Nothing Then Exit Sub '<~ in case the user clicks Cancel
Sheets("Database").Activate
last_row = Cells(Row.Count, 2).End(xlUp).Rows
Set rngTarget = Sheets("Database").Range("B2:B" & last_row)
If rngTarget Is Nothing Then Exit Sub
'Collect the uniques using the function we just wrote
Set colUniques = CollectUniques(rngTarget)
'Load a Variant array with the uniques
'(in preparation for writing them to a new sheet)
ReDim varUniques(colUniques.Count, 1)
For lngIdx = 1 To colUniques.Count
varUniques(lngIdx - 1, 0) = CStr(colUniques(lngIdx))
Next lngIdx
'Create a new worksheet (where we will store our uniques)
Set wksUniques = Worksheets("Lists")
Set rngUniques = wksUniques.Range("A2:A" & colUniques.Count + 1)
rngUniques = varUniques
'Let the user know we're done!
MsgBox "Finished!"
End Sub
To get you started, you have refered to Row instead of a range object representing all Rows. Follow the links to see the difference :)
Next you have used .Activate and therefor not specified what worksheet you working from. A better practice would be to use something like:
With Thisworkbook.Sheets("Database") 'Can even be dereferenced from worksheets collection
last_row = .Cells(.Rows.Count, "B").End(xlUp).Row
Set rngTarget = .Range("B2:B" & last_row) 'Tricky if last_row is 1
If rngTarget Is Nothing Then Exit Sub 'Superfluous and can be deleted
End with

Excel VBA: Is there something simple causeing the error 1004?

Sub copyFilteredData2()
Dim employee As String
Dim AutoFiltrng As Range
Dim rng As Range
Dim FilterSh As Worksheet
Dim DashSh As Worksheet
Dim FilterRng As Range
Set FilterSh = ActiveWorkbook.Sheets("Report")
Set DashSh = ActiveWorkbook.Sheets("Metrics Page")
Set FilterRng = FilterSh.Range("A1")
Dim Cell As Range
FilterRng.AutoFilter field:=19, Criteria1:=DashSh.Range("E4").value
With FilterSh.AutoFilter.Range
On Error Resume Next
Set AutoFiltrng = .Offset(1, 0).Resize(.Rows.Count - 1, 1).SpecialCells(xlCellTypeVisible)
On Error GoTo 0
End With
If AutoFiltrng Is Nothing Then
MsgBox "No data for that Engineer!"
Else
Worksheets(DashSh.Range("E4").value).Cells.Clear
Set rng = FilterSh.AutoFilter.Range
rng.Offset(1, 0).Resize(rng.Rows.Count - 1).Copy Destination:=DashSh.Range("E4").value
End If
End Sub
My goal with this code is to use a data set with data validation to filter information based on a value and then copy the information and paste it to a spread sheet that is named the same value. Ultimately I plan to build the code to loop through range E4:E25.

In range find this and do that

Have a range of cell with column headings as weeks In the range of cells I want to look for a number, say
1 if it finds a 1 then look at a column in said row for a variable, 2 or 4 whatever Now I want to put a triangle (can be copy and paste a cell) in the cell that has the "1" in it then skip over the number of week variable and add another triangle and keep doing this until the end of the range. Then skip down to the next row and do the same, until the end of the range.
Then change to the next page and do the same thing... through the whole workbook.
I think I have it done, don't know if it's the best way.
I get a error 91 at the end of the second loop, the first time the second loop ends it goes through the error code.
The second time the second loop ends it errors.
I don't understand it runs through once, but not twice.
Sub Add_Triangles2()
Dim Rng As Range
Dim OffNumber As Integer
Dim SetRange As Range
Dim OffsetRange As Range
Dim ws As Worksheet
Set SetRange = Sheets("Sheet1").Range("G25") ' Used to stop the second loop in range
Worksheets(1).Activate
Worksheets(1).Range("A1").Select ' Has item to be pasted (a triangle)
Selection.Copy
For Each ws In Worksheets
Worksheets(ws.Name).Activate
With Range("C4:G25")
Set Rng = .Find(1, LookIn:=xlValues)
If Not Rng Is Nothing Then
FirstAddress = Rng.Address
Do
Rng.Activate
ActiveSheet.Paste
Do
OffNumber = Range("A" & ActiveCell.Row)
Set OffsetRange = SetRange.Offset(0, -OffNumber)
If Not ActiveCell.Address < OffsetRange.Address Then
Exit Do
Else
End If
ActiveCell.Offset(, OffNumber).Select
ActiveSheet.Paste
Loop While (ActiveCell.Address <= OffsetRange.Address)
On Error GoTo ErrorLine
Set Rng = .FindNext(Rng)
Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress
End If
End With
ErrorLine:
On Error GoTo 0
Application.EnableEvents = True
Next ws
Application.CutCopyMode = False
End Sub
I was not able to get an Error 91 using the data set I built from your explanation, maybe a screenshot of the layout could help recreate the issue.
However, I would do something like this, it will look at the value of each cell in the range C4:G25, and if it equals 1, it will paste the symbol stored in Cell A1.
Sub Add_Triangles2()
Dim Rng As Range
Dim rngSymbol As Range
Dim intFindNum As Integer
Dim ws As Worksheet
Set rngSymbol = Range("A1") 'Set range variable to hold address of symbol to be pasted
intFindNum = 1 'Used to hold number to find
Worksheets(1).Activate
For Each ws In Worksheets
Worksheets(ws.Name).Activate
For Each Rng In Range("C4:G25")
If Rng.Value = intFindNum Then
rngSymbol.Copy Rng
End If
Next Rng
Next ws
End Sub
I got it....
Sub Add_TriWorking()
Dim Rng As Range
Dim rngSymbol As Range
Dim intFindNum As Integer
Dim ws As Worksheet
Dim OffNumber As Integer
Dim SetRange As Range
Dim OffsetRange As Range
Set SetRange = Sheets("Sheet1").Range("G25") ' Used to stop the second loop in range
Set rngSymbol = Range("A1") 'Set range variable to hold address of symbol to be pasted
intFindNum = 1 'Used to hold number to find
Worksheets(1).Activate
For Each ws In Worksheets
Worksheets(ws.Name).Activate
For Each Rng In Range("C4:G25")
If Rng.Value = intFindNum Then
rngSymbol.Copy Rng
Rng.Activate
ActiveCell.Copy
Do
OffNumber = Range("A" & ActiveCell.Row)
Set OffsetRange = SetRange.Offset(0, -OffNumber)
If Not ActiveCell.Address < OffsetRange.Address Then
Exit Do
Else
End If
ActiveCell.Offset(, OffNumber).Select
ActiveSheet.Paste
Loop While (ActiveCell.Address <= OffsetRange.Address)
On Error GoTo ErrorLine
End If
Next Rng
ErrorLine:
On Error GoTo 0
Application.EnableEvents = True
Next ws
Application.CutCopyMode = False
End Sub

Resources