How to check the value of Σ character in an Excel Cell? - VBA - excel

I do have a cell in excel that contains Σh. Not sure how to check for it in vba. I have tried with .Value and .Text, but the check is never true.
If (tRange.Value = (ChrW(931) + "h")) Then
Exit Sub
End if
When testing (Debug) I get this result for ActiveCell.Value = Sh

(a) You have to use .Value to get the content of the cell.
(b) You should use the ampersand character (&) to concatenate strings in VBA. The plus-sign works also, but only if all operands are strings.
(c) ChrW(931) & "h" (or ChrW(931) + "h") should work. VBA is able to handle characters even if the VBA-environment cannot show them.
Seems to me that either the Sigma-character is composed with a different character, or your cell contains invisible characters like space, newline, tabs...
You can dump the content of the cell with the following code to get an idea why your If-statement fails:
Sub DumpString(s As String)
Dim i As Long
For i = 1 To Len(s)
Dim c As String
c = Mid(s, i, 1)
Debug.Print i, AscW(c), c
Next
End Sub
When you enter the following command into the immediate window, you will see output like that:
DumpString activecell.Value
1 931 S
2 104 h

This should check if cell value contains the sub-string 'Σh'
If tRange.Value Like "*" & ChrW(931) & "h*" Then
Exit Sub
End If
Another maybe simpler way for some folks
If InStr(1, tRange.Value, ChrW(931) & "h") <> 0 Then
Exit Sub
End If

You have to use an ampersand to join the two characters:
If (tRange.Value = ChrW(931) & "h") Then
Exit Sub
End if

Related

Removing brackets inside a formula

So I created a macro that muliplies a cell value with 100 (10^2). If the cell is simply a value it justs multiplies the cell value with 100, however if it's a formula it puts the formula in brackets and adds a 100* to the beginning
As you can't undo a macro easily but I need it, I tried to create an "undo" macro.
The Cell Value-Undo is quite easy, however for the formulas I struggle to delete the outer brackets.
An example process would be:
Original: =1+1 becomes =100*(1+1) and the undo should return to =1+1 (without brackets).
This is my code for the multiplication:
Private Sub MultiplySelectionBy100(Control As IRibbonControl)
Dim Cell As Range
For Each Cell In Selection
If Len(Cell.Value) > 0 And Application.IsNumber(Cell.Value) Then
If Cell.HasFormula Then
Cell.Formula = Replace(Cell.Formula, "=", "=100*(") & ")"
Else
Cell.Value = 100 * Cell.Value
End If
End If
Next
Application.OnUndo "Undo something", "UnDoSomething"
End Sub
For the UNDO, this is what I have so far:
Public Sub UnDoSomething()
Dim Cell As Range
Dim bet As String
For Each Cell In Selection
If Len(Cell.Value) > 0 And Application.IsNumber(Cell.Value) Then
If Cell.HasFormula Then
Cell.Formula = Replace(Cell.Formula, "=100*(", "=") 'This is not running
Cell.Formula = Replace(Cell.Formula, Chr(41), Chr(0))
Else
Cell.Value = 100 / Cell.Value
End If
End If
Next
End Sub
I don't know how to attach multiple replace functions but it gives me an error every time (mostly because I delete a opening bracket but the closing bracket remains).
I also can't delete all brackets as there may be more brackets inside the formula.
Maybe you have an idea...
Your main problem is that the first replace command will set the formula invalid because the closing ")" is still there, and Excel (not VBA) doesn't allow an invalid formula, so you get a runtime error (1004).
You should use an intermediate variable to handle the string manipulation of the formula, and only if that is done completely, assign the formula back to the cell. Using intermediate variables is always a good idea if you are dealing with formulas in VBA - you can check with the debugger if the formula looks really as expected before you write it back to the cell.
You need to be careful with your second replace-statement: This will remove all closing parenthesis characters, even if it has nothing to do with your "Undo". You should (a) check if you really want to remove it and (b) remove only the last closing parenthesis.
Dim f As String
f = cell.Formula
If Left(f, 6) = "=100*(" Then
f = Replace(cell.Formula, "=100*(", "=")
f = Left(f, Len(f) - 1)
cell.Formula = f
End If
Or, maybe easier
If Left(f, 6) = "=100*(" Then
f = "=" & Mid(f, 7, Len(f) - 7)
cell.Formula = f
End If

