VBA - For loop throws Error 1004 after 5 passes - excel

I'm trying to write a VBA procedure to replace all #REF text in formulas with text from the first column of the worksheet which are also names of other sheets.
Each line has formulas from C to BC and the text from the first column varies by line.
The procedure works great for the first 4 rows and no matter what I do to the loop parameter, it will throw 1004 error (application-defined or object-defined error) on the 5th line.
PS.: First row of data is row 4, so the exception occurs when the loop reaches row 9.
I'd be glad to give more details if needed.
Sub Formulas()
Dim m As Integer, pts As Worksheet, formstr As String
Set pts = Sheets("Pontos")
m = Application.WorksheetFunction.CountIf(pts.Range("A5:A30"), "*") + 5
For i = 5 To m
For Each c In pts.Range("C" & i & ":BC" & i).Cells
formstr = c.Formula
formstr = Replace(formstr, "#REF", "'" & Cells(i, 1) & "'", , , vbTextCompare)
c.Formula = formstr
Next
Next i
End Sub
I've tried different forms of loops and mess with i and whenever it's > 9 there will be an error.

Related

For If Statement

I'm having an issue with my For If statement. The scenario is that, I need the empty cells to be filled with a telephone number. I have made a code and it works but at some point it will stop in between. Sometimes all the way to the end of the last row or just skip a few cells and continue again. I'm really not sure about this weird issue, hopefully someone can give me an insight. I have also attached a snapshot of the results.
My code is as shown below:-
Dim pn As Range
Dim h As Integer, phone As Integer
lastrow = Range("A" & Rows.Count).End(xlUp).Row
Set pn = Range("AE2:AE" & lastrow)
h = 1
For phone = 1 To pn.Rows.Count
If pn.Cells(h) = "" Then
pn.Cells(h) = "03-33422828"
Else
h = h + 1
End If
Next
An alternative way to do this is to select all the used cells in that range, then fill all the blank ones with a value.
For example, if we have a workbook with data in column A and we want to fill the blank cells in that column with "---" we could do this:
On Error Resume Next
Range("A1:A" & ActiveSheet.UsedRange.Rows.Count). _
SpecialCells(xlCellTypeBlanks).Value = "---"
On Error GoTo 0
VBA will generate an error if there are no blank cells, so I've "handled" that by just ignoring any errors.
For you it would be more like:
On Error Resume Next
Range("AE1:AE" & ActiveSheet.UsedRange.Rows.Count). _
SpecialCells(xlCellTypeBlanks).Value = "03-33422828"
On Error GoTo 0

Copy / paste within for cycle

I'm trying to copy contents from several sheets to a final sheet (let's call it "Report" sheet), where the content of a sheet is copied starting on the first free row after the content of the previous sheet.
I'm using a for cycle to go to each sheet and copy the range that I need and paste it to the Report sheet, but I'm getting:
Run-time error 1004: "Application-defined or object-defined error"
I already tried changing how to copy/paste the contents, but it still didn't work (copy and paste special; destination range.value = source range.value; select; ...).
Do you have an idea of what's going on?
Thanks in advance for your help!
Sub final_data()
Dim list_end, last_line, h, first_line_range, last_line_range As Integer
Dim sht_qty As Integer
h = 1
i = 2
list_end = 1
sht_qty = Application.Sheets.Count
For h = 1 To sht_qty
If Workbooks("Testes2").Sheets(h).Name <> "Report" Then
last_line = Workbooks("Testes2").Sheets(h).Range("A1").End(xlDown).Row
first_line_range = list_end + 1
last_line_range = last_line + list_end - 1
'the error is on the next line
Workbooks("Testes2").Sheets(h).Range("A2:I" & last_line).Copy Destination:=Workbooks("Testes2").Sheets("Report").Range("A" & first_line_range & "I" & last_line_range)
Else
End If
Next h
End Sub
Just change your destination to this:
Destination:=Workbooks("Testes2").Sheets("Report").Range("A" & first_line_range)
and that should work

Making a VBA FOR loop using vlookup function in Excel

I would like to use a Vlookup function 47 times to get the value for every data. I call the table I am filling "Table 1". "Table 1 starts from E3. I would like to use the vlookup to find the value for cell E3 and fill it in F3.
I call the table from which I return value by Vlookup "Table2". "Table 2 is located in sheet "CC Name" and has two columns A and B.
I have tried two FOR Loops. One FOR Loop for the Vlookup function to be repeated 47 times. Second FOR Loop for the Name of the vlookup function "ccName" to use the function to fill the value in "Table 1" for 43 times, but I get error every time I implement the Code.
Sub GLcreation()
For n = 3 To 50
For c = 3 To 50
ccName(c) = WorksheetFunction.Vlookup(Range("E" & n), Worksheets("CC Name").Range("A:B"), 2, 0)
Range("F" & n) = ccName(c)
Next c
Next n
End Sub
If you can Show me how to Code the correct for Loop, I appreciate your help.
As soon as there is a non-match the code will fail. It's safer to test for match before making the lookup. Here is a better solution:
Sub GLcreation()
Dim n As Integer
Dim wf As WorksheetFunction
Set wf = WorksheetFunction
For n = 3 To 50
If wf.CountIf(Worksheets("CC Name").Range("A:A"), Range("E" & n).Value) > 0 Then
Range("F" & n).Value = wf.Index(Worksheets("CC Name").Range("B:B"), wf.Match(Range("E" & n).Value, Worksheets("CC Name").Range("A:A"), 0))
End If
Next n
End Sub
By getting rid of c Loop, the correct Code is:
Range("F" & n) = WorksheetFunction.Vlookup(Range("E" & n), Worksheets("CC Name").Range("A:B"), 2, 0)

