Excel: Macro for dragging formula down to end of column - excel

I am using a macro that creates a copy of a worksheet then renames it, deletes some columns and inserts a formula into a cell and then drags it down.
The part that drags it down does not work!
Sub filterData()
'
' filterData Macro
' Filter data
'
' Keyboard Shortcut: Ctrl+m
'
Sheets("devices").Select
Sheets("devices").Copy After:=Sheets(1)
Sheets("devices (2)").Select
Sheets("devices (2)").Name = "filterData"
ActiveWorkbook.Save
Columns("G:J").Select
Selection.Delete Shift:=xlToLeft
Columns("H:AA").Select
Selection.Delete Shift:=xlToLeft
ActiveWorkbook.Save
Range("G2").Select
ActiveCell.FormulaR1C1 = _
"=LEFT(devices!RC[4],IFERROR(SEARCH("""""""",devices!RC[4]),SEARCH(""-"",devices!RC[4]))-1)"
ActiveWorkbook.Save
Range("G2").Select
Selection.AutoFill Destination:=Range("Table122[Display]")
Range("Table122[Display]").Select
End Sub
As you can see, the part that drags the formula down to last populated cell is not working!!!
Update
I have added the following to the code as well and it still does not work;
lastrow = Range("G2").End(xlUp).Row --new line
Range("G2").Select
ActiveCell.FormulaR1C1 = _
"=LEFT(devices!RC[4],IFERROR(SEARCH("""""""",devices!RC[4]),SEARCH(""-"",devices!RC[4]))-1)"
Range("G2").Select
Selection.AutoFill Destination:=Range("G2:G" & lastrow) --new line

Since it's a Table (VBA ListObject) you can fill in the whole ListColumn at once:
ActiveCell.ListObject.ListColumns("Display").DataBodyRange.Formula = _
"=LEFT(devices!RC[4],IFERROR(SEARCH("""""""",devices!RC[4]),SEARCH(""-"",devices!RC[4]))-1)"
Also, note that you can get rid of the Select statements generated by the Macro Recorder. For example:
Columns("G:J").Select
Selection.Delete Shift:=xlToLeft
can be just:
Columns("G:J").Delete Shift:=xlToLeft
And one final tip is to fully qualify ranges, e.g.:
Worksheets("filterData").Columns("G:J").Delete Shift:=xlToLeft
I'll stop now since you already accepted this answer. Except to say I do like the animation!

The problem with your macro is probably this line:
Range("Table122[Display]").Select
You are trying to auto-fill the Display column, including the Header row, which it probably doesn't like. Try it like this instead:
Range("Table122[[#Data],[Display]]").Select

For a simple solution to macro for dragging formula down to dynamic row count:
You can also use the previous column for a reference of how many rows you want to drag the formula.
Generic: Range("B2:B" & Range("A65000").End(xlUp).Row).FormulaR1C1 = "{=formulahere}"
So in your case it would look something like:
Range("G2:G" & Range("F65000").End(xlUp).Row).FormulaR1C1 = "=LEFT(devices!RC[4],IFERROR(SEARCH("""""""",devices!RC[4]),SEARCH(""-"",devices!RC[4]))-1)"

Related

Delete special cells base on criteria such as blanks or highlights

I have some reports that need to be modified by deleting some specific cells such as blank cells or highlights in the background
I have tried to record Macro to delete the special cells. however, the position will be changed regarding the difference of the row numbers. I could not specify the certain position of each cell.
Here is my data
here is what I expect to get
Here is my recorded Macro
Sub Macro1()
'Macro1 Macro
Range("B4").Select
Selection.Delete Shift:=xlToLeft
Range("B16").Select
Selection.Delete Shift:=xlUp
Range("B24").Select
Selection.Delete Shift:=xlToLeft
ActiveWindow.SmallScroll Down:=12
Range("B30").Select
Selection.Delete Shift:=xlToLeft
End Sub
You can try the below, change the columns you want to delete
you can change criteria by using xlcelltype XXXX
for xample of xlcelltype
Dim b As Range
For Each b In [B1:B2000].SpecialCells(xlCellTypeBlanks, 1).Offset(0, -1).Areas
b.Delete Shift:=xlToLeft
Next
Cells.Select
Cells.EntireColumn.Autofit
End Sub
Go in advance to proper click on chosen cells and pick the Delete from the right-clicking menu. And then take a look at the Entire row choice in the popping up Delete dialog box, and click on the OK button. Now you will see all the cells containing the sure fee are removed.

