Error 1004 AutoFill - excel

The error is being thrown on the line
ThisWorkbook.Sheets("data").Range("AJ2:AM2").AutoFill Destination:=Range("AJ2:AM" & localLastRow)
It was previously cooperating, but after I corrected another error it seems that it doesn't want to play nice anymore. The source is contained within the destination. I am just not sure where the problem is coming from.
Any help would be very appreciated.
I have posted the entire macro below. It will eventually be one that is called into a main macro.
Sub FormulaUpdate()
'
' FormulaUpdate Macro
' Updates Columns AJ through AS
'
Dim localLastRow As Long
Dim sourceLastRow As Long
Dim wbName As String
Dim wbPath As String
Dim sourceSheet As Worksheet
Dim sourceRange As Range
Dim thisSheet As Worksheet
Application.ScreenUpdating = False
'sets strings from user's selection of Item Branch Report
wbPath = GetFile("Select Item Branch Report to be Used")
wbName = GetFilenameFromPath(wbPath)
Workbooks.Open(wbPath, ReadOnly:=True).Activate
'sets workseets to be referenced
Set sourceSheet = ActiveWorkbook.Sheets(1)
Set thisSheet = ThisWorkbook.Sheets("data")
'counts rows in selected item branch report for use elsewhere in macro
sourceLastRow = sourceSheet.Range("A" & Rows.Count).End(xlUp).Row
'range for use in vlookup formula, for both system leadtime and order min columns
Set sourceRange = sourceSheet.Range("B1:BG" & sourceLastRow)
'Counts rows in this workbook for use elswhere in macro
localLastRow = thisSheet.Range("A" & Rows.Count).End(xlUp).Row
'uses formulas in cells to autofill the data
thisSheet.Range("AJ2:AM2").AutoFill Destination:=thisSheet.Range("AJ2:AM" & localLastRow)
'loops through each row of both the system lead time, and the order min column, and sets the value from item branch report
For i = 2 To localLastRow
thisSheet.Range("AN" & i).Value = Application.WorksheetFunction.VLookup(thisSheet.Range("C" & i), sourceRange, 53, False)
thisSheet.Range("AP" & i).Value = Application.WorksheetFunction.VLookup(thisSheet.Range("C" & i), sourceRange, 58, False)
Application.StatusBar = "Referencing IBR: " & i & " of " & localLastRow & ": " & Format(i / localLastRow, "0%")
Next i
'uses formulas in cells to autofill the data
thisSheet.Range("AO2").AutoFill Destination:=thisSheet.Range("AO2:AO" & localLastRow)
thisSheet.Range("AQ2:AS2").AutoFill Destination:=thisSheet.Range("AQ2:AS" & localLastRow)
Workbooks(wbName).Close (False)

I mention above that is the wrong solution. Read this for background on why relying on Select and Activate methods is usually problematic, and should be avoided at all times. You have already encountered one frustrating problem -- which is that you need to keep track of which sheet is "active" and constantly update the code to have the appropriate sheet "active". This makes for sloppy code that is difficult to navigate, and more expensive to execute.
The appropriate solution would be to fully qualify your range, for example:
ThisWorkbook.Sheets("data").Range("AJ2:AM2").AutoFill Destination:=ThisWorkbook.Sheets("data").Range("AJ2:AM" & localLastRow)
Why?
Because, as you observe, an unqualified range always refers to the ActiveSheet. One solution (the wrong one) is to continuously make the right sheet Active. The right solution is to fully qualify your ranges, especially when working across multiple workbooks or worksheets.

Related

Auto fill a formula down a column but skipping already populated cells

