I copy cells (from sheet1) if they contain a specific value (got this part figured out).
I need to paste them in a cell on sheet2 in row j.
Sheet1 has a long list of names, companies, emails, phones etc. with each person's information separated by a space. For Ex:
Column A Column B
Smith, Jill #N/A
CEO #N/A
ABC Corp 123 street ABC Corp
jill@ABC.com #N/A
#N/A
Smith, John #N/A
CTO #N/A
123 Inc ABC street 123 Inc
john@123.com #N/A
I have a variable (j) that counts each space and then if Cell b does not equal #NA, then cell a is copied and pasted into sheet2 column M and row j.
Variable j is needed because the formula in column B isn't 100% and the data is inconsistent so I need j so that the company name stays on the same line as the name. I need this because I have other code to split column A (like 4000 rows) into separate sheets by names, titles, companies, emails.
I.e. Sheet3 would have:
1. Jill Smith
2. John Smith
Sub AutoCompany()
Application.ScreenUpdating = False
Dim lr As Long, tr As Long, i As Long, j As Long, k As Long
Worksheets("Sheet1").Activate
lr = Range("A" & Rows.Count).End(xlUp).Row
tr = Worksheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Row - 1
'this is my formula for column B
Range("B2:B" & lr).Formula = "=INDEX(CompaniesTbl[CompanyNamesList],IF(SUMPRODUCT(--ISNUMBER(SEARCH(CompaniesTbl[CompanyNamesList],A2)))<>0,SUMPRODUCT(--ISNUMBER(SEARCH(CompaniesTbl[CompanyNamesList],A2))*ROW($1:$" & tr & ")),NA()))"
j = 0
k = 1
For i = 2 To lr Step 1
'increase j by 1 if there is a blank space (to figure out where to paste)
If Cells(i, 1) = "" Then
j = j + 1
'extra variable just cause
k = k + 1
End If
'check for an actual value
If Application.IsNA(Cells(i, 2)) Then
Else
Worksheets("Sheet1").Cells(i, 2).Select
Selection.Copy
Worksheets("Company").Activate
Worksheets("Company").Range("M" & j).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Worksheets("Sheet1").Activate
End If
Next
Application.ScreenUpdating = True
End Sub
This causes an error
"object defined or variable defined"
If I remove j from my paste selection, the error is gone but all my pastes are overwritten.
I can't remember what I had done before, but I basically didn't have all of the sheet activations and that caused a out of range error. Which I fix by activating a sheet, but that causes my variable to cause an error.
Edit:
Based on the comments and answer, the issue is not in how the VBA is written per se. I think it has to do with the fact that the variable j is unable to be called in the if statement. I can't figure another way to do this or how to troubleshoot that issue.