Excel 1004 error - Application or Object Defined - vba

I tried googling an answer for why I'm getting this but nothing helps so far. The sheet isn't protected. Any ideas? Thanks.
Sub category_sums()
Set ws = ActiveWorkbook.Sheets("Test")
ws.Activate
Set MyRg1 = ws.Range("$A$2:$A$582")
Set MyRg2 = ws.Range("$H$2:$H$58")
ws.Range("J17").Formula = "=SumIf((MyRg1,""Auto/Transportation"", MyRg2)"
End Sub

Your ranges need to be same length, concatenate address from variables in and drop the additional bracket. Use Option Explicit at the top of your module and declare all your variables.
Option Explicit
Sub category_sums()
Dim ws As Worksheet, MyRg1 As Range, MyRg2 As Range
Set ws = ActiveWorkbook.Worksheets("Test")
ws.Activate
Set MyRg1 = ws.Range("$A$2:$A$582")
Set MyRg2 = ws.Range("$H$2:$H$582")
ws.Range("J17").Formula = "=SumIf(" & MyRg1.Address & ",""Auto/Transportation"", " & MyRg2.Address & ")"
End Sub

Related

Delete rows from A2 to the end of the column in VBA

I am try to come up a code in VBA the will delete from A2(row 2) to the end of rows
Option Explicit
Sub Ticket()
Dim a As Long
Application.Calculation = xlManual
a = ThisWorkbook.Worksheets("Fleet Report").Range("A2").End(xlDown).Row
MsgBox "Last Row is " & a
ThisWorkbook.Worksheets("Fleet Report").Rows("3:a").EntireRow.Delete
End Sub
But I got error message: type mismatch. Does anyone has an idea?
Your line of code for deleting is incorrectly written. It reads:
ThisWorkbook.Worksheets("Fleet Report").Rows("3:a").EntireRow.Delete
When it should say:
ThisWorkbook.Worksheets("Fleet Report").Rows("3:" & a).EntireRow.Delete
Also to avoid row and column numbers, which I personally am not a fan of, you could format it as:
ThisWorkbook.Worksheets("Fleet Report").Range("A3:A" & a).EntireRow.Delete
Hope this helps!
Try this:
Sub Ticket()
Dim a As Long
Dim WB As Workbook, WS As Worksheet
Set WB = ActiveWorkbook
Set WS = WB.Worksheets("Fleet Report")
Application.Calculation = xlManual
a = WS.Range("A2").End(xlDown).Row
MsgBox "Last Row is " & a

Excel VBA - Table column formula - Error 1004

Morning All,
I'm trying to create function that changes the result column in a =VLOOKUP formula.
Sub changeDay(day As Integer)
Dim ws As Worksheet
Dim lo As ListObject
Dim lColName As ListColumn
Set ws = ThisWorkbook.Worksheets("sheetName")
Set lo = ws.ListObjects(1)
Set lColName = lo.ListColumns(2)
lColName.DataBodyRange.FormulaR1C1 = "=VLOOKUP'([#ID],'sheetName'!$A$2:$J$404," & day & ")"
End Sub
It returns an error Run-time error '1004': Application-defined or object-defined error.
Where am I going wrong, this seems to be the accepted solution for other people.
Replace FormulaR1C1 with Formula.
What is the function of FormulaR1C1?
Working solution for anyone facing the same problem.
Sub changeDay(day As Integer)
Dim ws As Worksheet
Dim lo As ListObject
Dim lCol As ListColumn
Set ws = ThisWorkbook.Worksheets("aWorksheetname")
Set lo = ws.ListObjects(1)
Set lCol = lo.ListColumns(2)
lColName.DataBodyRange.Formula = "=VLOOKUP([#ID],'aWorkSheetname'!$A$2:$J$404," & CStr(day) & ")"
End Sub

Syntax for VBA Vlookup to another workbook

