I am newbie to Excel VBA.
Need help to removing the commas, spaces and NULL string to "0" from ColumnName called StringName.
First, I have tried to remove the commas, spaces from the ColumnName called StringName and finally to find and replace the "NULL" string to 0(Zero).
Here is the code to Replace for commas, spaces from the ColumnName called StringName.
Sub ReplaceCharacters()
Application.ScreenUpdating = False
Dim lrow As Long
lrow = Cells(Cells.Rows.Count, "A").End(xlUp).Row
With ActiveSheet.Range("A2:A" & lrow).SpecialCells(xlCellTypeConstants, xlTextValues).Cells
.Replace What:=",", Replacement:="", LookAt:=xlPart
.Replace What:=" ", Replacement:="", LookAt:=xlPart
End With
Application.ScreenUpdating = True
End Sub
I am struggling to find and Replace the string "NULL" to 0 from the ColumnName called StringName.
I need help with this and I have tried a lot and ended up here for a solution.
Here is what I have tried..
' not working
Sub UpdateWhole()
With ActiveSheet.UsedRange
.Replace "NULL", "0", xlWhole
End With
End Sub
' not working
Sub FormulaRng()
For i = 2 To 10
Worksheets("Sheet1").Range("A2:A" & i).FormulaR1C1 = "=IF(A" & i & "=""NULL"",0,A" & i & ")"
Next
End Sub
Thanks in Advance
Here is the sample data to test
StringName
------------------
NULL
NULL
null
nullasdf
cbgrgNULLdf343
, asdfwe 4fdt
456fg , d55nullNULL
sdf34 df, 4fd
NULLfgf null
121
22
34545
Required OutPut
------------------------
0
0
0
nullasdf
cbgrgNULLdf343
asdfwe4fdt
456fgd55nullNULL
sdf34df4fd
NULLfgfnull
121
22
34545
The following revised procedure should work for you. I used the Clean function to remove all non-printable characters from the text before replacing the NULL text with 0.
VBA Code
Public Sub ReplaceCharacters()
On Error GoTo ErrTrap
Const ProcedureName As String = "ReplaceCharacters"
Dim sheet As Worksheet: Set sheet = ActiveSheet
Dim cell As Range
Application.ScreenUpdating = False
For Each cell In sheet.UsedRange.Cells
cell = Trim(Application.WorksheetFunction.Clean(cell))
cell.Replace What:="NULL", Replacement:=0, LookAt:=xlWhole
cell.Replace What:=",", Replacement:="", LookAt:=xlPart
cell.Replace What:=" ", Replacement:="", LookAt:=xlPart
Next cell
ExitProcedure:
On Error Resume Next
Application.ScreenUpdating = True
Set sheet = Nothing
Exit Sub
ErrTrap:
Select Case Err.number
Case Else
Debug.Print "Procedure: " & ProcedureName & " |Error #: " & Err.number & " |Error Description: " & Err.description
End Select
Resume ExitProcedure
Resume 'for debugging
End Sub
Example Video
Try this.
Sub test()
Dim Ws As Worksheet
Dim rngDB As Range
Set Ws = ActiveSheet
With Ws
Set rngDB = .Range("a2", .Range("a" & Rows.Count).End(xlUp))
End With
With rngDB
.Replace What:=",", Replacement:="", LookAt:=xlPart
.Replace What:=" ", Replacement:="", LookAt:=xlPart
.Replace What:="NULL", Replacement:="0", LookAt:=xlWhole
.Replace What:="null", Replacement:="0", LookAt:=xlWhole
End With
End Sub
Related
This is about VBA in excel.
I am trying to remove the sign "/" and cut the string length for every cell down to 31 to make those values valid as a name for a new sheet. The constraint is within the first two columns until the last occupied row.
My code compiled, however, it brought me endless processing and I have to task manager-exit every time after running it. Please take a look at it, thank you so much!
Sub replaceSpeCharaAndCutLength()
'selectPositionAndReplaceSpeCharaAndCutLength Macro
Dim cell As Range
Dim row As Long
For row = 7 To Sheet1.Cells(Rows.Count, 1).End(xlUp).row
Worksheets("Sheet1").Columns("A").Replace _
What:="/", Replacement:="_", _
SearchOrder:=xlByColumns, MatchCase:=True
Worksheets("Sheet1").Columns("B").Replace _
What:="/", Replacement:="_", _
SearchOrder:=xlByColumns, MatchCase:=True
For Each cell In Sheet1.Range("A:B").Cells
cell.Value = Left(cell.Value, 31)
Next cell
Next row
End Sub
Updated code 0142 08212020
Sub replaceSpeCharaAndCutLength()
'
' selectPositionAndReplaceSpeCharaAndCutLength Macro
'
Dim cell As Range
Worksheets("Sheet1").Columns("A").Replace _
What:="/", Replacement:="_", _
SearchOrder:=xlByColumns, MatchCase:=True
Worksheets("Sheet1").Columns("B").Replace _
What:="/", Replacement:="_", _
SearchOrder:=xlByColumns, MatchCase:=True
For Each cell In Sheet1.Range("A:B").Cells
cell.Value = Left(cell.Value, 31)
Next cell
End Sub
Range.Replace doesn't require a loop. You can also use Evaluate instead of the other loop:
Sub replaceSpeCharaAndCutLength()
Dim lastRow As Long
lastRow = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Row
Dim rng As Range
Set rng = Sheet1.Range("A7:B" & lastRow)
rng.Replace _
What:="/", Replacement:="_", _
SearchOrder:=xlByColumns, MatchCase:=True
rng.Value = rng.Parent.Evaluate("INDEX(LEFT(" & rng.Address & ",31),)")
End Sub
My code below works but it is very slow… This code in fact consists to convert the date in column C and D of my sheet (called "Test") from format day.month.year to format day/month/year (For example please see the picture below, the lines 1-2-3-4-5 have been already converted whereas the other lines from line 1183 have not been converted yet).
I am looking for a solution to improve the speed of this macro because if I have a lot of lines to convert in column C and D, the macro is really really slow…
If by chance someone know how to improve the speed of this macro, that would be really fantastic.
Sub convertdatrighteuropeanformat()
Dim cell As Range
Call selectallmylinesctrlshiftdown
Application.ScreenUpdating = False
For Each cell In Selection
With cell
.NumberFormat = "#"
.Value = Format(.Value, "dd/mm/yyyy")
End With
Next cell
Selection.Replace What:="/", Replacement:=".", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Application.ScreenUpdating = True
End Sub
Sub selectallmylinesctrlshiftdown()
With Sheets("Test")
.Range(.Range("D2"), .Range("E2").End(xlDown)).Select
End With
End Sub
Instead of a loop, refer to the entire Range (previously Selection) at once inside the With block. This is combined into one sub, although there is nothing wrong with your decision to declare the range with a stand alone procedure.
Option Explicit
Sub convert()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Test")
Dim LRow As Long, MyCell As Range, MyRange As Range
LRow = ws.Range("D" & ws.Rows.Count).End(xlUp).Row
Set MyRange = ws.Range("D2:E" & LRow)
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
With MyRange
.Value = Format(.Value, "dd/mm/yyyy")
.Replace "/", ".", xlPart, xlByRows
.NumberFormat = "#"
End With
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
have to replace the word in excel cell .
using like
Sub test()
Dim a_row As String
Dim b_row As String
Dim row_counter As Integer
For row_counter = 1 To 600
a_row = "A" & row_counter
b_row = "B" & row_counter
Dim Findtext As String
Dim Replacetext As String
Findtext = Sheets("sheet1").Range(a_row).Value
Replacetext = Sheets("sheet1").Range(b_row).Value
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
If ws.Name <> ActiveWorkbook.Worksheets(1).Name Then
ws.Cells.Replace What:=Findtext, Replacement:=Replacetext, LookAt:= _
xlWhole, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End If
Next ws
Next row_counter
End Sub
there are two cols in sheet1. 1st cols shows Japanese words. 2nd column shows English words.
公園 park
夏 summer
緑 Green
青空 blue Sky
男の人 man
In the 2nd sheet displays in col A
column A
公園、夏、青空、緑、男の人
the above code replace Japanese words.
if LookAt:= _xlPart, after replace shows like below
park, summer, 青sky, green,manの人
if LookAt:= _xlWhole , its not replacing the word
In the 2nd sheet displays in the separate columns
A B C D E
公園 夏 青空 緑 男の人
if LookAt:= _xlWhole then
its working perfectly.
i want to do
In the 2nd sheet displays the value in single col A delimited by comma
column A
公園、夏、青空、緑、男の人
need the output like
park, summer, blue sky, green,man
please give some idea.. thanks
Do it in memory instead, it's quicker and much easier to work with arrays. If I understand the way your data is set out - the following should work where your find/replace table is in columns A:B on sheet1 and the values to replace are in sheet2 and are comma separated in cell A1:
Sub MM_Foo()
Dim findArray As Variant
Dim replaceArray As Variant
Dim matchPosition As Long
With Sheets(1)
findArray = .Range("A1:B" & .Cells(.Rows.Count, 2).End(xlUp).Row).Value
End With
On Error GoTo checkErr:
For j = 1 To Sheets(2).Cells(Sheets(2).Rows.Count, 1).End(xlUp).Row
replaceArray = Split(Sheets(2).Cells(j, 1).Value, ",")
With Application
For i = LBound(replaceArray) To UBound(replaceArray)
matchPosition = .Match(replaceArray(i), .Index(findArray, , 1), 0)
replaceArray(i) = findArray(matchPosition, 2)
skipReplace:
Next
End With
Sheets(2).Cells(j, 1).Value = Join$(replaceArray, ",")
Next
On Error GoTo 0
Exit Sub
checkErr:
If Err.Number = 13 Then
Err.Clear
GoTo skipReplace:
Else
MsgBox Err.Description & " (" & Err.Number & ")", vbExclamation, "Error"
Err.Clear
On Error GoTo 0
Exit Sub
End If
End Sub
Without a trailing 'comma', there may have to be repetitive passes that may or may not actually do anything; there need to cover all possible combinations.
Sub delimitedTranslate()
Dim w As Long, vWRDs As Variant
With Worksheets("Sheet1")
vWRDs = .Range(.Cells(2, "A"), _
.Cells(Rows.Count, "A").End(xlUp).Offset(0, 1)) _
.Value2
End With
With Worksheets("Sheet2")
With .Columns("A")
For w = LBound(vWRDs, 1) To UBound(vWRDs, 1)
.Replace what:=vWRDs(w, 1) & ChrW(12289), _
replacement:=vWRDs(w, 2) & Chr(44), _
lookat:=xlPart, MatchCase:=False, searchformat:=False
.Replace what:=ChrW(12289) & vWRDs(w, 1), _
replacement:=Chr(44) & vWRDs(w, 2), _
lookat:=xlPart, MatchCase:=False, searchformat:=False
.Replace what:=Chr(44) & vWRDs(w, 1), _
replacement:=Chr(44) & vWRDs(w, 2), _
lookat:=xlPart, MatchCase:=False, searchformat:=False
Next w
End With
End With
End Sub
Sheet1 terms Sheet2 before delimitedTranslate Sheet2 after delimitedTranslate
I have a worksheet with more than 200 cells.
Each cell contains a formula as below:
=AVERAGE('worksheetname'!range)
I want to run a macro that changes the formula to following formula:
=IFERROR(AVERAGE('worksheetname'!range),100%)
I have worked out that I can change =AVERAGE into for example &AVERAGE and than search & replace &AVERAGE with &IFERROR. It will allow me to search for cells which contains &IFERROR and add missing parenthesis at the end of formula )
I want to build a macro but have few problems:
how to search & replace it all once for each cell
macro gives me a mismatch error
below is a code for my macro:
Sub aaaa()
'
' IFERROR Macro
'
'
Dim myRange As Range
Dim myCell As Range
Dim i As Integer
Set myRange = Range("E4:BB120")
Sheets("Zones").Select
Cells.Replace What:="=AVERAGE(", Replacement:="&IFERROR(AVERAGE(", LookAt _
:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
For Each myCell In myRange
If myCell Like "*&IFERROR*" Then
myCell.Select
i = 1
Do While i < 2
Selection.Replace What:=")", Replacement:="),100%)", LookAt _
:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
i = i + 1
Loop
End If
Next myCell
Cells.Replace What:="&IFERROR(AVERAGE(", Replacement:="=IFERROR(AVERAGE(", LookAt _
:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End Sub
You might find it easier to do the replacement "manually" in code instead of using Replace :
Sub aaaa()
Dim myRange As Range
Dim c As Range
Dim f As String, i As Long
On Error Resume Next
Set myRange = Sheets("Zones").Range("E4:BB120").SpecialCells( _
xlCellTypeFormulas)
On Error GoTo haveError
If myRange Is Nothing Then Exit Sub
Application.Calculation = xlCalculationManual
For Each c In myRange.Cells
f = c.Formula
If f Like "=AVERAGE(*)" Then
c.Formula = "=IFERROR(" & Right(f, Len(f) - 1) & ",100%)"
i = i + 1
End If
Next c
MsgBox "Replaced " & i & " formulas"
haveError:
If Err.Number <> 0 Then MsgBox Err.Description
Application.Calculation = xlCalculationManual
End Sub
I cannot find or create VBA code to allow pasting copied text from one cell in another sheet(sheet2) into a previously created comment in another sheet(sheet1).
Here is the code I have successfully compiled thus far, and I am stuck on how to get the text found into the comment box.
Sub For_Reals()
'Add Comment
Sheets("Sheet1").Range("F2").AddComment
Range("F2").Comment.Visible = False
'Find Value in Sheet2 based on Value from Sheet1
Dim FindString As String
Dim Rng As Range
FindString = Sheets("Sheet1").Range("F2").Value
If Trim(FindString) <> "" Then
With Sheets("Sheet2").Range("C:C")
Set Rng = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
Application.Goto Rng, True
Else
MsgBox "Nothing found"
End If
End With
End If
'Copy Value 4 cells to the right of found Value
Selection.Offset(0, 4).Copy
'Need Code to paste copied value in previously created comment
End Sub
Rather than copy and paste the cell value into the comment, you create the text at the same time as creating the comment box. If a comment box already exists an error is raised - so remove any comment boxes in that cell beforehand.
The VBA help gives this as an example:
Worksheets(1).Range("E5").AddComment "Current Sales"
So with this in mind, this code will do the trick:
Sub For_Reals()
'Find Value in Sheet2 based on Value from Sheet1
Dim FindString As String
Dim Rng As Range
FindString = Sheets("Sheet1").Range("F2").Value
If Trim(FindString) <> "" Then
With Sheets("Sheet2").Range("C:C")
Set Rng = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
'Remove any existing comments, create comment and add text.
If Not Rng Is Nothing Then
Sheets("Sheet1").Range("F2").ClearComments
Sheets("Sheet1").Range("F2").AddComment Rng.Offset(0, 4).Value
Range("F2").Comment.Visible = True
Else
MsgBox "Nothing found"
End If
End With
End If
End Sub
Final code I ended up with is below. Added a loop to run through the column, and added a second reference to pull both the definition and description into the comment. Thank you Darren Bartrup-Cook for helping me out when I was stuck!
Sub Add_Comment_As_Def_Desc_Reference()
'Posted by Jeff Barrett 2015-04-10
Dim FindString1 As String
Dim Rng1 As Range
Dim sCommentText1 As String
Dim sCommentText2 As String
Dim str1 As String
Dim str2 As String
Dim cmmt As String
Dim i As Integer
str1 = "Definition: "
str2 = "Description: "
'Loop Code, must specify range for i based on # of FieldAlias
Sheets("Fields").Select
Range("F4").Select
For i = 4 To 59
'Find Definition & Description in NASDefs based on Value from FieldAlias
FindString1 = ActiveCell.Value
If Trim(FindString1) <> "" Then
With Sheets("NASDefs").Range("C:C")
Set Rng1 = .Find(What:=FindString1, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
End With
End If
'Remove any existing comments, create comment and add text in FieldAlias
If Not Rng1 Is Nothing Then
ActiveCell.ClearComments
sCommentText1 = Rng1.Offset(0, 4).Value
sCommentText2 = Rng1.Offset(0, 5).Value
ActiveCell.AddComment.Text Text:=str1 & Chr(10) & Chr(10) & sCommentText1 & Chr(10) & Chr(10) & str2 & Chr(10) & Chr(10) & sCommentText2
ActiveCell.Comment.Visible = False
ActiveCell.Comment.Shape.AutoShapeType = msoShapeRoundedRectangle
'Format lines of text
With ActiveCell.Comment.Shape.TextFrame
.Characters.Font.ColorIndex = 5
End With
Else
MsgBox "Nothing found"
End If
'End Loop
ActiveCell.Offset(RowOffset:=1, ColumnOffset:=0).Select
Next i
'Resize Comment to fit text
'posted by Dana DeLouis 2000-09-16
Dim MyComments As Comment
Dim lArea As Long
For Each MyComments In ActiveSheet.Comments
With MyComments
.Shape.TextFrame.AutoSize = True
If .Shape.Width > 300 Then
lArea = .Shape.Width * .Shape.Height
.Shape.Width = 300
' An adjustment factor of 1.1 seems to work ok.
.Shape.Height = (lArea / 200) * 0.6
End If
End With
Next ' comment
End Sub