Excel - VBA : How do I replace the last 3 characters if they are "..."

Please could you help me a little bit? I am a complete beginner, I don't know anything about programming.
I have the following code that changes double spaces into single spaces and deletes "..." if it's at the beginning of the selected cell(s).
Sub Test()
Dim X As Long, Cell As Range
For Each Cell In Selection
For X = Len(Cell.Text) To 1 Step -1
If Cell.Characters(X - 1, 2).Text = " " Then Cell.Characters(X, 1).Text = ""
If Cell.Characters(1, 3).Text = "..." Then Cell.Characters(1, 3).Text = ""
Next
Next
End Sub
Please could you tell me how I could change the part If Cell.Characters(1, 3).Text so that it removes "..." if it's at the end of the selected cell(s)?
This is not that easy as may seem, since Excel has the inclination to adjust three dots into an ellipsis, making it a single character that's unrecognizable when compared to a dot (or three). Furthermore, you don't need to loop characters 1 by 1, instead you could use Like to check if a cell is ending with the three dots, or rather the ellipsis. Next to that, we can trim excessive space characters in a Range in one go, using Application.Trim() as shown here.
So let's look at example data like:
Then if we select this Range and go over its cells using, for example:
Sub Test()
Dim cl As Range
For Each cl In Selection
If cl.Value Like "*..." Then
cl.Value = Left(cl.Value, Len(cl.Value) - 3)
ElseIf cl.Value Like "*" & ChrW(8230) Then
cl.Value = Left(cl.Value, Len(cl.Value) - 1)
End If
Next
Selection.Value = Application.Trim(Selection)
End Sub
The results would then be:
And for the sake of fun alternatives, a RegEx approach:
Sub Test2()
Dim cl As Range
With CreateObject("vbscript.regexp")
.Global = True
.Pattern = "…$|\.{3}$"
For Each cl In Selection
cl.Value = .Replace(cl.Value, "")
Next
End With
Selection.Value = Application.Trim(Selection)
End Sub
Maybe this can help you: Use the replace methode to change two spaces into one space. To search for three points at the beginning use the left methode and if it's the case, cut it out with the right methode. Here you have to watch out. Excel often replace three point by the character 133. So you have additional to test for it.
Sub Test()
Dim cell As Range
For Each cell In Selection
cell.Value = Replace(cell.Value, " ", " ")
If Left(cell.Value, 3) = "..." Then
cell.Value = Right(cell.Value, Len(cell.Value) - 3)
End If
If Left(cell.Value, 1) = Chr(133) Then
cell.Value = Right(cell.Value, Len(cell.Value) - 1)
End If
Next
End Sub
I think you can use Characters(1,3).Insert("") to change the text
Sub Test()
Dim c As Range
Selection.Value = Application.Trim(Selection)
For Each c In Selection
If c.Characters(1,3).Text = "..." Then c.Characters(1,3).Insert("")
Next
End Sub

Adding a space between two words once