I'm trying to perform a VLOOKUP in VBA, using a table in a different workbook.
I've tried:
width = Application.VLookup(code, Workbooks("T:\Data\Dimensions.xlsx").Sheets("Main").Range("A61:G1500"), 7, False)
where code is a variable I've already set, but it just returns "Subscript out of range".
I'm sure you can see what I'm trying to do, but I'm guessing I've got the syntax wrong in the vlookup.
Thanks.
Make sure the target workbook is opened. Try this:
Set src = Workbooks.Open("T:\Data\Dimensions.xlsx")
width = Application.VLookup(code, src.Sheets("Main").Range("A61:G1500"), 7, False)
The code below is a little long, but it will work you through step-by-step, defining and setting all your objects (see comments in the code itself).
You also need to handle a scenario where Vlookup will not be able to find code in your specified Range,
Code
Option Explicit
Sub VlookupClosedWorkbook()
Dim Width, code
Dim WorkbookName As String
Dim WB As Workbook
Dim Sht As Worksheet
Dim Rng As Range
WorkbookName = "Dimensions.xlsx"
' set the workbook object
On Error Resume Next
Set WB = Workbooks(WorkbookName) ' first try to see if the workbook already open
On Error GoTo 0
If WB Is Nothing Then ' if workbook = Nothing (workbook is closed)
Set WB = Workbooks.Open("T:\Data\" & WorkbookName)
End If
' set the worksheet object
Set Sht = WB.Sheets("Main")
' set the Range object
Set Rng = Sht.Range("A61:G1500")
' verify that Vlookup found code in the Range
If Not IsError(Application.VLookup(code, Rng, 7, False)) Then
Width = Application.VLookup(code, Rng, 7, False)
Else
MsgBox "Vlookyp Error finding " & code
End If
End Sub
You have to open that workbook or use cell to get value from closed one
range("A1").formula = "=vlookup(" & code & ",'T:\Data\[Dimensions.xlsx]Main'!A61:G1500,7,0)"
range("A1").calculate
width = range("A1").value

excel vba insert column runtime error 1004

this is my first post on StackExchange! I've been using StackExchange for answers, but now i really have a question.
I am trying to add a column in excel using vba. This is procedure is part of a bigger sub function of which I created a new workbook and copy a series of sheets from a different workbook over.
Workbooks.Add
Set TTB = ActiveWorkbook
'add a bunch of sheets here
'sheetName = specific_sheet
Set ttb_sheet = TTB.Sheets(sheetName)
ttb_sheet.Columns("I:I").Insert Shift:=xlToRight
With this i get a runtime error of 1004: 'Insert method of Range class failed'
I tried following a series of questions on StackOverflow...
Select method of Range class failed via VBA
VBA error 1004 - select method of range class failed
It seems like the solution is to select the sheet first, then select the range. I have tried this and there was no luck. Anyone have any insight?
Here's my main sub code..
Sub create_TTB_workbook(TTB_name_)
'create TTB workbook
Dim wsHelper As New WorksheetHelper
Dim final_TTB As Workbook
Dim ttb_sheet As Worksheet
ttb_wb = ActiveWorkbook.name
Workbooks(ttb_wb).Activate
PCB_tab = 0
ST_COMP_tab = 0
For Each WS In Worksheets
If WS.name = "PCB_PIN_REPORT" Then
PCB_tab = 1
End If
If WS.name = "ST_PIN_REPORT" Then
ST_COMP_tab = 1
End If
Next WS
Workbooks.Add
Set TTB = ActiveWorkbook
new_ttb_wb = TTB.name
Debug.Print (new_ttb_wb)
If PCB_tab = 1 Then
wsHelper.copySheet ttb_wb, "PCB_PIN_REPORT", new_ttb_wb, "PCB_PIN_REPORT"
End If
If ST_COMP_tab = 1 Then
wsHelper.copySheet ttb_wb, "ST_PIN_REPORT", new_ttb_wb, "ST_PIN_REPORT"
End If
wsHelper.copySheet ttb_wb, TTB_name_, new_ttb_wb, TTB_name_
' TRIED A BUNCH OF METHODS here...
'Workbooks(ttb_wb).Sheets(TTB_name_).Cells.copy
'Sheets.Add.name = TTB_name_
'ActiveSheet.paste
'Sheets(TTB_name_).Activate
'Columns("I:I").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
'Worksheets(TTB_name_).Range("I1").EntireColumn.Insert
'Columns("I:I").Select
'Columns("I:I").Insert Shift:=xlToRight
Set ttb_sheet = Sheets(TTB_name_)
ttb_sheet.Columns("I:I").Insert Shift:=xlToRight
Columns("K").copy Destination:=Range("I1")
Range("I6") = "header name"
End Sub
Whenever I run into an issue like this, I always isolate the code to its simplest form. Once I get it working at that level, I add it back in to the full application and can usually figure out what I did wrong.
I've written a simple version of what you are trying to do. Note that I've included a few Debug.Print statements to help me verify what is going on. The debug messages will appear in your Immediate window. Obviously you can also step through the code and examine variables as you go.
To get this to work, create a workbook and save it as DestinationWorkbook.xlsx. Then open another workbook and insert the code below.
Sub InsertColumnInDestinationWorksheet()
Dim sourceWb As Workbook
Dim targetWb As Workbook
Dim sourceWs As Worksheet
Dim targetWs As Worksheet
Set sourceWb = ThisWorkbook
Debug.Print sourceWb.Name
Set targetWb = Workbooks("DestinationWorkbook.xlsx")
Debug.Print targetWb.Name
Set sourceWs = sourceWb.Sheets("Sheet1")
Debug.Print sourceWs.Name
Set targetWs = targetWb.Sheets("Sheet1")
Debug.Print targetWs.Name
targetWs.Range("I1").Value2 = "Moving right along..."
targetWs.Columns("I:I").Insert shift:=xlToRight
End Sub
After running the code, you can examine the target sheet. You should see the text we wrote into column I is now in column J.
This works for me when I change the variable naming to:
Sub testingg()
Dim ttb_sheet As Worksheet
Set ttb_sheet = Sheets(1)
ttb_sheet.Columns("I:I").Insert Shift:=xlToRight
End Sub
So I presume there's an issue with the way you reference the workbook when setting ttb_sheet on line 3. Note that you add a workbook but you aren't actually 'activating' it necessarily. And are you sure the 'Sheetname' actually exists in the TTB workbook?

Copy a range with rows to another sheet

My requirement is to copy rows from sheet3 having font color black to sheet1.I have a range of rows selected from sheet3 in a workbook. I want to copy this and paste in sheet1.Selection part is ok, but Error (Application defined or object defined ) in copy statement.
Sub Copy()
Dim lastRow, i As Long
Dim CopyRange As Range
lastRow = Sheet3.Rows.Count
With Sheets(Sheet3.Name)
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 1 To lastRow
If .Rows(i).Font.Color = 0 Then
If CopyRange Is Nothing Then
Set CopyRange = .Rows(i)
Else
Set CopyRange = Union(CopyRange, .Rows(i))
End If
End If
Next
End With
CopyRnge.Copy Destination:=Worksheets("Sheet1").Range("A1:J300")
End Sub
Option Explicit forces you to declare ALL the variables you use.
CopyRnge.Copy didn't exist when you ran the program, so Excel showed a run-time error.
Common errors like these can be avoided by turning on Option Explicit by default.
How to enable Option Explicit for all modules in VBA:
Suggested Code To Try:
The code below uses Option Explicit and it also takes advantages of using Object References.
By setting up Object References, you can rely on Intellisense to ensure you avoid typos.
Option Explicit
Sub CopyBlackText()
Dim lastRow As Long
Dim i As Long
Dim srcRangeToCopy As Range
Dim destinationRange As Range
Dim wrkbook As Workbook
'Setup Object references by assigning and using the 'Set' keyword
Set wrkbook = ActiveWorkbook
Set destinationRange = wrkbook.Worksheets("Sheet1").Range("A1:J300")
With wrkbook.Worksheets("Sheet3")
'Using Cells(1,1).Address instead of saying Range("A1")
lastRow = .Range(Cells(1, 1).Address).End(xlDown).Row
For i = 1 To lastRow
If .Rows(i).Font.Color = 0 Then
If srcRangeToCopy Is Nothing Then
Set srcRangeToCopy = .Rows(i)
Else
Set srcRangeToCopy = Union(srcRangeToCopy, .Rows(i))
End If
End If
Next
End With
srcRangeToCopy.Copy Destination:=destinationRange
End Sub