After numerous failed attempts I am really hoping someone can with my problem. It theory what I am trying to do sounds easy enough but I have spent hours on it today with no success.
I have tried all the possible solutions from this thread but to no avail: Excel vba Autofill only empty cells
Also looked here : https://www.mrexcel.com/board/threads/macro-to-copy-cell-value-down-until-next-non-blank-cell.660608/
I am looking to autofill a formula down a column(a vlookup from another sheet) but if there is already populated cells then to skip and continue the formula in the next available blank cell. For example, in rows A2:A10, row A5 has a value in it, so the formula gets into in A2, then fills to A4, then skips A5, then continues in A6 to A10.
This below code works the first time you use it but then on the second run it debugs with a "Run-time error '1004' - No cells were found". I noticed it it putting the formula into the first cell (B2) and then debugging out.
Sub FillDownFormulaOnlyBlankCells()
Dim wb As Workbook
Dim ws1, ws2 As Worksheet
Dim rDest As Range
Set wb = ThisWorkbook
Set ws1 = Sheets("Copy From")
Set ws2 = Sheets("Copy To")
ws2.Range("A1").Formula = "=IFERROR(IF(VLOOKUP(A2,'Copy From'!A:B,2,FALSE)=0,"""",VLOOKUP(A2,'Copy From'!A:B,2,FALSE)),"""")"
Set rDest = Intersect(ActiveSheet.UsedRange, Range("B2:B300").Cells.SpecialCells(xlCellTypeBlanks))
ws2.Range("B2").Copy rDest
End Sub
Please, try the next code:
Sub FillDownFormulaOnlyBlankCells()
Dim wb As Workbook, ws1 As Worksheet, rngBlanc As Range
Set wb = ThisWorkbook
Set ws1 = wb.Sheets("Copy From")
On Error Resume Next
Set rngBlanc = ws1.Range("B2:B" & ws1.rows.count.End(xlUp).row).SpecialCells(xlCellTypeBlanks)
On Error GoTo 0
If Not rngBlanc Is Nothing Then
rngBlanc.Formula = "=IFERROR(IF(VLOOKUP(A2,'Copy From'!A:B,2,FALSE)=0,"""",VLOOKUP(A2,'Copy From'!A:B,2,FALSE)),"""")"
Else
MsgBox "No blanc rows exist in B:B column..."
End If
End Sub
After running it once and do not create any empty cell, of course there will not be any blanc cells, anymore, at a second run...
Thanks to FaneDuru for his suggestion but I actually came up with an alternative solution to my problem which I though I would post as it might help others with a similar issue.
On a separate sheet, I created 3 columns, first column is names I already have, 2nd column are the new names and the 3rd column is there to combine the first 2 columns together, then use this code to combine first 2 columns :
Sub MergeColumns()
Dim wb As Workbook
Dim ws1 As Worksheet
Dim LastRow As Long, i As Long
Set ws1 = Sheets("Your Sheet Name")
LastRow = ws1.Range("F" & Rows.Count).End(xlUp).Row
For i = 2 To LastRow
If ws1.Range("G" & i) <> "" Then
ws1.Range("I" & i) = ws1.Range("H" & i).Text & "" & ws1.Range("G" & i).Text
Else: ws1.Range("I" & i) = ws1.Range("H" & i)
End If
Next i
End Sub
Obviously changing the sheet name and columns letter to suit your requirements.

How can I remove #N/A from macro results / also multiple lookups using VBA?

