Excel VBA iterate over all used cells and substitute their values - vba

This is my first time ever working with VBA and Excel and my problem is probably caused by a big lack of knowledge on my part.
I have a one column list of city names (containing 800 items, hence I'm looking to automatically replace them) and some chunks of text in which the term "cityname" occurs multiple times and needs to be replaced by the correct city name, which in my setup would be the value of the first column cell in the same row.
So I found this: How to iterate through all the cells in Excel VBA or VSTO 2005
and found the InStr and Substitute functions by looking through the Excel VBA reference.
Using the iteration like this works fine:
Sub MySubstitute()
Dim cell As Range
For Each cell In ActiveSheet.UsedRange.Cells
If InStr(cell.Value, "cityname") > 0 Then
MsgBox "Hello World!"
End If
Next cell
End Sub
I get a message box for every "cityname" in my sheet (a test sheet with only 2 rows).
However when I add what I really want to achieve I get a Runtime Error (1004):
Sub MySubstitute()
Dim cell As Range
For Each cell In ActiveSheet.UsedRange.Cells
If InStr(cell.Value, "cityname") > 0 Then
cell.Value = WorksheetFunction.Substitute(cell.Value, "cityname", Cells(cell.Row, A))
End If
Next cell
End Sub
So I guess something in that line is wrong but I can't figure out what. Any hints to what my mistake is are appreciated, thanks :)

You can use the Range.Replace Method and replace all at once no need to iterate.
Sub MySubstitute()
Dim rng As Range
Set rng = ActiveSheet.UsedRange.Cells
rng.Replace "cityname", "correctcityname", xlPart
End Sub

You should change:
cell.Value = WorksheetFunction.Substitute(cell.Value, "cityname", Cells(cell.Row, A))
by
cell.Value = WorksheetFunction.Substitute(cell.Value, "cityname", Cells(cell.Row, 1))

Related

Setting variables VBA

complete novice here
I started some VBA a few days ago, I have simple question but cant seem to find what I am doing wrong.
I am trying to make a button which will take the coordinates of the active cell and compare them to another worksheet to retrieve a specific value from another table.
I set variables to the active cell column and row, I want to do this so I can later compare these locations to another worksheet and get the value at a specified position on another worksheet.
So far I have written simply what I could find on the internet as I have no formal training.
The msgbox at the end is just to test whether or not it actually picks up the reference.
Sub CommandButton1_Click()
Dim Arow As Range
Dim Acol As Range
Set Arow = Worksheets("Sheet1").Range(ActiveCell.Row)
Set Acol = Worksheets("Sheet1").Range(ActiveCell.Column)
MsgBox (Arow)
End Sub
So far I have error run-time error '1004' Application defined or object defined error highlighting the 4th Row. If anyone could help me solve this or redirect me to some help it would be much appreciated.
I think this won't work, you should put there
Set arow = Worksheets("Sheet1").Range(ActiveCell.Row & ":" & ActiveCell.Row)
Putting there simply number won't work. For the column, you should put there somethong like C:C. For getting letter of column, see this qestion: Function to convert column number to letter?
For more information about Range property, please see official documentation https://msdn.microsoft.com/en-us/library/office/ff836512.aspx.
The thing is, that you have to supply either the address in so called A1 reference, which is "A1", or "$A$1" or name of cell, etc, or you have to supply two Range objects, such as two cells Worksheets("Sheet1").Range(Worksheets("Sheet1").Cells(1,1), Worksheets("Sheet1").Cells(2,2)), which defines area starting with upper-left corner in first parameter and lower right in second parameter.
ActiveCell.Row and ActiveCell.Column returns you some Integer value representing number of row and column, i.e. if you point cell B4, ActiveCell.Row would return 4, and ActiveCell.Column gonna return 2. An Range() property need as an argument whole adress for some range, i.e. Range("C6") or Range("G3:J8").
When you have your column as a number, you can use Cells() property for pointing first and last cell in your range, i.e. Range(Cells(2, 4), Cells(6, 8) would be the same range as Range("D2:H6").
Following this, one of the ways that you can do what you have described is:
Sub CommandButton1_Click()
Dim Rng As Range
Set Rng = Worksheets("Sheet1").Cells(ActiveCell.Row, ActiveCell.Column)
End Sub
Now you have under variable Rng an Range of the same coordinates as ActiveCell, but in Sheet1. You can pass some value into i.e Rng.Value = "Hello World", paste something with Rng.PasteSpecial xlPasteAll etc.
if you want the value from other sheet at the same location as activeCell, use this code,
Private Sub CommandButton1_Click()
valueFromOtherSheet = Sheets("Sheet2").Range(ActiveCell.Address)
MsgBox (valueFromOtherSheet)
End Sub
Like the others have said, it's just about knowing your variable types. This is another way you could achieve what you want
Sub CommandButton1_Click()
Dim Acell As Range
Set Acell = Worksheets("Sheet2").Range(ActiveCell.Address)
MsgBox "Value on ActiveSheet: " & ActiveCell.Value & vbNewLine & _
"Value on Sheet2: " & Acell.Value
End Sub
Thank you everyone for the help and clarification, In the end I was able to come up with some code that seems to do what I need it to.
Private Sub CommandButton1_Click()
Dim cabDate As Range
Dim searchCol As Integer
Dim newindex As Range
Set cabDate = WorksheetFunction.Index(Range("A1:O9999"), ActiveCell.Row, 2)
searchCol = ActiveCell.Column
Set newindex = WorksheetFunction.Index(Worksheets("Deadlines").Range("A1:O9999"), cabDate.Row, searchCol)
MsgBox (newindex)
End Sub
I wasn't aware about conflicting data types so thank you all for the assistance.

Excel vba Autofill only empty cells

I have a column A with data up to A300.
In this range, some of theses cells are empty, some contain values.
In VBA, I set the formula of the cell A1 then I use the autofill function to set it all over my column (up to A300) like this :
ws.Range("A1").Select
Selection.AutoFill Destination:=ws.Range(ws.Cells(1, 1), ws.Cells(300, 1))
My problem is that datas contain on some cells are erased too ! I'm trying to autofill like it but only throught the empties cells.
I tried to add a filter on my worksheet like this :
ws.Range("$A$1:$A$300").AutoFilter Field:=1, Criteria1:="="
Then I reused the autofill function, but it seems to fill thourght the filtered cells...
Can't we add a parameter like "only empties cells" to the autofill function ? Something like this :
Selection.AutoFill Destination:=ws.Range(ws.Cells(1, 1), ws.Cells(300, 1)), Criteria1:="="
Thanks for your replies !
with data like:
I would do a single copy rather than a fill-down:
Sub luxation()
Range("A1").Formula = "=ROW()"
Dim rDest As Range
Set rDest = Intersect(ActiveSheet.UsedRange, Range("A1:A300").Cells.SpecialCells(xlCellTypeBlanks))
Range("A1").Copy rDest
End Sub
with this result:
NOTE:
The formulas adjust after being copied.
EDIT#1:
Please note that there are some circumstances under which this code will not work. It is possible that UsedRange my not extend down to cell A300.
For example, if the worksheet is totally empty except for a formula in A1 and some value in A3. In this case Rdest will only include the single cell A2. The code will leave A4 through A300 untouched.
Assuming you want static values, I would use a loop. The one below will fill all empty cells with poop:
Sub AllFillerNoKiller()
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
For Each c In ws.Range("A1:A300")
If c.Value = "" Then c.Value = "poop"
Next
End Sub
Apologies, I miss-understood you question - Want to fill all blank cells with the value in A1? - here you go:
Sub Replace()
If Trim(Range("A1").Value) = "" Then
MsgBox "There's no value in A1 to copy so there's nothing to copy to all blank cells", vbInformation, "Nothing in A1"
Exit Sub
Else
Range("A1:A300").SpecialCells(xlCellTypeBlanks).Select
Selection.Value = Range("A1").Value
End If
End Sub
You can also use below code:
stAddress = Sheet1.Range("A1").CurrentRegion.SpecialCells(xlCellTypeBlanks).Address
Sheet1.Range(st).Value = "Empty"

Auto filling formula VBA

Looking for some help with a VBA function
I have data on two sheets I need to perform an index match on.
The data size will vary every time the compare is run.
I have coded the VBA to call the data and populate both sheets but running the comparison is causing a problem.
I have created the below function, its running without error but not populating the formula in cell starting J2 to end of the J range.
Sub FormulaFill()
Dim strFormulas(1 To 1) As Variant
With ThisWorkbook.Sheets("Export Worksheet")
strFormulas(1) = "=INDEX('sheet1'!E:E,MATCH('Export Worksheet'!A2,'sheet1'!A:A,0))"
.Range("J:J").FillDown
End With
End Sub
Any help would be greatly appreciated.
W
Image after updated code applied
You were writing the formula to an array variable, not a cell, then you tried to fill the entire column by using J:J. This means it was trying to fill the entire column with the contents of cell J1, the top cell, not J2.
Here is the code with corrections.
Sub FormulaFill()
With ThisWorkbook.Sheets("Export Worksheet")
.Cells(2, 10).Formula = "=INDEX('sheet1'!E:E,MATCH('Export Worksheet'!A2,'sheet1'!A:A,0))"
.Range(.Cells(2, 10), .Cells(.Cells(.Rows.Count, 9).End(xlUp).Row, 10)).FillDown
End With
End Sub
The .Cells(.Rows.Count, 9).End(XlUp).Row determines the last filled row of column 9 (I) and the code uses that number in the range to use for the autofill of column 10 (J)
It's because you're not filling the cell with the formula.
Sub FormulaFill()
Dim strFormulas(1 To 1) As Variant
With ThisWorkbook.Sheets("Export Worksheet")
strFormulas(1) = "=INDEX('sheet1'!E:E,MATCH('Export Worksheet'!A2,'sheet1'!A:A,0))"
.Range("J1").Forumla = strFormulas(1)
.Range("J:J").FillDown
End With
End Sub

Use User-defined range as input for cell parsing

I'm writing a macro in Excel 2010 in order to remove line breaks in multiple cells of a column. This cells need to be selected by the user. Following this previous post I was able to create an InputBox to let the user select the range but now, I am unable to process the data within the selection.
My previous code without the selection range parsed an entire column with a regexp to find a pattern in the string within the cells and change its contents.
I did this with a For i To Rows.Count block of code like this:
For i = 1 To Rows.Count
If Not IsEmpty(Cells(i, 5).Value) Then
varString = Sheets(ActiveSheet.Name).Cells(i, 5).Text
Sheets(ActiveSheet.Name).Cells(i,5).Value=objRegExp.Replace(varString, "$1 ")
End If
Next i
Now I want to replace the static column so I can process only the user range.
In order to achieve that I tried this:
Set selection = Application.InputBox(Prompt:= _
"Please select a range to apply the remove break lines procedure.", _
Title:="Remove Line Breaks", Type:=8)
If selection Is Nothing Then
Exit Sub
End If
Set RowsNumber = selection.CurrentRegion -> This line gives me an error: "Object required"
Set RowsNumber = RowsNumber.Rows.Count
For i = 1 To RowsNumber
If Not IsEmpty(Cells(i, 5).Value) Then
varString = Sheets(ActiveSheet.Name).Cells(i, 5).Text
Sheets(ActiveSheet.Name).Cells(i, 5).Value = objRegExp.Replace(varString, "$1 ") 'Replace pattern found with regular expression in the same line
End If
Next i
How can I access the cells in the range returned by the InputBox?
I also tried changing RowsNumber with selection.Rows.Count but that way, although it doesn't gives an error, the cells used have blank string within them when I run the debugger. I think this is because I try to access row = 5 when the range could be less, i.e 3 if user just selects 3 cells.
I tried a For Each Next loop but then again, I know not how to access the cells withing the selection range.
You can iterate through the cells of a range by using For Each loop.
Below is your code modified. I have changed the name of variable Selection to rng, because Selection is Excel library built-in function and this name should be avoided.
Sub x()
Dim rng As Excel.Range
Dim cell As Excel.Range
Set rng = Application.InputBox(Prompt:= _
"Please select a range to apply the remove break lines procedure.", _
Title:="Remove Line Breaks", Type:=8)
If rng Is Nothing Then
Exit Sub
End If
For Each cell In rng.Cells
If Not IsEmpty(cell.Value) Then
varString = cell.Text
cell.Value = objRegExp.Replace(varString, "$1 ") 'Replace pattern found with regular expression in the same line
End If
Next cell
End Sub

How to find cells that contain specific text then hide the entire row

When a button is pressed I want to loop through all the cells in my Sheet and find the cells that contains .doc or .xls or .pdf and hide the entire Row.
I know I can't use Contains but there must be something similar.
Cell example PM-TR Training.doc
This is what I have for now what can I replace contains with?
Sub HideRows()
Dim cell As Range
Dim DataCount As Integer
'Change the sheet name as necessary in the following line
With Worksheets("Sheet1")
DataCount = Range("A" & Rows.Count).End(xlUp).Row
For Each cell In Range("A1:A" & DataCount)
If cell.Contains(".doc") Or cell.Contains(".xls") Or cell.Contains(".pdf") Then
'The following code assumes you want the row hidden.
Range(cell.Row).EntireRow.Hidden = True
End If
Next cell
End With
End Sub
The function InStr withing your IF statement should do the trick.
IF instr(cell.value, ".doc")> 0 then
'Code Here