Runtime error '1004': application or object defined error - excel

Runtime error '1004': application or object defined error
Hey I cant find out why my code isn't working. I know it's somewhere in the right hand side of the formula. I've highlighted the error for you.
Private Sub CommandButton1_Click() 'accept button
Blank:
machine = TextBox1.Value
rates = TextBox2.Value
If machine = "" Then 'if blank
MsgBox ("Please type in a machine name.")
GoTo DONE
ElseIf rates = "" Then 'if rates is blank
MsgBox ("Please type in a rate for machine.")
GoTo DONE
End If
For i = 1 To 50 'search database
If LCase(Worksheets("database").Cells.Range("B2").Offset(0, i)) = LCase(machine) Then 'if name is in database
MsgBox (machine & " is already in database. Choose another name.")
GoTo DONE
ElseIf IsEmpty(Worksheets("database").Cells.Range("B2").Offset(0, i)) Then 'if it's not
Range("B:B").Offset(0, i).Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Worksheets("database").Cells.Range("B2").Offset(0, i) = machine
Worksheets("database").Cells.Range("B2").Offset(0, i).HorizontalAlignment = xlLeft
Worksheets("database").Cells.Range("B2").Offset(-1, i) = rates
For j = 1 To 50
If LCase(Range("A1").Offset(j, 0)) = "total hours" Then
ActiveSheet.Range("B1").Offset(j, i).Formula = "=sum(" & Range(Cells(3, i + 2), Cells(j, i + 2)).Address(False, False) & ")"
ActiveSheet.Range("B1").Offset(1 + j, i).Formula = "=product(sum(" & ActiveSheet.Range(Cells(3, i + 2), Cells(j, i + 2)).Address(False, False) & "," & ActiveSheet.Range(Cells(1, 2 + i)) & ")"
GoTo Cancel
End If
Next j
GoTo Cancel
End If
Next i
Cancel:
DONE:
End Sub
the line that i separate from the others is the one in question.
Thanks!

Hard to know without a description of what you are trying to do. But perhaps:
"=product(sum(" & ActiveSheet.Range(Cells(3, I + 2), Cells(J, I + 2)).Address(False, False) & "," & ActiveSheet.Cells(1, 2 + I).Address & "))"

You need to analyze each part of the line by itself to see what is causing the error. Then put them together after verifying the parts.
Dim HoursRangeAddress As String
Dim RateRangeAddress As String
HoursRangeAddress = ActiveSheet.Range(Cells(3, i + 2), Cells(j, i + 2)).Address(False, False)
RateRangeAddress = ActiveSheet.Cells(1, i + 2).Address
Debug.Print HoursRangeAddress
Debug.Print RateRangeAddress
ActiveSheet.Range("B1").Offset(1 + j, i).Formula = _
"=product(sum(" & HoursRangeAddress & ")," & RateRangeAddress & ")"
You were missing a parenthesis ) after your sum. But also this caused an error: ActiveSheet.Range(Cells(1, 2 + i)) Try this instead: ActiveSheet.Cells(1, 2 + i).Address
Using R1C1 Notation: You should really learn R1C1 notation. Once you are familiar with it, your code is much easier to write and read. You can replace all of the lines of code above with this one line:
ActiveSheet.Range("B1").Offset(1 + j, i).FormulaR1C1 = "=R1C*R[-1]C"
I understand now that you are trying to multiply the rate in row one by the total hours one row above this formula.
It's so much better to use R1C1 notation in a situation like this. You can avoid entirely the need to create string addresses for the formulas. Your formula becomes very simple and easy to read.

Related

Using VLOOKUP in Formula

