VBA - Format Name - vba

I am hoping someone can help me in my dilemma. Due to a system software limitation, I need to have all my code in one Macro.
1.) take Column Q which is a name in the format "last, first" and break it up using text to column (some names contain initials which is why I used text to column)
2.) include code to dismiss the message box that appears "Do you want to replace the contents of the destination cells?"
3.) delete all columns that are generated except the "last" & "first" name.
4.) concatenate the two columns so that they read Firstname Lastname
5.) auto fill down to the last row.
6.) copy paste special the values into an adjacent column and delete the old column with the function.
I tried recording the code but it seems that what I need can't be recorded and needs to be written.
Here's my shot at get those steps to work, pulled from code from my recorder as well as forums, and think I need a trained eye to sort through my mess:
Application.DisplayAlerts = False
Columns("Q:Q").Select
Selection.TextToColumns Destination:=Range("Q1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, _
Semicolon:=True, Comma:=True, Space:=True, Other:=False, FieldInfo:= _
Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1)), TrailingMinusNumbers:= _
True
Application.DisplayAlerts = False
Columns("U:U").Select
Selection.Delete Shift:=xlToLeft
Columns("S:T").Select
Selection.ClearContents
Range("S2").Select
ActiveCell.FormulaR1C1 = "=CONCATENATE(RC[-1], "" "", RC[-2])"
Range("S2").Select
Selection.AutoFill Destination:=Range("S2:500")
Range("S2:S42").Select
Columns("S:S").Select
Selection.Copy
Columns("T:T").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("T1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "Lead Recruiter"
Columns("Q:S").Select
Selection.Delete Shift:=xlToLeft
Thanks to Ron, I was able to get the msg box to dismiss. Right now it's break at the line:
Selection.AutoFill Destination:=Range("S2:500")
How can I update this to Autofill to the last row? The data is in column Q. Any insight is greatly appreciated.

My Assumptions
Data is in Column Q
There is no data after Column Q
The results needs to be generated in Column R. If you want to replace the values in Column Q then see CODE 2.
Here is the shortest code that I could think of.
CODE 1
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long
'~~> Change this to the relevant sheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> Find the last row in a column
lRow = .Range("Q" & .Rows.Count).End(xlUp).Row
'~~> Enter the formula in the complete column
.Range("R1:R" & lRow).Formula = "=IFERROR(MID(Q1,FIND("","",Q1,1)+2,FIND("" "",Q1,FIND("","",Q1,1)+2)-" & _
"(FIND("","",Q1,1)+2)),MID(Q1,FIND("","",Q1,1)+2,LEN(Q1)-FIND("","",Q1" & _
",1)+2+1)) & "" "" & LEFT(Q1,FIND("","",Q1,1)-1)"
'~~> Convert all formulas to values in one go
.Range("R1:R" & lRow).Value = .Range("R1:R" & lRow).Value
End With
End Sub
ScreenShot
CODE 2
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long
'~~> Change this to the relevant sheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> Find the last row in a column
lRow = .Range("Q" & .Rows.Count).End(xlUp).Row
'~~> Enter the formula in the complete column
.Range("R1:R" & lRow).Formula = "=IFERROR(MID(Q1,FIND("","",Q1,1)+2,FIND("" "",Q1,FIND("","",Q1,1)+2)-" & _
"(FIND("","",Q1,1)+2)),MID(Q1,FIND("","",Q1,1)+2,LEN(Q1)-FIND("","",Q1" & _
",1)+2+1)) & "" "" & LEFT(Q1,FIND("","",Q1,1)-1)"
'~~> Convert all formulas to values in one go
.Range("R1:R" & lRow).Value = .Range("R1:R" & lRow).Value
'~~> Delete Col Q so R moves to Q
.Columns(17).Delete Shift:=xlToLeft
End With
End Sub
Followup from Comments
Is this what you are trying?
Sub FormatPushReport()
Dim ws As Worksheet
Dim lRow As Long
'~~> Change this to the relevant sheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
.Range("R:R,U:U").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
.Range("R1").Value = .Range("Q1").Value
.Range("V1").Value = .Range("U1").Value
'~~> Find the last row in a column
lRow = .Range("Q" & .Rows.Count).End(xlUp).Row
'~~> Enter the formula in the complete column
.Range("R2:R" & lRow).Formula = "=IFERROR(MID(Q2,FIND("","",Q2,1)+2,FIND("" "",Q2,FIND("","",Q2,1)+2)-" & _
"(FIND("","",Q2,1)+2)),MID(Q2,FIND("","",Q2,1)+2,LEN(Q2)-FIND("","",Q2" & _
",1)+2+1)) & "" "" & LEFT(Q2,FIND("","",Q2,1)-1)"
.Range("V2:V" & lRow).Formula = "=IFERROR(MID(U2,FIND("","",U2,1)+2,FIND("" "",U2,FIND("","",U2,1)+2)-" & _
"(FIND("","",U2,1)+2)),MID(U2,FIND("","",U2,1)+2,LEN(U2)-FIND("","",U2" & _
",1)+2+1)) & "" "" & LEFT(U2,FIND("","",U2,1)-1)"
'~~> Convert all formulas to values in one go
.Range("R2:R" & lRow).Value = .Range("R2:R" & lRow).Value
.Range("V2:V" & lRow).Value = .Range("V2:V" & lRow).Value
.Columns(18).Replace What:="#VALUE!", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
.Columns(22).Replace What:="#VALUE!", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
.Range("Q:Q,U:U").Delete Shift:=xlToLeft
End With
End Sub
Screenshot

Related

TableDestination:="Sheet2!R1C1"

Sub Macro1()
Sheet2.Select
ActiveWindow.SmallScroll Down:=-69
Cells.Select
Selection.Delete Shift:=xlUp
Range("A1").Select
Dim Endrow&
Endrow = Sheet3.Range("H1").End(xlDown).Row
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
Sheet3.Name & "!R1C8:R" & Endrow & "C21", Version:=6).CreatePivotTable _
**TableDestination:=Sheets("Sheet2").Cells(1, 1)**, TableName:= _
"PivotTable1", DefaultVersion:=6
I tried to make this Pivot Tables Macro insert into Sheet2!R1C1 (which is an existing worksheet), instead of creating a new worksheet. However, I receive Run-time error
5: Invalid Procedure call or argument.
I have tried to following methods
TableDestination:=Sheets("Sheet2").Cells(1, 1)
TableDestination:="Sheet2!R1C1"
TableDestination:=Sheet2.name & "!R1C1"
but all failed. How can I make this right?
Your code works on the assumption that there are worksheets with the Code Name (not names!) of Sheet2 and Sheet3. Could it be that you're referring to the sheet's object name which possibly has changed? This works … if you have a Sheet2 and Sheet3
Sub Macro1()
Sheet2.Select
ActiveWindow.SmallScroll Down:=-69
Cells.Select
Selection.Delete Shift:=xlUp
Range("A1").Select
Dim Endrow&
Endrow = Sheet3.Range("H1").End(xlDown).Row
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
Sheet3.Name & "!R1C8:R" & Endrow & "C21", Version:=6).CreatePivotTable _
TableDestination:=Sheets("Sheet2").Cells(1, 1), TableName:= _
"PivotTable1", DefaultVersion:=6
End Sub
Perhaps check that when you refer to Sheet2 and Sheet3 that they still exists.
Public Sub ListSheetNames()
Dim vSheet As Worksheet
For Each vSheet In Worksheets
Debug.Print "Code Name/Sheet Name: " & vSheet.CodeName & " / " & vSheet.Name
Next
End Sub
Maybe change Sheet2 reference to the below … and similarly for Sheet3
sheets("Sheet2")

