Excel VBA problems with combined cells [duplicate] - excel

This question already has answers here:
Get value of a merged cell of an excel from its cell address in vba
(4 answers)
Closed 1 year ago.
I am writing a Excel VBA program to generate text.
I am using IF statements to find out if some specific text is in in a cell and concatenate a string based on that.
I have a problem with combined cells:
IF Cells(1,1) Like "A" and Cells(1,2) Like "---" Then
concatenate something
end if
The above works
IF Cells(2,1) Like "B" and Cells(2,2) Like "---" Then
concatenate something
end if
This does not work, because the Cell(2,2) is empty according to
MsgBox (Cells(2, 2).Value) instead of the "---".
Is it possible to get the code to work, without splitting the cells again?
I would like to go row by row concatenating text, the VBA code should recognize the cellvalue one cell right to "B" as "---".

Cells(1,1).Value is "A". Cells(1,2).Value is "---".
Cells(2,1).Value is empty. Cells(3,2).Value is empty.
Cells(3,1).Value is "B". Cells(3,2).Value is empty.
Just because you merge the cells above, doesn't change that the cell is in Row 3. Only the top-left cell in a Merged Range has a value. (Although, there are ways around that.)
You can check if a cell is merged using Range.MergeCells. You can get the value of a Merged Cell using Range.MergeArea
For example:
Cells(1,1).MergeArea.Cells(1,1) is "A". Cells(2,2).MergeArea.Cells(1,1) is "---". Cells(1,1).MergeCells is True.
Cells(2,1).MergeArea.Cells(1,1) is "A". Cells(2,2).MergeArea.Cells(1,1) is "---". Cells(2,1).MergeCells is True.
Cells(3,1).MergeArea.Cells(1,1) is "B". Cells(3,2).MergeArea.Cells(1,1) is "---". Cells(3,1).MergeCells is False.
If you are using a loop to run through the cells, consider using a While or Do instead of a For, since you can increment by different numbers for each iteration:
Dim rowCurrent AS Long
rowCurrent = 1
While Cells(rowCurrent,1).Value <> ""
If Cells(rowCurrent,2).MergeArea.Cells(1,1).Value = "---" Then
Select Case Cells(rowCurrent,1).MergeArea.Cells(1,1).Value
Case "A"
'concatenate something
Case "B"
'concatenate something else
Case "C"
'concatenate a third thing
Case Else
'throw an error?
End Select
End If
'Skip the rest of the merged cell
rowCurrent = rowCurrent + Cells(rowCurrent,1).MergeArea.Rows.Count
Wend

Related

Change the value of a column with vba code rather than loop

I want to add "#" before each cell in a column (have more than 13000 cells), and add "000" to another column through vba excel code. I can achieve this with loop but it takes a long time when running the macro. Can anyone help me with more effective solutions?
for each cell in column
cell = "#"& cell
next cell
for each cell in column
select case len(cell)
case 2: cell = "'000" & cell
case 3: cell = "'00" & cell
end select
next cell
Desired result:
456 => #456
10 => 00010
however it runs very slowly.
Use display format:
Range("A1:A1300").NumberFormat = "\##"
Range("B1:B1300").NumberFormat = "00000"
This does not change the underlying value, but it will display correctly.
To read the value out use Cell.Text to retrieve a string with the leading zeros.

Excel VBA Clear Contents

I have a column in excel sheet that contains the IF condition i.e.
=If(Cond 1 is TRUE, X, Y)
Now, after using this condition, i get certain values in the column. Following format can be considered (these are actual values):
4L
4L
4L
4L
Note: The two empty cells in the above col are an outcome of the TRUE condition(entry 4 and 5, i entered total 6 entries, two are empty cells ). Therefore, they are valid. (let me call the above col "A" for future reference)
Now, these empty cells actually contains formulas (the if condition). I want to CLEARCONTENT them using VBA but it is not working.
And I'm trying the below code:
If ActiveSheet.Cells(row_no, col_no) = "" Then
ActiveSheet.Cells(row_no, col_no).ClearContents
End If
But this does not work. I just want to CLEAR CONTENT those empty cells by running a loop over the whole column. The cells of the column where TEXT exist (i.e. 4L), that should be skipped but as soon the code encounters the EMPTY CELL (which actually have an IF condition), it should CLEAR CONTENT it and complete the loop. So the final result would be again the same as column "A", the only difference would be that the empty cells will be BLANK now i.e. they will not have any IF condition.
I do not have problem running the loops but i am not getting how to tell VBA about that empty cell and clear contenting it. Hopefully i was able to post a clear query. Thanking in advance.
Regards
Nayyar
Please try the below sample code it should work..
Sub test()
'Assuming your data in column A from A2
Set Rng = Range("A2", Cells(Rows.Count, 1).End(xlUp))
For Each cell In Rng
If cell.Value = "" Then
cell.ClearContents
End If
Next
End Sub
And in your formula =If(Cond 1 is TRUE, X, Y) your not giving any output like "" which will give you blank. Please update it and then try :)
Try this as well
If (Range("A35").Value = "") Then
Range("A35").Formula = ""
End If