I am getting a compile error on this line but everything seems right to me. I need to put a vlookup inside an if statement which is making this tricky. Can someone catch the error?
Dim k as Integer, numS as Integer
Range(Cells(k, 13), Cells(k, 13)).Formula = _
"=IF(" & Range(Cells(k, 14), Cells(k, 14)).Value & "=" & VLOOKUP(""Weeks from Event " & numS-1 & " to Event " & numS & """, R11C5:R10000C8, 4) & "," & (numS) & ", """")"
I think the error is the RC notation, try R[11]C[5]:R[10000]C[8], but to use VlookUp in VBA I like to use Application.WorksheetFunction...
Sub test()
Dim k As Long
Dim numS As Long
Dim LookUpValue As String
LookUpValue = "Weeks from Event " & numS - 1 & " to Event " & numS
Debug.Print (LookUpValue)
If (Cells(k, 14).Value = WorksheetFunction.VLookup(LookUpValue, Range(Cells(11, 5), Cells(1000, 8)), 4)) Then
Cells(k, 13).Value = numS
Else
Cells(k, 13).Value = ""
End If
End Sub
Let me know if this helps. You can pull up the immediate windows (Ctrl+G) in the VBA editor to see what the value of LookUpValue will be.

Deleting Cells after Concatenation in VBA

I am trying to reformat a text file that has been imported into Excel.
I have done several minor reformatting points including adding rows, deleting page numbers, and combining headlines back into a single cell via the & function (the text file was delimited when importing).
After a concatenate, in which I took certain cells from columns A-Z and combined them in Column A, I tried to delete the now redundant information from Columns B-Z.
I tried selecting the cells and deleting, and also Range.Clear, but it does not delete the cells. I receive no errors.
This is what I have to take care of this step:
'Fix Duplicate Cells from Concatenate
For i = lastRow2 To 2 Step -1
If IsEmpty(Range(i, 1).Offset(-1, 0)) = True Then
ActiveSheet.Range(Cells(i, 2), Cells(i, 26)).Clear
End If
Next
Ultimately, I would like to check if column A contains no information one row above the row where I would like to delete information from columns B-Z.
Full code:
Sub Format()
'This will delete page numbers
Dim lRow As Long
Dim iCntr As Long
lRow = 350
For iCntr = lRow To 1 Step -1
If IsNumeric(Cells(iCntr, 1)) Then
Rows(iCntr).Delete
End If
Next
'Add Row above each row with Headings
Dim lRow2 As Long, iRow As Long
With Worksheets("Sheet1")
lRow2 = .Cells(.Rows.Count, "A").End(xlUp).Row ' last row in column A
'loop backwards (bottom to top = Step -1) through all rows
For iRow = lRow2 To 1 Step -1
'check if column A of current row (iRow) is "DIM"
If .Cells(iRow, "A").Value = "DIM" Then
.Rows(iRow).Resize(RowSize:=1).Insert xlShiftDown
'insert 1 row and move current (iRow) row down (xlShiftDown)
'means: insert 1 row ABOVE current row (iRow)
End If
Next iRow
End With
'Combine Headings back to single Cell
Dim lngLastRow As String
Dim lastRow As Long
Dim lastcolumn As Long
lastRow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count
lastcolumn = ActiveSheet.UsedRange.Column - 1 + ActiveSheet.UsedRange.Columns.Count
For i = lastRow To 1 Step -1
If Cells(i, 1).Value = "DIM" Then
Cells(i, 1).Value = Cells(i, 1).Value & " " & Cells(i, 2).Value & " " & _
Cells(i, 3).Value & " " & Cells(i, 4).Value & " " & Cells(i, 5).Value & " " & _
Cells(i, 6).Value & " " & Cells(i, 7).Value & " " & Cells(i, 8).Value & " " & _
Cells(i, 9).Value & " " & Cells(i, 10).Value & " " & Cells(i, 11).Value & " " & _
Cells(i, 12).Value & " " & Cells(i, 13).Value & " " & Cells(i, 14).Value & " " & _
Cells(i, 15).Value & " " & Cells(i, 16).Value & " " & Cells(i, 17).Value & " " & _
Cells(i, 18).Value & " " & Cells(i, 19).Value & " " & Cells(i, 20).Value & " " & _
Cells(i, 21).Value & " " & Cells(i, 22).Value & " " & Cells(i, 23).Value & " " & _
Cells(i, 24).Value & " " & Cells(i, 25).Value & " " & Cells(i, 25).Value
End If
Next
'Fix Duplicate Cells from Concatenate
For i = lastRow2 To 2 Step -1
If IsEmpty(Range(i, 1).Offset(-1, 0)) = True Then
ActiveSheet.Range(Cells(i, 2), Cells(i, 26)).Clear
End If
Next
End Sub
The reason I have a condition set for the clearing of cells after concatenate is because I do not simply want to clear all cells in range B:Z, or even the specific rows in this range. I only want to clear this range in the instances where there is a blank line above it (headers to data). The reason being: I am trying to keep the spreadsheet as generic as possible in order to use it again if the specific layout of rows changes based on the input file.
First, the variable lastRow2 doesn't seem to be declared, and as you don't get any errors, you obviously don't use Option Explicit. Please do, because that will warn you about such errors.
Secondly, I don't see that you in any way initialize lastRow2, which explains why the loop is never run. Did you run the code in the debugger to verify values of variables and progress of the execution? That is the first thing to do when you see unexpected results.
Thirdly, I don't understand why you have the condition and why you use offset If IsEmpty(Range(i, 1).Offset(-1, 0)) = True. Just clear the cells explicitly
Try this instead:
lastColumn = 26
For i = lastRow To 1 Step -1
Range(Cells(i, 2), Cells(i, lastColumn)).Clear
Next
edit:
I noticed you have the last column as 25 (as well as the previous one) in the part where you concatenate the values from the cells. The correct last column is 26.
edit2:
Based on your edit of your question and assuming you have declared and initialized lastRow2 the corrected function would look like this:
For i = lastRow2 To 2 Step -1
If IsEmpty(Range(Cells(i, 1), Cells(i, 1)).Offset(-1, 0)) = True Then
ActiveSheet.Range(Cells(i, 2), Cells(i, 4)).Clear
End If
Next

Macro filling wrong column with value?

Morning guys,
I have recently been tasked with being the person to update and monitor any VBA issues my currently company has, as the previous employee who was doing such has no left and there are no immediate plans to hire a replacement. Unfortunately my excel and VBA skills are rudimentary put politely, and youtube has only been able to help so much.
There is a macro used in one of the spreadsheets which checks and overwrites certain month end figures. This part of the macro runs fine, and when completed for each client an X should be input to column M (Labelled done) to signify this is done. The column N (labelled skip) is already filled with an X for those that should be skipped due to individual client technicalities.
The macro however appears to be filling in column N with the value x for when a client check is done. Have any of you ever encountered a similar issue with values being incorrectly assigned to the adjacent column?
Sub Values()
Application.ScreenUpdating = False
Dim EndRow As Integer
Dim i As Integer
Dim ValueDate As Date
Dim Cash As Double
Dim Value As Double
Dim APXRef As String
Dim d As Integer
Dim Overwrite As Boolean
Overwrite = Worksheets("Summary").Range("Y2").Value ' from checkboxes
EndRow = Range("J2").End(xlDown).Row
ValueDate = Range("P6").Value
If MsgBox("You are uploading with the following date: " & ValueDate & ", do
you want to continue?", vbYesNo) = vbNo Then Exit Sub
For i = 2 To EndRow
APXRef = Range("J" & i).Value
Value = Range("L" & i).Value
If Range("M" & i) = "" And Range("N" & i) = "" Then
Worksheets("Summary").Activate
r = Range("A:A").Find(APXRef).Row
Range("B" & r).Select
Call GoToClient
d = Range("A10").End(xlDown).Row
If Range("A" & d).Value < ValueDate Then
Range("A" & d + 1).Value = ValueDate
Range("B" & d + 1).Value = Value
Range("D" & d + 1).FormulaR1C1 = "=((RC[-2]/(R[-1]C[-2]+RC[-1]))-1)*100"
Range("E" & d + 1).FormulaR1C1 = "=((((R[-1]C)*(RC[-1]))/100)+R[-1]C)"
Range("H" & d + 1).Value = Range("H" & d).Value
'Save client
If Overwrite = True Then
Call SaveClient
End If
'Return to Flow Tab
Worksheets("Flows").Activate
Range("M" & i).Value = "x"
Else
'skip
Worksheets("Flows").Activate
Range("N" & i).Value = "x"
End If
End If
Application.StatusBar = TabRef & " " & Round(((i - 1) / (EndRow - 1)) *
100, 1) & "% Complete"
Next i
Application.StatusBar = "Value Update Complete"
End Sub

.FormulaR1C1 = Application.WorksheetFunction.CountIfs Arguments not working

I'm trying to use a countifs statement by looking in the first 2 columns and comparing them to another table in the same Wokbook. The reference RrC1, RC1 or anything else does not work. I only get "0" as a result. If i type in constants it works. I'm sure that my arguments 2, 4, 6 are the problem. I just can' figure out why!
Sub DataBase()
'Set my tables
Dim Answers As ListObject
Dim Table As ListObject
Set Answers = Worksheets("quantitativ").ListObjects("DataQuant")
Set Table = Worksheets("Database").ListObjects("Tabelle7")
'Set my Ranges for filters (Organizational level, Location, Function...)
Set OrgRange = Answers.ListColumns(1).Range
Set LocRange = Answers.ListColumns(2).Range
'Set Ranges for Answers to Questions (Scale)
Set Q1 = Answers.ListColumns(5).Range
Dim r As Long 'Row variables for For-Loop
For r = 5 To Table.DataBodyRange.Rows.Count + 4
'Q1
Cells(r, 6).FormulaR1C1 = _
Application.WorksheetFunction.CountIfs(Q1, RrC5, OrgRange, RrC1, LocRange, RrC2)
Next r
End Sub
Cells(r, 6).FormulaR1C1 = _
Application.WorksheetFunction.CountIfs(Q1, RrC5, OrgRange, RrC1, LocRange, RrC2)
This is quite a mess. You're attempting to load a formula with the result of a worksheet function.
If you want to load the formula to the cell then I'd do this:
Cells(r, 6).Formula = "=CountIfs(" & Q1.Address & ", " & _
Cells(r, 5).Address & ", " & OrgRange.Address & ", " & _
Cells(r, 1).Address & ", " & LocRange.Address & ", " & _
Cells(r, 2).Address & ")"
Or even:
Cells(r, 6).Formula = .Formula = "=CountIfs(" & _
Q1.Address & ", E" & r & ", " & _
OrgRange.Address & ", A" & r & ", " & _
LocRange.Address & ", B" & r & ")"
However, if you want the formula evaluated and just the result dumped in the cell..
Cells(r, 6).Value = Application.WorksheetFunction.CountIfs(Q1, _
Cells(R, 5), OrgRange, Cells(R, 1), LocRange, Cells(R, 2))
Keep in mind though with all of these options, Cells(.. are not fully qualified.
Changing all to .Cells(.. would make this much better, wrapping the lot
in a
With WorkSheet("DESTINATION_SHEET")
...
...
End With
is highly advisable.

Excel VBA snippet causing Run-Time Error '438'

1st time poster.
The following VBA script breaks a work macro everytime. I've tried different syntaxes to fix, but getting the same result.
The code is supposed to look through all data cells in column L, looking for the string, "ERROR". If found, copy that cell and the one to the right over to the correct column "AX" and clear the text in L and M.
The step it breaks at every time is the "Cells(i, 50).Paste" line.
Set rng = Application.Range("L4:M" & lrow)
For i = rng.Rows.Count To 4 Step -1
If Cells(i, 12).Value = "ERROR" Then
Range("L" & i & ":M" & i).Copy
Cells(i, 50).Paste
Range("L" & i & ":M" & i).ClearContents
End If
If Cells(i, 21).Value = "ERROR" Then
Rows(i).Delete
End If
Next I
Paste is not a method available to the Range object. Cells is a Range object. Ergo, "Object does not support this property or method" :)
You could try:
Cells(i, 50).PasteSpecial xlPasteAll
As #DavidZemens said, you missed the proper method name
furthermore your code seems to do unnecessary work where:
it first does something in current i row should If Cells(i, 12).Value = "ERROR" check return True
then it would delete the same i row should subsequent If Cells(i, 21).Value = "ERROR" Then return True again
Finally you're not using any PasteSpecial feature so you may want to use plain Copy one
Hence I'd refactor it as follows
Dim lrow As Long, i As Long
lrow = Cells(Rows.Count, "L").End(xlUp).Row
For i = lrow To 4 Step -1
If Cells(i, 21).value = "ERROR" Then
Rows(i).Delete
ElseIf Cells(i, 12).value = "ERROR" Then
Range("L" & i & ":M" & i).Copy Destination:=Cells(i, 50)
Range("L" & i & ":M" & i).ClearContents
End If
Next i

Resources