Inserting formulas w/ FOR NEXT Loop

Couldn't find a thread that would answer my question, os here I am. Please provide a link if there is one that I have not found.
Using Excel 2010
The comments should be sufficient to show what I'm trying to do.
I'm getting the Application-defined or Object-defined error (Runtime error 1004) I just can figure it out. Any help would be appreciated. Side note: I can get the loop to work when a formula like =if(A1=B1,"",3) If actually places the formula in the cell and show 3 in each cell when the condition is met. it just adding the Column,Row, I've tried & Range($, C) &, all sorts of combinations so, show me how much of a boob I am and help me with the SIMPLE fix that eludes me.
Thanks in advance.
Private Sub CommandButton1_Click()
Dim R, C As Integer
Dim Frmla1, Frmla2, Frmla3 As String
R = 4 'Initial Row #
C = 2 'Initial Column #
Frmla1 = "=IF('Log Sheet'!" '1st half of the formula
Frmla2 = "="""","""",'Log Sheet'!" '2nd half of the formula
Frmla3 = ")" 'Closing Parenthesis
' The Cells should have incremental Column,Row Identifiers.
' The following is what I want in each cell.
' The problem is trying to get the B4 and B5 into the formula.
' Formula "=IF('Log Sheet'!B4="","",'Log Sheet'!B4)
' Formula "=IF('Log Sheet'!B5="","",'Log Sheet'!B5)
For R = 4 To 301
ActiveSheet.Cells(R, C).Value = Frmla1 & R & C & Frmla2 & R & C & Frmla3
R = R + 2
Next R
End Sub
It looks like you should be using the R and C to reference a Range.Cells property that you can return a Range.Address property from.
For R = 4 To 301 Step 2
ActiveSheet.Cells(R, C).Formula = _
Frmla1 & Cells(R, C).Address(0, 0) & Frmla2 & Cells(R, C).Address(0, 0) & Frmla3
Next R
I've also removed your R = R + 2 and changed the Step of the For ... Next to increment by 2. You shouldn't self-increment a For ... Next inside the loop.
I changed the Range.Value property assignment to Range.Formula property. While your method often works, it wasn't correct and if the cells were formatted as Text, the formulas would come into the cells as text-that-looks=like-a-formula.
Your variable declarations should be more like the following.
Dim R As Long, C As Long
Dim Frmla1 As String, Frmla2 As String, Frmla3 As String
Each declaration should carry a variable type. Without it, they are declared as object/variant types,

Excel VBA - Loop through range and set formula in each cell

I've got a workbook where I have one worksheet which contains a lot of data.
My goal is to create a macro that inserts a formula in a separate sheet to copy the data from the first sheet. Lets call the first sheet "Numbers1" and the second sheet "TidyNumbers1".
In the sheet "TidyNumbers1" I want to loop through each cell from column A to M and rows 1 to 60. So I've got a macro that so far looks like this:
Sub updateFormulasForNamedRange()
Dim row, col, fieldCount As Integer
colCount = 13
RowCount = 60
For col = 1 To colCount
For row = 1 To RowCount
Dim strColCharacter
If col > 26 Then
strColCharacter = Chr(Int((row - 1) / 26) + 64) & Chr(((row - 1) Mod 26) + 65)
Else
strColCharacter = Chr(row + 64)
End If
Worksheets("TidyNumbers1").Cells(row, col).Formula = "=IF(Numbers1!E" & col & "<>0;Numbers1!" & strColCharacter & row & ";"")"
Next row
Next col
End Sub
But the formula is supposed to looks like this for Column A, row 2:
IF(Numbers1!E2<>0;Numbers1!A2;"")"
And the formula in Column A, row 3 should look like this:
IF(Numbers1!E3<>0;Numbers1!A3;"")"
Formula in Column B, row 2 should look like this:
IF(Numbers1!E2<>0;Numbers1!B2;"")"
In other words, the formula looks to see if the value in Column E, row % is anything but 0 and copies it if conditions are met.
But, I see that I need to translate my integer variable Row with letters, because the formula probably needs "A" instead of 1. Also, I get a 1004 error (Application-defined or object-defined error) if I just try to use:
Worksheets("Numbers1").Cells(row, col).Formula = "=IF(Numbers1!E" & row & "<>0;Numbers1!" & col & row & ";"")"
I clearly see that the integer row should be translated to letters, if that's possible. Or if anyone has any other suggestions that might work. Also, the 1004 error is unclear to me why happens. I can define a string variable and set the exact same value to it, and there's no error. So it's probably the formula bar that whines about it I guess?
Here is a former post of mine containing functions for conversion of column numbers to letters and vice versa:
VBA Finding the next column based on an input value
EDIT: to your 1004 error: Try something like this:
=IF(Numbers1!E" & row & "<>0,Numbers1!A" & row & ","""")"
(use ; instead of ,, and "" for one quotation mark in a basic string, """" for two quotation marks).
Would not it be easier to get the cell address with the Cells.Address function?
For example:
MsgBox Cells(1, 5).Address
Shows "$E$1"
Best Regards

Resources