VBA code to recopy multiple cells if a specific cell contains a specific text

I'm new here and I apologize in advance in my question isn't clear... I couldn't find the answer after some research...
I'm looking for a way to go through all the cells of column "R" and if one cell on a given row contains "Y", then the values of cells at columns "W","X" and "Y" will take the same value as the columns "F","G" and "H" (always at the same row).
The goal is to have a button that will execute the VBA code in order to do this (instead of having to copy/paste all the time).
Thank you very much in advance for your help.
A poor ignorant but motivated VBA beginner...
Here is VBA which will do what you want. It takes advantage of the replacement operation being cells that are next to each other by using Resize.
Highlights
Iterates through each cell in column R. I used Intersect with the UsedRange on the sheet so that it only goes through cells that have values in them (instead of all the way to the end).
Checks for "Y" using InStr.
Replaces the contents of columns WXY with values from columns FGH. Since they are contiguous, I did it all in one step with Resize.
Code:
Sub ReplaceValuesBasedOnColumn()
Dim rng_search As Range
Dim rng_cell As Range
'start on column R, assume correct sheet is open
Set rng_search = Range("R:R")
For Each rng_cell In Intersect(rng_search, rng_search.Parent.UsedRange)
'search for a Y, case sensitive
If InStr(rng_cell, "Y") > 0 Then
'update the columns as desired
'takes advantage of cells being next to each other
Range("W" & rng_cell.Row).Resize(1, 3).Value = Range("F" & rng_cell.Row).Resize(1, 3).Value
End If
Next rng_cell
End Sub
I tested it on my end, and it works, producing the following after running:

excel macro : Change cell value dependant on original cell value

When recording a macro, i want to change the current value of a cell to a new value dependant on the original value. not set it to a "recorded" value.
Example : value in cell needs to change from .1234 (text) to 0,1234 (number). And
.56789 to 0,56789
My work method is:
record macro
"F2" : to change value,
"home" : go to beginning,
"del",
"del",
"0",
",",
"return",
stop record macro
but when i use the macro on other fields, the value is changed to 0,1234 even when original value is .5678 for example.
This can be done in VBA but the most simple solution (if all your values begin with ".") is to use the built in "Text to Columns" Excel option (by simply selecting your entire column then ALT+A, +E, +F). If this has to be done with VBA please tell. Hope this alone helps.
Edit I've wrote this code to solve your problem (based on the rule of the cell values are starting with "." and then switching to numbers is made by adding a "0" to the initial text). Then "number" format is picked up by Excel as implicit format.
Sub ChangeFormat()
For i = 1 To 2 'This is the row index (it's now set to the 1st 2 rows.)
For j = 1 To 2 'This is the column Index (i.e. column 2 is B, 1 is A, etc.) (it's now set to the A and B columns)
If Left(ActiveSheet.Cells(i, j), 1) = "." Then
ActiveSheet.Cells(i, j).Value = "0" & ActiveSheet.Cells(i, j).Value
End If
Next j
Next i
End Sub

VBA convert all cells in column to type text

I'm using VBA to do some further formatting to a generated CSV file that's always in the same format. I have a problem with my For Each Loop. the loop deletes an entire row if there is more than one blank row which can be determined from the first column alone.
Dim rowCount As Integer
For Each cell In Columns("A").Cells
rowCount = rowCount + 1
'
' Delete blank row
'
If cell = "" And cell.Offset(1, 0) = "" Then
Rows(rowCount + 1).EntireRow.Delete
spaceCount = 0
End If
Next
At some point the value in the loop one of the calls does not have a value of "", it's just empty and causes it to crash. To solve this I think that changing the type of the cell to text before that compare would work but I can't figure out how (no intellisense!!!)
So how do you convert a cell type in VBA or how else would I solve the problem?
Thanks.
Use cell.Value instead of the cell.Text as it will evaluate the value of the cell regardless of the formating. Press F1 over .Value and .Text to read more about both.
Be carefull with the statement For Each cell In Columns("A").Cells as you will test every row in the sheet (over a million in Excel 2010) and it could make Excel to crash.
Edit:
Consider also the funcion TRIM. It removes every empty space before and after a string. If in the cell there is a white space " "; it will look like empty for the human eye, but it has a space inside therefore is different than "". If you want to treat it like an empty cell, then try:
If Trim(cell.value) = "" then
As #andy (https://stackoverflow.com/users/1248931/andy-holaday) said in a comment, For Each is definitely the way to go. This even allows for there to be spaces in between lines.
Example code:
Sub ListFirstCol()
Worksheets("Sheet1").Activate
Range("A1").Activate
For Each cell In Application.Intersect(Range("A:A"), Worksheets("Sheet1").UsedRange)
MsgBox (cell)
Next
End Sub
Thanks Andy!

Resources