Excel Macro: I would like to add one column to a range and call a function to fill it

Below is a macro we use to build a worksheet with a subset of a larger worksheet.
When the loop finds a match in our array of server names, it copies it over to the new worksheet.
I would like to add a new column to the new worksheet during the copy process. And after getting that working, I would like to fill this field by calling a function. We are trying to have a column that shows whether a server is a "critical" server. Simple y/n returns from a function that would look in an array of critical servers. I don't need the function, just how to add a column and fill it during the loop.
I will paste the big loop farther down, but here is the individual line of code that would copy over a range if found to a new worksheet. It is here I would like to add or copy one more column filled by a function:
Rcount = Rcount + 1
Source.Range("A" & Rng.Row & ":R" & Rng.Row).Copy NewSh.Range("A" & Rcount & ":R" & Rcount)
Here is the big loop for inquiring minds. It might be useful or at least prove this code is being used:
With Source.Range("A1:R9000")
'Find where the actual data we need starts
Set Rng = .Find(What:="Client", _
After:=.Cells(.Cells.Count), _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
intColorMatch = 0
If Not Rng Is Nothing Then
FirstAddress = Rng.Address
Do
Set Rng = .FindNext(Rng)
If (Rng.Interior.Color = 13421772) Then
intColorMatch = intColorMatch + 1
End If
If (intColorMatch < 2) = False Then
StartRow = Rng.Row
Exit Do
End If
Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress
End If
Source.Range("A" & StartRow & ":R" & StartRow + 1).Copy NewSh.Range("A1:R2")
Rcount = 2
FirstAddress = 0
For I = LBound(MyArr) To UBound(MyArr)
'If you use LookIn:=xlValues it will also work with a
'formula cell that evaluates to "#"
'Note : I use xlPart in this example and not xlWhole
Set Rng = .Find(What:=MyArr(I), _
After:=.Cells(.Cells.Count), _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
FirstAddress = Rng.Address
Do
If Rng.Row >= StartRow Then
Rcount = Rcount + 1
Source.Range("A" & Rng.Row & ":R" & Rng.Row).Copy NewSh.Range("A" & Rcount & ":R" & Rcount)
' Use this if you only want to copy the value
' NewSh.Range("A" & Rcount).Value = Rng.Value
End If
Set Rng = .FindNext(Rng)
Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress
End If
Next I
End With
If the "new" column that you are wanting to populate is after the end of your copied data, you aren't really adding a column - you are just populating an existing empty column.
If so, you can just say something like
NewSh.Cells(Rcount, "Q").Formula = "=whatever_formula_you_want"
(or use FormulaR1C1 if that is easier).
Or, if you only want to insert a value there (which you are calculating in your VBA code), it is just
NewSh.Cells(Rcount, "Q").Value = the_value_I_want

Replace value of cell in the sheet

I need a macro that takes the value in "I2" and replaces it everywhere in the Sheet with a spacebar "" then go to "I3" and does the same till ~"I6000" and if possible rotate through till "Z6000"IMPORTANT: If possible it should only delete the exact value so if there is a "5" it should only delete it where "5" is as a string alone not take "5675" and make it a "67"
Edit: I have more then 1 Value in 1 Cell Example: "ValueC ValueZ Value5 95 C-69"
I have this code:
Range("I2").Select
Application.CutCopyMode = False
Selection.Copy
Cells.Replace What:=I2, Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End Sub
How can I change it to go through "L2"-"Z6000"?
Example Screenshot excel with highlight
User following code it will do your job.
Sub fillValue()
cellValue = Range("I2").Value
For i = 1 To 6000 'increase this value to add more rows
compareValue = Range("A" & i).Value
if compareValue = cellValue then
Range("A" & i).Value = ""
end if
compareValue = Range("B" & i).Value
if compareValue = cellValue then
Range("B" & i).Value = ""
end if
'Add as many column as you want.
Next
End Sub
In excel you can not assign single key to a macro. You have to assign it with the combination of Ctrl key as shown in following image.

Replace worksheet name within the function in VBA in case of loop

I am creating several worksheets based on some worksheet format just simply copying all its content with formulas. Only I give a new name to the sheet.
I want that each time I create a sheet and giving it a name, format! word in all cells must be replaced with active worksheet name.
I tried to write some codes but it seems not working.
Sub createsheet()
LastRow = Sheets("SUMMARY").Range("A" & Rows.Count).End(xlUp).Row
Dim ws As Worksheet
For i = 9 To LastRow
Set ws = ThisWorkbook.Sheets.Add(after:= _
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
ws.Name = Left(Sheets("SUMMARY").Cells(i, 1), 31)
wsrepl = Worksheets(Worksheets.Count).Name
Sheets("format").Select
Cells.Select
Application.CutCopyMode = False
Selection.Copy
Worksheets(Worksheets.Count).Activate
ActiveSheet.Paste
ActiveSheet.Cells(2, 2) = Sheets("SUMMARY").Cells(i, 1)
ActiveSheet.Cells(5, 2) = Sheets("SUMMARY").Cells(i, 1)
Worksheets(Worksheets.Count).Activate
Cells.Replace What:="format!", Replacement:= _
wsrepl, LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
Next i
End Sub
Any help will be highly appreciated.
Cells.Replace What:="format!", Replacement:= _
"'" & wsrepl & "'" & "!", LookAt:=xlPart, SearchOrder:=xlByRows _
, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
I found an answer.

Filtered Views VBA Excel

I have an automated filed that comes out with a row (4) of headers
the first column (A) contains different categories (types of payment), in base of the specific type I would run a different test based on a certain sheet contained into the file I'm working on.
What am I doing at the moment is basically create a filter (of the first column A) based on the type of payment I want to check, create a temporary sheet, copy paste this filtered view, work on that with the checks and then copy/paste the result (contained in the column R) into the main sheet.
The problem comes out in the last part, when I want to copy paste, because of the filtered view I can't Just go to the first free cell under the header of R and copy paste, because the system doesn't understand I'm moving into a filtered view. I have to be sure that I'm copy pasting the correct results in base of the value (string) contained into the A column), can you help me to solve it please?.
Another way is to do a for each loop, but actually I'm not sure about how to structure it.
Here we have the part of the code i'm working on
Sub Payexample()
' normal cleaning procedures
Sheets("Payexample").Select
Rows("1:10").Select
Selection.Delete Shift:=xlUp
Columns("J:J").Select
Selection.Replace What:="AED", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.NumberFormat = "0.00"
Sheets("Sheet1").Select
ActiveSheet.Range("$A$4:$A$500").AutoFilter Field:=1, Criteria1:="Payfort"
Range("A5 : N5").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "Payfort momentary"
Range("A1").Select
ActiveSheet.Paste
Range("$M$1").Formula = Range("B1") & (",") & Range("M1")
Dim Lastrow As Long
Application.ScreenUpdating = False
Lastrow = Range("J" & Rows.Count).End(xlUp).Row
Range("O1").FormulaR1C1 = "=IF(RC[-2]-VLOOKUP(RC[-3],'PayFort'!B:J,9,FALSE)<=0.99, ""Payfort Payment Checked"", ""Manual Verification Needed"")"
Range("O1").AutoFill Destination:=Range("O1:O" & Lastrow)
Range("O1:O" & Lastrow).Select
Selection.Copy
Sheets("Sheet1").Select
ActiveSheet.Range("$A$4:$A$500").AutoFilter Field:=1, Criteria1:="Payfort"
Range("R5").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'Sheets("Payfort Momentary").Select
'ActiveWindow.SelectedSheets.Delete
End Sub
I think this will do mostly what you are after but I wasn't sure what you want to do with your formulas, hopefully you'll be able to work out what you want to do with them from here:
Sub Payexample()
Dim rngCheck As Range
Dim r As Range
Dim rowNum As Long
' normal cleaning procedures
Sheets("Payexample").Select
Rows("1:10").Select
Selection.Delete Shift:=xlUp
Columns("J:J").Select
Selection.Replace What:="AED", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.NumberFormat = "0.00"
Sheets("Sheet1").Select
With ActiveSheet
rngCheck = .Range("$A$4:$A$500")
For Each r In rngCheck.Rows ' Loop through the rows in your data area
rowNum = r.Row
If .Range("A" & rowNum) = "Payfort" Then
' Either
.Range("R" & rowNum).Formula = "" ' Your formula here
.Range("R" & rowNum) = .Range("R" & rowNum).Value ' Change formula to value
' Or
.Range("R" & rowNum) = ' Do calculations in VBA without formula
End If
Next r
End With
End Sub