I completed code to remove any data in front of a string, add some text (with a space) to the front and store it back in the cell.
However, every time I run the macro (to check if changes that I've made are working for example), a new space is added in between the words.
The code that removes anything before the name and adds the required string. I have called a InStr function and stored the value in integer pos. Note that this is in a loop over a specific range.
If pos > 0 Then
'Removes anything before the channel name
cellValue.Offset(0, 2) = Right(cell, Len(cell) - InStr(cell, pos) - 2)
'Add "DA" to the front of the channel name
cellValue.Offset(0, 0) = "DA " & Right(cell, Len(cell) - InStr(cell, pos) - 2)
'Aligns the text to the right
cellValue.Offset(0, 2).HorizontalAlignment = xlRight
End If
An additional "DA" is not being added and I haven't made any other functions to add spaces anywhere. The extra space is not added if adding "DA " is changed to "DA".
I'd prefer not to add another function/sub/something somewhere to search and remove any extra spaces.
What the string is AND what is in front of the string is unknown. It could be numbers, characters, spaces or exactly what I want it to be. For example, it could be "Q-Quincey", "BA Bob", "DA White" etc. I thought that searching through the cell for the string I want (Quincey, Bob, White) and altering the cell as needed would be the best way.
Solution that you all helped me come up with:
If pos > 0 Then
modString = Right(cell, Len(cell) - InStr(cell, pos) - 2)
'Removes anything before the channel name and places it in the last column
cellValue.Offset(0, 2) = modString
'Aligns the last column text to the right
cellValue.Offset(0, 2).HorizontalAlignment = xlRight
cellValue.Offset(0, 2).Font.Size = 8
'Add "DA" to the front of the channel name in the rightmost column
If StartsWith(cell, "DA ") = True Then
cellValue.Replace cell, "DA" & modString
Else
cellValue.Replace cell, "DA " & modString
End If
End If
Maybe this is something you can work with:
Sample data:
Sample code:
Sub Test()
With Sheet1.Range("A1:A4")
.Replace "*quincey", "AD Quincey"
End With
End Sub
Result:
In your examples, it seems you want to replace the first "word" in the string with something else. If that is always the case, the following function, which makes use of Regular Expressions, can do that:
Option Explicit
Function replaceStart(str As String, replWith As String) As String
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
With RE
.Global = False
.MultiLine = True
.Pattern = "^\S+\W(?=\w)"
replaceStart = .Replace(str, replWith)
End With
End Function
Sub test()
Debug.Print replaceStart("Q-Quincy", "DA ")
Debug.Print replaceStart("BA Bob", "DA ")
Debug.Print replaceStart("DA White", "DA ")
End Sub
The debug.print will -->
DA Quincy
DA Bob
DA White
The regular expression matches everything up to but not including the first "word" character that follows a non-word character. This should be the second word in the string.
A "word" character is anything in the set of [A-Za-z0-9_]
Seems to work on the examples you present.
If you wanted to go about it through a loop you should remove some redundancies in your code. For instance, refering to cell.offset(0,0) doesn't make sense.
I would set the target cells to a range and simply edit that cell with out placing the unwanted strings in another cell.
**EDIT:
I'd try something like this.**
nameiwant = "Quincy"
Set cell = Range("A1")
If InStr(cell, nameiwant) > 0 And Left(cell, 3) <> "DA " Then
cell.Value = "DA " & nameiwant
End If

Remove characters from string (String normalization?)

I am attempting to remove characters from a string in excel by utilizing a VBA macro.For example the string is "UOZV3A-WB1○1.8ml vbn958Xzlv2" and I need it to return "UOZV3A-WB1". It is pretty straight forward, the code I am using is:
For Each c In Range("D2:D69")
If InStr(c.Value, "?") > 0 Then
c.Value = Left(c.Value, InStr(c.Value, "?") - 1)
End If
Next c
The issue I am running into is a single character in the string ("o") is unrecognized by the macro. The string is entered into the cell by scanning a QR code. I suspect that "o" is a sort of placeholder that is recognized/interpreted as a "o" in excel but interpreted differently in VBA. If I try to just copy and paste the character into VBA I get a "?".
Is there a way to manipulate or interpret that character in VBA? Some of the other posts I read seemed to indicate that the string could be normalized but the coding was over my head.
Thanks!
You need to understand what character you are parsing on:
Sub junkkiller()
For Each c In Range("D2:D69")
If InStr(c.Value, ChrW(9675)) > 0 Then
c.Value = Left(c.Value, InStr(c.Value, ChrW(9675)) - 1)
End If
Next c
End Sub

excel: is it possible to put a FOR statement as a formula within a cell?

can i do this =(For i=1 to 100, print i)
is there a way to put a FOR statement inside a cell WITHOUT USING VBA?
You can use an array to get the numbers 1 through 100, but you're limited on what you can do with them. You can't, for instance, concatenate in an array formula (which your pseudo code suggests). But you could SUM, AVERAGE or many other operations.
{=SUM(ROW(1:100))}
{=AVERAGE(ROW(1:100))}
{=MAX(ROW(1:100))}
The braces means enter with control+shift+enter, not just enter.
The VBA for this isn't fancy at all :-)
Option Explicit
Sub SimpleForLoop()
Dim i As Integer
For i = 1 To 100 Step 1
With ActiveWorkbook.Sheets(1).Cells(1, 1)
.Value = .Value + i
End With
Next
End Sub
The simple code above puts the value 5050 in cell A1.
If you want to concatenate a string instead, slap this code into your for-loop:
With ActiveWorkbook.Sheets(1).Cells(2, 1)
If .Value = "" Then
.Value = CStr(i)
Else
.Value = .Value & "," & CStr(i)
End If
End With
Which will print the following into cell A2:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100

Resources