Excel 2013 VBA select cell P for every row that has data in column A

Working on a function to put the filename in a specific column (P) of a file. I've got this running if I specify the cells to put the filename in (e.g. P1:P5).
However, I want to get this to run in the P column, but for all rows that have data in the A column.
I know I could do it for just the whole P column, but i dont want it to run on empty rows (they're of no use)
Code I have so far:
Sub Save_files()
Cells.Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Rows("1:3").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlUp
Range("P2").Select
ActiveCell.FormulaR1C1 = "=CELL(""filename"")"
Range("P2").Select
Selection.Copy
Range("p1:p5").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Range("D4").Select
End Sub
I want to replace Range("p1:p5").Select with something that selects every P cell that is on a row with data in A of the same row.
Things to note:
Column A will always have data
Columns B through to O may or may not have data
Thanks in advance!
I changed:
Range("p1:p5").Select
to:
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
Range("p1:p" & LastRow).Select

VBA Macro: Paste underneath last cell in column with variable range

Title isn't the best so here a an overview.
I'm using VBA to copy select columns from one workbook to another, as what will be part of a larger automated program.
On the Workbook I am copying from, there are different sheets containing a "Stock Number" column. When pasting into my other workbook, I am trying to get these columns to merge into 1 single column (pasting below the last entry from the first sheet and so on).
Here is my current code:
Sub import_adam_article()
Windows( _
"copyfrom.xlsx" _
).Activate
Columns("F:G").Select
Selection.Copy
Windows("pasteinto.xlsx").Activate
Columns("A:A").Select
ActiveSheet.Paste
Windows( _
"copyfrom.xlsx" _
).Activate
Columns("N:N").Select
Application.CutCopyMode = False
Selection.Copy
Windows("pasteinto.xlsx").Activate
Columns("C:C").Select
ActiveSheet.Paste
Rows("1:1").Select
Selection.Delete Shift:=xlUp
NextRow = Range("A1").End(xlDown).Row + 1
Windows( _
"copyfrom.xlsx" _
).Activate
Columns("F:G").Select
Selection.Copy
Windows("pasteinto.xlsx").Activate
Range("A" & (NextRow)).Select
ActiveSheet.Paste
[A:C].Select
With Selection
.NumberFormat = "General"
.Value = .Value
End With
End Sub
The difficulty is that the amount of Stock Numbers will change every new file that comes through, so it needs to be able to adjust to varying amounts.
I can't seem to find a way to make it work and I've tried searching for answers elsewhere.
EDIT: The current issue with the code that it is selecting the next empty row to paste into, but only that cell, not a variable length down as required by the copyfrom column.

Blank/ empty columns are being printed because they were used and now are not

there are lot of people that have asked and answered a similar question but none of the suggestions are working for me. I have a sheet where the data ends in column 'S'. However, when I go to print it the preview shows an extra 8 columns on the right. When I apply a filter these same columns also get the filter added, even though they are empty (I checked if the cells were empty with =ISBLANK() and it returned true). If I highlight and delete the 8 columns, there is no difference in the print preview, however it does delete the filter.
I think I have just figured out why this is happening but I still do not know how to fix it. The data in the sheet that is causing the problems is copied from another workbook. The original data has an extra 8 columns within it. But I run a macro which formats everything and deletes these columns as they are either blank or unneeded.
So I think for some reason when I delete the 8 columns, 8 columns at the right most side of the sheet are added?
Does anyone know how I can fix this? Or what I should change to stop this happening.
Heres a snippet of one of the macros. This is the only piece of code that is deleting any columns.
Range("C:C").Select
Selection.Delete Shift:=xlToLeft
Range("G:G").Select
Selection.Delete Shift:=xlToLeft
Range("H:H").Select
Selection.Delete Shift:=xlToLeft
Range("K:L").Select
Selection.Delete Shift:=xlToLeft
Range("L:M").Select
Selection.Delete Shift:=xlToLeft
Range("O:O").Select
Selection.Delete Shift:=xlToLeft
Range("A:A").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("C:C").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("C1").Select
ActiveCell.FormulaR1C1 = "Crew"
Range("A1").Select
ActiveCell.FormulaR1C1 = "Yes/ No"
Range("G1").Select
ActiveCell.FormulaR1C1 = "RPC"
Range("H1").Select
ActiveCell.FormulaR1C1 = "SCE"
Range("M1").Select
ActiveCell.FormulaR1C1 = "Craft"
Range("O1").Select
ActiveCell.FormulaR1C1 = "Frequency"
Range("P1").Select
ActiveCell.FormulaR1C1 = "Unit"
Range("S1").Select
ActiveCell.FormulaR1C1 = "Duration"
See related
Excel resetting “UsedRange” and Excel VBA usedRange Property and reset usedRange
I seem to recall that the last cell in the UsedRange is cached. Meaning if you had typed something in column X (furthest right column in use), went about your business, then later cleared column X... then the UsedRange still goes out to column X despite there not being any filled in cells. You'd have to either Save the file, or run some VBA against the UsedRange in order to clear the cached setting.
I basically solved or did a work around for this. I wrote a piece of code that can go at the end of another macro or can be used as its own macro. It just sets the print area to be whatever size the used range is.
Sub printPrep()
Dim rng As Range
Set rng = ActiveSheet.UsedRange
With ActiveSheet
.PageSetup.PrintArea = .UsedRange.Address
Debug.Print (rng.Address)
End With
End Sub

How can I remove the rows that matches from one Excel column with another Excel file? With VBA

Hi and thanks for your help.
I've two Excel files, lets call them Excel 1 (active one), and Excel 2 (which I just need to compare if there's duplicates).
I want to remove the matches from Excel 1 that are found in Excel 2. Only deleting the matches from Excel 1, and keeping the Excel 2 intact.
I normally do this process with a Vlookup then delete the matches.
[Example][1]: =VLOOKUP(C2,'[End Use Screening Log.xlsb]EUS Log'!$A:$A,1,0))
This is the macro code produced after the Vlookup:
Sub Testing()
'
' Testing Macro
'
'
Workbooks.Open Filename:= _
"Z:\Customer Screening\End User Screening Log\End Use Screening Log.xlsb"
Windows("Copy of WW33 TEST .xlsm").Activate
Range("G2").Select
ActiveCell.FormulaR1C1 = _
"=VLOOKUP(RC[-4],'[End Use Screening Log.xlsb]EUS Log'!C1,1,0)"
Range("G2").Select
Selection.AutoFill Destination:=Range("G2:G16")
Range("G2:G16").Select
Range("G1").Select
Selection.AutoFilter
ActiveSheet.Range("$A$1:$Q$16").AutoFilter Field:=7, Criteria1:=Array( _
"4997466", "6392634", "9026175", "9362935", "9363654", "9369599", "9370171"), _
Operator:=xlFilterValues
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Rows("2:2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Delete Shift:=xlUp
Range("E15").Select
Selection.AutoFilter
Range("G2:G9").Select
Selection.ClearContents
Range("Q2").Select
End Sub
However, I'm trying to automatize the process to do it just with one click.
I want to compare column C from Excel 1 against column A from Excel 2.
I guess I'd need to do it with a VBA, because I've tried it recording the macro but doesn't work properly.
Any ideas how to make this possible?
Maria
I created a very crude code that might just work for your needs. I do not know what your worksheets look like and what your exact needs are but I just assumed you're just matching each cell of column C of Excel 1 to the values at column A of Excel 2, and if there is a match, the cell at row C of Excel 1 will be deleted.
Excel1 Workbook:
Excel2 Workbook:
Code:
Sub Macro1()
Start = 2
'Change path to your excel's file name
'This will open your 2nd excel file so that you won't have to open it evertime. Delete when not needed
Workbooks.Open ("C:\Users\Pops\Desktop\Excel2.xlsm")
'The deletion of the row will mess up with the For-Next loops so I included a GoTo so this is where it will end up
ReLoop:
'Counts how many rows are in your worksheets
Total_rows_Excel1 = Workbooks("Excel1.xlsm").Worksheets("Sheet1").Range("C" & Rows.Count).End(xlUp).Row
Total_rows_Excel2 = Workbooks("Excel2.xlsm").Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
'Loops on all the rows on your worksheet
For i = Start To Total_rows_Excel1
For j = 2 To Total_rows_Excel2
If Workbooks("Excel1.xlsm").Worksheets("Sheet1").Range("C" & i) = Workbooks("Excel2").Worksheets("Sheet1").Range("A" & j) Then
Workbooks("Excel1").Worksheets("Sheet1").Rows(i).Delete Shift:=xlUp 'Deletes the rows in Excel1 that have a match from Excel2
Start = i 'This will let the loop to start at the last row it stopped when it loops again so it's less computationally taxing
GoTo ReLoop
End If
Next j
Next i
End Sub
So at the click of a button, all the matches in Excel 1's column C to Excel 2's column A will be removed.
Result:

Resources