I am trying to come up with a macro that checks if any numeral value exists in a cell. If a numeral value exists, copy a portion of that row and paste it into another worksheet within the same spreadsheet.
Sheet1 is the sheet that has all my data in it. I am trying to look in column R if there is any values in it. If it does, copy that cell and the four adjacent cells to the left of it and paste it into Sheet2.
This is what I have come up with so far based on mish-mashing other people's code though it only does a part of what I want. It just copies part of a row then pastes it into another worksheet but it does not check column R for a value first. It just copies and pastes regardless and does not move onto the next row once it has done that. I need it to continue onto the next row to continue looking:
Sub Paste_Value_Test()
Dim c As Range
Dim IRow As Long, lastrow As Long
Dim rSource As Range
Dim wsI As Worksheet, wsO As Worksheet
On Error GoTo Whoa
'~~> Sheet Where values needs to be checked
Set wsI = ThisWorkbook.Sheets("Sheet1")
'~~> Output sheet
Set wsO = ThisWorkbook.Sheets("Sheet2")
Application.ScreenUpdating = False
With wsI
'~~> Find Last Row which has data in Col O to R
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastrow = .Columns("O:R").Find(What:="*", _
After:=.Range("O3"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
lastrow = 1
End If
'~~> Set you input range
Set rSource = .Range("R" & lastrow)
'~~> Search for the cell which has "L" and then copy it across to sheet1
For Each c In rSource
Debug.Print cValue
If c.Value > "0" Then
.Range("O" & c.Row & ":R" & c.Row).Copy
wsO.Cells(5 + IRow, 12).PasteSpecial Paste:=xlPasteValues
IRow = IRow + 1
End If
Next
End With
LetsContinue:
Application.ScreenUpdating = True
Application.CutCopyMode = False
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
Below is some code which hopefully achieves what I think you are trying to do. I have included comments throughout stating what I changed:
Sub Paste_Value_Test()
Dim c As Range
Dim IRow As Long, lastrow As Long
Dim rSource As Range
Dim wsI As Worksheet, wsO As Worksheet
On Error GoTo Whoa
'~~> Sheet Where values needs to be checked
Set wsI = ThisWorkbook.Sheets("Sheet1")
'~~> Output sheet
Set wsO = ThisWorkbook.Sheets("Sheet2")
Application.ScreenUpdating = False
With wsI
'~~> Find Last Row which has data in Col O to R
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
'You specified "After" to be cell O3. This means a match will
' occur on row 2 if cell R2 (or O2 or P2) has something in it
' because cell R2 is the cell "after" O3 when
' "SearchDirection:=xlPrevious"
' After:=.Range("O3"), _
lastrow = .Columns("O:R").Find(What:="*", _
After:=.Range("O1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
lastrow = 1
End If
'This was only referring to the single cell in column R on the
' last row (in columns O:R)
'Set rSource = .Range("R" & lastrow)
'Create a range referring to everything in column R, from row 1
' down to the "last row"
Set rSource = .Range("R1:R" & lastrow)
'This comment doesn't seem to reflect what the code was doing, or what the
'question said
'~~> Search for the cell which has "L" and then copy it across to sheet1
For Each c In rSource
'This is printing the variable "cValue", which has never been set
'Debug.Print cValue
'It was probably meant to be
Debug.Print c.Value
'This was testing whether the value in the cell was
' greater than the string "0"
'So the following values would be > "0"
' ABC
' 54
' ;asd
'And the following values would not be > "0"
' (ABC)
' $523 (assuming that was as text, and not just 523 formatted as currency)
'If c.Value > "0" Then
'I suspect you are trying to test whether the cell is numeric
' and greater than 0
If IsNumeric(c.Value) Then
If c.Value > 0 Then
'This is only copying the cell and the *three* cells
' to the left of it
'.Range("O" & c.Row & ":R" & c.Row).Copy
'This will copy the cell and the *four* cells
' to the left of it
'.Range("N" & c.Row & ":R" & c.Row).Copy
'wsO.Cells(5 + IRow, 12).PasteSpecial Paste:=xlPasteValues
'But this would avoid the use of copy/paste
wsO.Cells(5 + IRow, 12).Resize(1, 5).Value = _
.Range("N" & c.Row & ":R" & c.Row).Value
IRow = IRow + 1
End If
End If
Next
End With
LetsContinue:
Application.ScreenUpdating = True
Application.CutCopyMode = False
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
Related
I have this Macro which essentially uses two sheets - sheet2 updates sheet1 and then kills the second worksheet.
I noticed that when it comes to one part of the macro (delete row which has "Delete" in column A in worksheet 1) it doesn't appear to work if I run the Macro from worksheet 2. If I run it from Sheet 1 is works without a problem.
This is the full code, just in case you need to look at it - I'll highlight the part that I'm having trouble with next.:
Public Sub Cable_Load_full()
'~~> Copy New Accounts from worksheet2
Dim ws1 As Worksheet, ws2 As Worksheet
Dim bottomL As Integer
Dim x As Integer
Dim c As Range
Dim i As Long, J As Long, LastCol As Long
Dim ws1LR As Long, ws2LR As Long
Dim ws1Rng As Range, aCell As Range
Dim SearchString
Set ws1 = Sheets("CableSocials")
Set ws2 = Sheets("CableRevised")
bottomL = ws2.Range("A" & Rows.Count).End(xlUp).Row: x = 1
x = ws1.Range("A" & Rows.Count).End(xlUp).Row
x = x + 1
For Each c In ws2.Range("A1:A" & bottomL)
If c.Value = "New" Then
c.EntireRow.Copy ws1.Range("A" & x)
x = x + 1
End If
Next c
'~~> Assuming that ID is in Col B
'~~> Get last row in Col B in Sheet1
ws1LR = ws1.Range("B" & Rows.Count).End(xlUp).Row
'~~> Set the Search Range
Set ws1Rng = ws1.Range("B1:B" & ws1LR)
'~~> Adding Revise Column to worksheet 1
ws1.Columns("A:A").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("A1").Value = "Revise"
Set ws2 = Sheets("CableRevised")
'~~> Turn off Filter
ws2.AutoFilterMode = False
'~~> Get last row in Col A in Sheet2
ws2LR = ws2.Range("B" & Rows.Count).End(xlUp).Row
'~~> Loop through the range in Sheet 2 to match it with the range in Sheet1
For i = 1 To ws2LR
SearchString = ws2.Range("B" & i).Value
'~~> Search for the ID
Set aCell = ws1Rng.Find(What:=SearchString, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
'~~> If found
If Not aCell Is Nothing Then
'~~> Append values
ws1.Cells(aCell.Row, 1).Value = ws2.Cells(i, 1).Value
ws1.Cells(aCell.Row, 3).Value = ws2.Cells(i, 2).Value
ws1.Cells(aCell.Row, 19).Value = ws2.Cells(i, 18).Value
ws1.Cells(aCell.Row, 20).Value = ws2.Cells(i, 19).Value
End If
Next i
'~~> Delete the accounts that need to be deleted
ws1.AutoFilterMode = False
With Range("A1", Range("A" & Rows.Count).End(xlUp))
.AutoFilter 1, "Delete"
On Error Resume Next
.Offset(1).SpecialCells(12).EntireRow.Delete
End With
ws1.AutoFilterMode = False
'~~> Removing New from Column B
ws1.Columns("B").Replace What:="New", _
Replacement:="", _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
MatchCase:=False, _
SearchFormat:=False, _
ReplaceFormat:=False
ws1.Columns("A").EntireColumn.Delete
Call SheetKiller
End Sub
Sub SheetKiller()
Dim s As Worksheet, t As String
Dim i As Long, K As Long
K = Sheets.Count
For i = K To 1 Step -1
t = Sheets(i).Name
If t = "CableRevised" Then
Application.DisplayAlerts = False
Sheets(i).Delete
Application.DisplayAlerts = True
End If
Next i
End Sub
So the part that only works when I run the Macro from Sheet1 is:
'~~> Delete the accounts that need to be deleted
ws1.AutoFilterMode = False
With Range("A1", Range("A" & Rows.Count).End(xlUp))
.AutoFilter 1, "Delete"
On Error Resume Next
.Offset(1).SpecialCells(12).EntireRow.Delete
End With
ws1.AutoFilterMode = False
I'm not sure why - is it acting as if it will only delete the rows from the ActiveSheet (which I guess would be the Sheet I run the Macro from?) ? Is it possible to make it work even if I run the Macro from Sheet2?
Thanks for any help you provide!
You need to explicitly refer to ranges on ws1. As written, your code is looking for ranges on the active sheet.
Try this:
'~~> Delete the accounts that need to be deleted
ws1.AutoFilterMode = False
With ws1.Range("A1", ws1.Range("A" & ws1.Rows.Count).End(xlUp))
.AutoFilter 1, "Delete"
On Error Resume Next
.Offset(1).SpecialCells(12).EntireRow.Delete
End With
ws1.AutoFilterMode = False
I hope you can help. I have a piece of code and what it does is it allows a user to open a dialog box then select an excel file. This selected excel file then gets formatted, it then puts a filter on the 8th column it then creates new excel sheets copies and pastes the information to these sheets and names the new sheet based on the data in the 8th column.
So I end up with an excel workbook like the one you see in Pic 1
As you can see in PIC 1 I have the original sheet "Searchcaseresults" and the sheets "In Progress" and "Complete"
What I am trying to achieve is code that goes if in this workbook there is a sheet called "In Progress" then execute code on that sheet if there is not a sheet called "in Progress then Msg Box "no In progress sheet found" or do nothing and if there is a sheet in this workbook called "Complete" then execute code and if there is no sheet called Complete in this workbook then Msg Box "no complete sheet found" or do nothing.
At the moment I have not entered the Complete code because I getting Run time error 424 on line If Worksheet.Name = "In Progress" Then and I would like to solve this first.
The area of code that is giving me trouble is here
''''Trouble code
Dim wb As Workbook
With wb
If Worksheet.Name = "In Progress" Then
Columns.AutoFit '<--|Auto fits Columns
Range("E1").Value = "# days open" '<--|Enters Value
Rows("2:2500").RowHeight = 25 '<--|Adjusts Row Height
Dim LastRow As Long, i As Long
With Worksheets("In Progress")
LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row '<--|Looks for the last non empty cell in C
For i = 2 To LastRow
.Range("E" & i).Value = DateDiff("d", .Range("D" & i).Value, Date) '<--|As long as C is not blank it will subtract todays date from C and populate in D
Next i
End With
Else
MsgBox "In Progress Sheet not Found"
End If
End With
and my code in its entirety is below PIC 1
As always any and all help is greatly appreciated.
PIC 1
TOTAL CODE
Sub Open_Workbook_Dialog()
Dim my_FileName As Variant
MsgBox "Pick your TOV file" '<--| txt box for prompt to pick a file
my_FileName = Application.GetOpenFilename(FileFilter:="Excel Files,*.xl*;*.xm*") '<--| Opens the file window to allow selection
If my_FileName <> False Then
Workbooks.Open Filename:=my_FileName
Call Sample '<--|Calls the sample Code and executes
End If
End Sub
Public Sub Sample()
Dim ws As Worksheet
Dim aCell As Range, Rng As Range
Dim col As Long, lRow As Long
Dim colName As String
Set ws = ActiveWorkbook.Sheets(1)
With ws
Rows("1:5").Delete
End With
With ws
Set aCell = .Range("A1:AH50").Find(What:="Issue No", LookIn:=xlValues, LookAt:=xlWhole, _
MatchCase:=False, SearchFormat:=False)
'~~> If Found
If Not aCell Is Nothing Then
'~~> Cut the entire column
aCell.EntireColumn.Cut
'~~> Insert the column here
Columns("A:A").Insert Shift:=xlToRight
Else
MsgBox "Country Not Found"
End If
End With
With ws
Set aCell = .Range("A1:AH50").Find(What:="NPI Number", LookIn:=xlValues, LookAt:=xlWhole, _
MatchCase:=False, SearchFormat:=False)
'~~> If Found
If Not aCell Is Nothing Then
'~~> Cut the entire column
aCell.EntireColumn.Cut
'~~> Insert the column here
Columns("J:J").Insert Shift:=xlToRight
Else
MsgBox "Country Not Found"
End If
End With
With ws
Range("A1").EntireColumn.Insert
Range("A1").Value = "Market"
Cells(1, 2).Copy
Cells(1, 1).PasteSpecial (xlPasteFormats)
Application.CutCopyMode = False
Columns.AutoFit
Range("O:AH").EntireColumn.Delete
Rows("2:2500").RowHeight = 25
End With
With ws
lRow = .Range("B" & .Rows.Count).End(xlUp).Row
.Range("A2:A" & lRow).Formula = "=If(B2<>"""",""Enter Your Country Here"","""")"
.Range("A2:A" & lRow).Value = .Range("A2:A" & lRow).Value
.Range("A2:A" & lRow).Interior.ColorIndex = 39
End With
Dim rCountry As Range, helpCol As Range
With ws '<--| refer to data worksheet
With .UsedRange
Set helpCol = .Resize(1, 1).Offset(, .Columns.Count) '<--| get a "helper" column just at the right of used range, it'll be used to store unique country names in
End With
With .Range("A1:Q" & .Cells(.Rows.Count, 1).End(xlUp).Row) '<--| refer to its columns "A:Q" from row 1 to last non empty row of column "A"
.Columns(8).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=helpCol, Unique:=True '<-- call AdvancedFilter on 7th column of the referenced range and store its unique values in "helper" column
Set helpCol = Range(helpCol.Offset(1), helpCol.End(xlDown)) '<--| set range with unique names in (skip header row)
For Each rCountry In helpCol '<--| iterate over unique country names range (skip header row)
.AutoFilter 8, rCountry.Value2 '<--| filter data on country field (7th column) with current unique country name
If Application.WorksheetFunction.Subtotal(103, .Cells.Resize(, 1)) > 1 Then '<--| if any cell other than header ones has been filtered...
Worksheets.Add Worksheets(Worksheets.Count) '<--... add new sheet
ActiveSheet.Name = rCountry.Value2 '<--... rename it
.SpecialCells(xlCellTypeVisible).Copy ActiveSheet.Range("A1") 'copy data for country under header
End If
Next
End With
.AutoFilterMode = False '<--| remove autofilter and show all rows back
End With
helpCol.Offset(-1).End(xlDown).EntireColumn.Delete '<--| clear helper column (header included)
''''Trouble code
Dim wb As Workbook
With wb
If Worksheet.Name = "In Progress" Then
Columns.AutoFit '<--|Auto fits Columns
Range("E1").Value = "# days open" '<--|Enters Value
Rows("2:2500").RowHeight = 25 '<--|Adjusts Row Height
Dim LastRow As Long, i As Long
With Worksheets("In Progress")
LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row '<--|Looks for the last non empty cell in C
For i = 2 To LastRow
.Range("E" & i).Value = DateDiff("d", .Range("D" & i).Value, Date) '<--|As long as C is not blank it will subtract todays date from C and populate in D
Next i
End With
Else
MsgBox "In Progress Sheet not Found"
End If
End With
End Sub
I have simplified the code but I am still getting an error the error I am now getting is run-time error 91
The run-time error 91 is happening on line If worksheet.name = "In Progress" Then
The code I am trying to get to work is below
Public Sub Msg_Box()
Dim wb As Workbook
Set wb = ThisWorkbook
Dim worksheet As worksheet
With wb
If worksheet.name = "In Progress" Then
MsgBox "found"
Else
MsgBox "not found"
End If
End With
End Sub
Private Function SheetExists(ByVal SheetName as String, ByRef InWorkbook As Workbook) As Boolean
On Error Resume Next
Debug.Print InWorkbook.Worksheets(SheetName).Name
If Err.Number = 0 Then SheetExists = True Else SheetExists = False
End Function
Use this function to test if the workbook opened has a sheet named "In Progress". For example:
If SheetExists("In Progress", wb) Then
'Some code to execute
Else
MsgBox "No In Progress sheet found"
End If
So what i think was happening is that I was not activating the the sheet name "In Progress"
The code that finally worked for me is below. Again I would to thank all those who assisted, and I hope this helps another Excel enthusiast with a solution
'''''Trouble code
Dim wb As Workbook
''Dim ws As Worksheet <-- this was dotted out as it is declared earlier in the code
Set wb = ActiveWorkbook
For Each ws In wb.Worksheets
If ws.Name = "In Progress" Then
Worksheets("In Progress").Activate ''<-- this what I believe need to happen activate the sheet
Columns.AutoFit '<--|Auto fits Columns
Range("E1").Value = "# days open" '<--|Enters Value
Rows("2:2500").RowHeight = 25 '<--|Adjusts Row Height
With Worksheets("In Progress")
LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row '<--|Looks for the last non empty cell in C
For i = 2 To LastRow
.Range("E" & i).Value = DateDiff("d", .Range("D" & i).Value, Date) '<--|As long as C is not blank it will subtract todays date from C and populate in D
Next i
End With
Columns(5).NumberFormat = "0"
Range("P:P").EntireColumn.Delete
End If
Next
I want to copy the last row that that has formulas from a worksheet to the next row down and then value out the row that I just copied down. For example I have formulas in columns A through W and my current last row is 10 and I want to copy row 10 to row 11 and then value out row 10. Trying to get vba code to automate process. Any help appreciated.
This should get you started in the right direction:
Sub appendToEnd()
Dim myLastCell As Range
Set myLastCell = LastCell(Worksheets("Sheet1").Range("A:W"))
Dim lastCellCoords As String: lastCellCoords = "A" & myLastCell.Row & ":W" & myLastCell.Row
Dim firstEmptyRow As Integer: firstEmptyRow = myLastCell.Row + 1
Dim firstEmptyCoords As String: firstEmptyCoords = "A" & firstEmptyRow & ":W" & firstEmptyRow
If Not myLastCell Is Nothing Then
' Now Copy the range:
Worksheets("Sheet1").Range(lastCellCoords).Copy
' And paste to first empty row
Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
Application.CutCopyMode = False
Else
MsgBox ("There is no data in specified range")
End If
End Sub
Function LastCell(r As Range) As Range
'
' Note "&" denotes a long value; "%" denotes an integer value
Dim LastRow&, lastCol%
On Error Resume Next
With r
' Find the last real row
LastRow& = .Cells.Find(What:="*", _
SearchDirection:=xlPrevious, _
SearchOrder:=xlByRows).Row
' Find the last real column
lastCol% = .Cells.Find(What:="*", _
SearchDirection:=xlPrevious, _
SearchOrder:=xlByColumns).Column
End With
' Finally, initialize a Range object variable for
' the last populated row.
Set LastCell = r.Cells(LastRow&, lastCol%)
End Function
I am trying to create some code that looks through a range of cells and will copy and paste the cells that meet a specific parameter to a different location in the workbook.
I would like to copy anything with the letter L from "sheet5" and copy a specific range to "sheet1"
I must have something wrong with the loop part of the code because only the top of the cell range is being copied. I would like the pasting to start at row 5 and continue moving downward. Does this mean I correctly put the IRow = IRow + 1 below the paste function?
Sub Paste_Value_Test()
Dim c As Range
Dim IRow As Long
Dim rDestination As Excel.Range
Application.ScreenUpdating = False
Sheets("sheet5").Activate
For Each c In Sheets("sheet5").Range("b2", Range("N65536").End(xlUp))
If c.Value = "L" Then
Sheets("sheet5").Cells(c.Row, 2).Copy
Set rDestination = Worksheets("sheet5").Cells(5 + IRow, 12)
rDestination.Select
Selection.PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, _
SkipBlanks:=False, _
Transpose:=False
IRow = IRow + 1
End If
Next c
End Sub
I really appreciate any help on this. I'm relatively new to VBA and am going to start seriously digging in.
Is this what you are trying by any chance? I have commented the code so you shouldn't have any problem understanding it.
Sub Paste_Value_Test()
Dim c As Range
Dim IRow As Long, lastrow As Long
Dim rSource As Range
Dim wsI As Worksheet, wsO As Worksheet
On Error GoTo Whoa
'~~> Sheet Where "L" needs to be checked
Set wsI = ThisWorkbook.Sheets("Sheet5")
'~~> Output sheet
Set wsO = ThisWorkbook.Sheets("Sheet1")
Application.ScreenUpdating = False
With wsI
'~~> Find Last Row which has data in Col B to N
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastrow = .Columns("B:N").Find(What:="*", _
After:=.Range("B1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
lastrow = 1
End If
'~~> Set you input range
Set rSource = .Range("B2:N" & lastrow)
'~~> Search for the cell which has "L" and then copy it across to sheet1
For Each c In rSource
If c.Value = "L" Then
.Cells(c.Row, 2).Copy
wsO.Cells(5 + IRow, 12).PasteSpecial Paste:=xlPasteValues
IRow = IRow + 1
End If
Next
End With
LetsContinue:
Application.ScreenUpdating = True
Application.CutCopyMode = False
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
This is a separate question stemming from this post: How to use the filename of an excel file to change a column of cells?
I noticed that in the last post's code it was referencing specific cells (J2,K2). However when using the code, I came into an error when the columns changed. So now I am seeking a way to modify the below code to use the names of the header columns to populate the 2nd column instead of referencing specific cells. I think the only line that really needs adjusting is the myRng line, but I will provide all the code I am trying for reference.
In case you don't read the other post, I will describe the issue. I am trying to fill in the 2nd column (name+type) based on the "name" column and the filename. When I was referencing the K or J row in the code, everything was working fine, but when I load a different file and the columns positions have changed, everything gets messed up.
I need to populate the 2nd column (name+type) to be the exactly the same number or rows as the 1st column (name) which is why I am using the Range ("K2:K" & lastCell) formula.
Is there a way to do this?
Current Attempted VBA code:
' Insert Column after name and then rename it name+type
Rows(1).Find("name").Offset(0, 1).EntireColumn.Insert
Rows(1).Find("name").Offset(0, 1).FormulaR1C1 = "name+type"
Dim myRng As Range
Dim lastCell As Long
Dim myOtherRange As Range
Dim column2Range As Range
myOtherRange = Rows(1).Find("name")
column2Range = Rows(1).Find("name+type")
lastCell = Range(myOtherRange).End(xlDown).Row
Set myRng = Range("K2:K" & lastCell)
myOtherRange.FormulaR2C1 = "=LEFT(MID(CELL(""filename""),SEARCH(""["",CELL(""filename""))+1, SEARCH(""]"",CELL(""filename""))-SEARCH(""["",CELL(""filename""))-1),5)&RC[-1]"
myOtherRange.FormulaR2C1.Select
Selection.Copy
myRng.Select
ActiveSheet.Paste
First Draft VBA code:
' Insert Column after name and then rename it name+type
Rows(1).Find("name").Offset(0, 1).EntireColumn.Insert
Rows(1).Find("name").Offset(0, 1).FormulaR1C1 = "name+type"
'Add the contents to the name+type column
Range("K2").Select
ActiveCell.FormulaR1C1 = "=LEFT(MID(CELL(""filename"",RC[-1]),SEARCH(""["",CELL(""filename"",RC[-1]))+1,SEARCH(""]"",CELL(""filename"",RC[-1]))-SEARCH(""["",CELL(""filename"",RC[-1]))-1),5)&RC[-1]"
Range("K2").Select
Selection.Copy
Range("K2:K8294").Select
ActiveSheet.Paste
#Scott or Siddharth Rout probably =) – Jonny 11 hours ago
I would never recommend this :) SO is full of experts who can assist you. Why do you want to limit the help that you can get? ;)
Is this what you are trying?
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long, aCol As Long
Dim aCell As Range
Set ws = Sheets("Sheet1") '<~~ Change this to the relevant sheet name
With ws
Set aCell = .Rows(1).Find("Name")
'~~> Check if the column with "name" is found
If Not aCell Is Nothing Then
aCol = aCell.Column
.Columns(aCol + 1).EntireColumn.Insert
.Cells(1, aCol + 1).Value = "Name+Type"
.Activate
.Rows(1).Select
With ActiveWindow
.SplitColumn = 0
.SplitRow = 1
.FreezePanes = True
End With
'~~> Get lastrow of Col which has "name"
lRow = .Range(Split(.Cells(, aCol).Address, "$")(1) & .Rows.Count).End(xlUp).Row
ThisWorkbook.Save
'~~> Add the formula to all the cells in 1 go.
.Range(Split(.Cells(, aCol + 1).Address, "$")(1) & "2:" & _
Split(.Cells(, aCol + 1).Address, "$")(1) & lRow).Formula = _
"=LEFT(MID(CELL(""filename"",RC[-1]),SEARCH(""["",CELL(""filename"",RC[-1]))+1," & _
"SEARCH(""]"",CELL(""filename"",RC[-1]))-SEARCH(""["",CELL(""filename"",RC[-1]))-1),5)&RC[-1]"
.Columns("A:AK").Columns.AutoFit
Else
MsgBox "Name Column Not Found"
End If
End With
End Sub
After modifying the code provided by Siddharth, this is the final code that worked for me. The save feature needed to also remove a format and the Formula to search and add the filename to the cells did not work without this edit. I also had to change the sheet to the activeSheet, because it was constantly changing. Here is the code:
Sub Naming()
Dim LR As Long, i As Long, lngCol As Long
lngCol = Rows(1).Find("NAME", lookat:=xlWhole).Column 'assumes there will always be a column with "NAME" in row 1
Application.ScreenUpdating = False
LR = Cells(Rows.Count, lngCol).End(xlUp).Row
For i = LR To 1 Step -1
If Len(Cells(i, lngCol).Value) < 4 Then Rows(i).Delete
Next i
Application.ScreenUpdating = True
' Insert Column after NAME and then rename it NAME+TYPE
Dim ws As Worksheet
Dim lRow As Long, aCol As Long
Dim aCell As Range
Set ws = ActiveSheet 'Need to change to the Active sheet
With ws
Set aCell = .Rows(1).Find("NAME")
' Check if the column with "NAME" is found, it is assumed earlier
If Not aCell Is Nothing Then
aCol = aCell.Column
.Columns(aCol + 1).EntireColumn.Insert
.Cells(1, aCol + 1).Value = "NAME+TYPE"
.Activate
' Freeze the Top Row
Rows("1:1").Select
With ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
ActiveWindow.FreezePanes = True
' Get lastrow of Col which has "NAME"
lRow = .Range(Split(.Cells(, aCol).Address, "$")(1) & .Rows.Count).End(xlUp).Row
'Save the file and format the filetype
Dim wkb As Workbook
Set wkb = ActiveWorkbook 'change to your workbook reference
wkb.SaveAs Replace(wkb.Name, "#csv.gz", ""), 52 'change "csv.gz" to ".xlsm" if need be
' Add the formula to all the cells in 1 go.
.Range(Split(.Cells(, aCol + 1).Address, "$")(1) & "2:" & _
Split(.Cells(, aCol + 1).Address, "$")(1) & lRow).Formula = _
"=LEFT(MID(CELL(""filename""),SEARCH(""["",CELL(""filename""))+1, SEARCH(""]"",CELL(""filename""))-SEARCH(""["",CELL(""filename""))-1),5)&RC[-1]"
.Columns("A:AK").Columns.AutoFit
Else
MsgBox "NAME Column Not Found"
End If
End With
' Change the Range of the cursor
Range("A1").Select
Application.CutCopyMode = False
End Sub