I have been trying to put together a spread sheet to track down several activities using some macros I got from different places as I can’t write my own
I have 2 problems:
This macro does a lookup from one sheet and returns a value in another
Dim lngLastRow As Long
Dim wsOutput As Worksheet
Dim wsSource As Worksheet
Application.ScreenUpdating = False
Set wsOutput = Sheets("sheet 1") 'Sheet name for the following VBA to fill in
Set wsSource = Sheets("sheet 2") 'Sheet name containing completed data for VLOOKUP
lngLastRow = wsOutput.Range("A:G").Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
With wsOutput
With .Range("B2:B" & lngLastRow)
.Formula = "=VLOOKUP(C2,'" & CStr(wsSource.Name) & "'!A:G,6,FALSE)"
.Value = .Value 'Convert above formula to a value. Comment out or remove if you want the formula to remain
End With
End With
Set wsOutput = Nothing
Set wsSource = Nothing
Application.ScreenUpdating = True
End Sub
So I do a lookup from column C in sheet 1 in a table in sheet 2.
The macro does the look up and returns values in column B in sheet 1.
The macro does that for all values in column C in sheet 1.
Problem: if no value found it returns #N/A, how do I get rid of that, I don't know how to use iferror in VBA
I am using the same macro to do the same exact thing but for 2 other sheets, and its behaving differently. This time I am looking up column A in sheet 1, in sheet 2.
Problem 1: It's not working ! It only does the look up for the first value in column a and does not go through all the values in column a, as I have no clue what I am doing I tried to change the value in the “with. Range” part, it fixed the issue, but now it seems like it's trying to do the lookup for 300 cells down when there are only 17 cells with values in the lookup column
I realize what I am saying probably makes no sense, so I have attached the workbook
https://easyupload.io/eehkw8
Column C has the with.range set as C2:C, and the problem is that it does not do lookup for the entire column
Column D has the with.range set as D30:D, and the problem here is that it does the lookup even if there is no Value to lookup, it also adds #N/A
Edit adding second macro
Option Explicit
Sub update_Co1newincidents()
Dim lngLastRow As Long
Dim wsOutput As Worksheet
Dim wsSource As Worksheet
Application.ScreenUpdating = False
Set wsOutput = Sheets("New tickets") 'Sheet name for the following VBA to fill in
Set wsSource = Sheets("lookup") 'Sheet name containing completed data for VLOOKUP
lngLastRow = wsOutput.Range("C:W").Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
With wsOutput
'Formula for School Name
With .Range("C2:C" & lngLastRow)
.Formula = "=VLOOKUP(A2,'" & CStr(wsSource.Name) & "'!C:W,3,FALSE)"
.Value = .Value 'Convert above formula to a value. Comment out or remove if you want the formula to remain
End With
End With
With wsOutput
'Formula for School Name
With .Range("D2:D30" & lngLastRow)
.Formula = "=VLOOKUP(A2,'" & CStr(wsSource.Name) & "'!C:W,4,FALSE)"
.Value = .Value 'Convert above formula to a value. Comment out or remove if you want the formula to remain
End With
End With
Set wsOutput = Nothing
Set wsSource = Nothing
Application.ScreenUpdating = True
End Sub
This is a mock up of the sheet that is supposed to have to lookup output
Check for the result to be #N/A. If so, return empty string, otherwise return the lookup value.
.Formula = "=IF(ISNA(VLOOKUP(C2,'" & CStr(wsSource.Name) & "'!A:G,6,FALSE)), """", VLOOKUP(C2,'" & CStr(wsSource.Name) & "'!A:G,6,FALSE))"
Maybe the the resulting reference "'lookup'!" is not correct, while there's no space character in the sheet's name "lookup". Try removing the single quotes. Does that help?
.Formula = "=VLOOKUP(A2," & CStr(wsSource.Name) & "!C:W,3,FALSE)"
For the first formula I still have no solution. But for the second:
You say you want to use the cells D30:D for the next formula. So you should use the value in A30 I guess. Then I think the following should be changed:
.Range("D2:D30" & lngLastRow)
.Formula = "=VLOOKUP(A2,'" & CStr(wsSource.Name) & "'!C:W,4,FALSE)"
into
.Range("D30:D" & lngLastRow)
.Formula = "=VLOOKUP(A30,'" & CStr(wsSource.Name) & "'!C:W,4,FALSE)"

Vlookup in vba to find values between two worksheets

I'm trying to grab the values from a different worksheet and match them to the their sister data in my main sheet in column A but I'm having issues with getting the right results, I was thinking of going the Vlookup route but I can't quite get it to work properly. I found a funky way of getting it done but I'm trying to save just the values and not the formula itself.
This is what I tried at first
Sub matchID()
'Dim wb As Workbook
'Set wb = ActiveWorkbook
'
'With wb.Sheets("Data")
' .Range("E2:E" & .Range("A" & .Rows.Count).End(xlUp).Row).Formula = "=VLOOKUP(A2,ID!A:B,2,FALSE)"
'End With
'the above works but need to save values and not formula
It kinda works but I need that values and not the formula, my plan is to find the data I need and then save a copy of the file as a csv
I tried using a different method but I'm running into runtime error '1004'
I'm still learning VBA so I feel like I'm spinning my wheels right now.
Can someone show me what I'm doing wrong?
Sub matchID()
'this is what I'm trying to get to work but unsure if I will still end up with formula and not just values
Dim result As String
Dim sheet As Worksheet
Dim lrow As Integer
Dim i As Integer
Set sheet = ActiveWorkbook.Sheets("Data")
lrow = sheet.UsedRange.Rows(sheet.UsedRange.Rows.Count).Row
For i = 2 To lrow
result = Application.WorksheetFunction.VLookup("A2", Sheets("ID").Range("A:B"), 2, False)
Cells(i, 5).Value = result
Next
End Sub
I'm trying to lookup all IDs(in column B) from my second sheet("ID") using the values in column A from my primary sheet("Data") and then populate the all results in column E in my primary sheet to their match.
My first try kinda worked but instead of leaving just the value it leaves the formula in the cell e.g. =VLOOKUP(A2,ID!A:B,2,FALSE) when really I'm looking for just the value 8447 that it shows before clicking on the cell.
If you want to get rid of the formula, just paste as values:
Sub matchID()
Dim wb As Workbook
Set wb = ActiveWorkbook
With wb.Sheets("Data")
.Range("E2:E" & .Range("A" & .Rows.Count).End(xlUp).Row).Formula = "=VLOOKUP(A2,ID!A:B,2,FALSE)"
.Range("E2:E" & .Range("A" & .Rows.Count).End(xlUp).Row).Value = .Range("E2:E" & .Range("A" & .Rows.Count).End(xlUp).Row).Value
End With
End Sub

Is there a way to have VBA excel find a word/string of words in a file and return the value in the cell next to it?

I have a macro that looks up cells and inserts them into another sheet, however, the column and row value don't always stay the same as rows/columns are sometimes added so I can't just look up the specific cell as it can move. I would like to be able to look up the cell to the left which is unique to the file "Total Cost Per Shift" and return the cost in the column to the right. That way no matter what row or column the number is in it will return the correct information.
Here's what I have:
Option Explicit
Sub CostingInfo()
Dim wb As Workbook, sht As Worksheet, pth As String
Set sht = ActiveSheet
pth = "='[" & sht.Parent.Name & "]" & sht.Name & "'!"
Set wb = Workbooks.Open("\\FS3\Users$\UsersName\Desktop\Costing Template Test.xlsx")
With wb.Sheets("Open Quote")
.Range("B3:C3").FormulaR1C1 = pth & "R6C2" ' .Range("L3"). ????
Set cell = Range("A1:BA350").Find("Total Cost per Shift")
Range(ActiveCell, ActiveCell.Offset(0, 1)).Copy
End With
End Sub
There isn't a Range.Set property/method. It's invalid, hence why I didn't include it when I tried to fix your question to include the code from your comments.
The .Range syntax is just a continuation of the With wb.Sheets("Open Quote") statement; so .Range actually means wb.Sheets("Open Quote").Range.
When you call Range (wihout the .), you use an implicit reference to the active worksheet; Since you just opened a file, which you reference as wb, the active worksheet in it is now active, not the sheet/workbook that was active when the subroutine started.
See reference: avoiding implicit code
So, what workbook/sheet is Range(L3) supposed to be on?
You never test to see if cell is nothing then or actually use cell anywhere in your code after that.
Whenever you run into problems, you should place a Breakpoint (F9) before the problem and use F8 to step through, one line at a time.
You can mouse over the variables, add a Watch and/or use Debug.Print to display values to the immediate window (Ctrl+G).
Try,
Debug.Print .Range("L3").Parent & ".Range(" & .Range("L3").Address & ")"
Debug.Print Range("A1:BA350").Parent & ".Range(" & Range("A1:BA350").Address & ")"
Debug.Print cell.Parent & ".Range(" & cell.Address & ")"
Please edit the question to include the code that you are currently using.
(It better include Option Explicit)

In Excel trying to update rows in Sheet 1 from Sheet 2 based on a unique id found in both sheets

My question is similar to some found on this forum, but I can't quite get it to work. I have a master sheet in excel that has all my data with many columns and rows. What happens is, I receive updated data via excel sheets and need to update the master sheet based on a unique id, that is found in both sheets. Not all cells will have new data, so I would like to only update cells that have changed.
What I have found so far works, but it isn't updating all the cells. I'm new to VBA, so any help would be greatly appreciated. If this code is not what I should be doing then I'm willing to scrap it and start from scratch.
Here is the code that I found on this forum, but I can't quite get it to do what I need. I have tried changing it slightly, but to no avail. I have included the code as it appears in the forum. Any help would be greatly appreciated.
Dim sh1 As Worksheet
Dim rw2 As Range
Set sh1 = Worksheets("Sheet1")
For Each rw2 In Sheets("Sheet2").UsedRange.Rows
If Not sh1.UsedRange.Columns(1).Find(rw2.Cells(1, 2).Value,, xlValues, xlWhole) Is Nothing Then
rw2.Cells(1, 5) = sh1.UsedRange.Columns(1).Find(rw2.Cells(1, 2).Value,, xlValues, xlWhole).Offset(0, 6)
End If
Next rw2
this doesnt need a VBA macro unless its a multitude of files.
Use a formula:
=index(table,match(variables, array, 0),match(variables, array, 0))
if its the same process everytime use this is my personal code for a similar task. Just adjust the formula, worksheet, ranges.
Dim kcFormula As String
kcFormula = "=IF(OR(Table3[[#This Row],[Status]]=" & """Rejected""" & "," & "Table3[[#This Row],[Status]] =" & """Completed""" & "," & "Table3[[#This Row],[Status]]=" & """Not Implemented""" & ")," & """ """ & ",INDEX('AMLLAST'!$1:$1048576,MATCH(Table3[[#This Row],[ID]],'AMLLAST'!$E:$E,0),11))"
lastROW = ActiveSheet.UsedRange.Rows.Count
With Sheets("AML")
myRNG = "K2:" & "K" & lastROW
Sheets("AML").Range(myRNG).NumberFormat = "General"
Sheets("AML").Range(myRNG).Formula = kcFormula
End With

Resources