Issue with Replace function when editing strings - vb.net

So currently I am trying to update an old excel file's macro codes so that we can use it with a new program. Though I am new to VB I know some C++ and Java from college so I was able to get just about everything working but this section of code. So basically, we are converting excel information to .CVS and when we do the conversion seems to give some of the information three quotation marks on either side instead of the single set like it is listed in the excel document.
To make a simple fix I just added this extra set of code to search each string for quotation marks and remove all but a single set. Instead it seems to just continue replacing sections of the entire string until there is only 1 quotation mark left...do y'all know what the issue might be?
I know this is some poorly written code especially since I havent moved on to fix the infinite loop BUT the main concern right now is just how I am misusing the Replace function.
For X = 1 To 56
String2 = Sheets(1).Cells(X, 1)
Z = 1
Do While Z <> Len(String2)
If Mid(String2, Z, 1) = Chr(34) Then
If Mid(String2, Z + 1, 1) = Chr(34) Then
String2 = Replace(String2, """", "", Z, 1)
' Replace(String2, Char(34) + Char(34), "", Z, 1)
Sheets(1).Cells(X, 1) = String2
Z = 1
Else
Z = Z + 1
End If
Else
Z = Z + 1
End If
Loop
Next
The File Information being altered:
"MH 7 to Tipton1",7.942,1,1,0.22
4.9,1,18.8
"SINGLE CABLE",15,206.8
""--""",0,0 ^^ This is a string that gets eaten by the Replace
function after a few loops. It continues till (",0,0") Previous
strings were not altered in operation.
0,"""--""",0,"""H""","""--""",100,21.1
0,"""--""",0,"""VU""","""U""",200,5.1
5.1,"""U""",0,"""N""","""--""",0,0
0,"""--""",0,"""H""","""--""",100,21.4
0,"""--""",0,"""VU""","""U""",200,6.5
0,"""--""",0,"""VD""","""U""",100,11.5
0,"""--""",0,"""N""","""--""",0,0
0,"""--""",0,"""VU""","""U""",100,11.5
0,"""--""",0,"""VD""","""U""",100,11.5
0,"""--""",23.1,"""N""","""--""",0,0
0,"""--""",0,"""VU""","""U""",100,3.6
0,"""--""",0,"""VD""","""U""",100,3.6
0,"""U""",120.8,"""N""","""--""",0,0
0,"""--""",0,"""H""","""--""",12,30.9
"Test4.pll"

I cant quite tell from your question but if all you are trying to do is replace triple quotes and with single quotes then you can remove the entire do loop and just put
string2=replace(string2,"""""""","""")
inside the for loop to replace contents of the entire string rather than just each character.
So
For X = 1 To 56
String2 = Sheets(1).Cells(X, 1).value
String2 = Replace(String2, """""""", """")
Sheets(1).Cells(X, 1).value = String2
Next
or even
For X = 1 To 56
Sheets(1).Cells(X, 1).value = Replace(Sheets(1).Cells(X, 1).value, """""""", """")
Next
EDIT
You'll also want to use .value for getting the cell value

Related

VBA USING TWO DIFFERENT RESULT USING countif VARIABLE

Good Evening
I have a problem on VBA ​I have a variable as countif
Dim Y As Integer
Y = Application.WorksheetFunction.CountIf(Worksheets("Calc_Giac").Range("I11:EZ11"), ">0")
So If I use the variable in a formula
Range("B21").Formula = "=SumIF((I11:EZ11), "">0"") / (" & Y & ")"
The value is correct
But if use in a condition the result is the variable*-1
If ("(" & Y & ")" > 0) Then
Range("L19") = "(" & Y & ")"
Else
Range("L19") = "HELLO"
End If
Any Idea about it?
First: You have a strange if-condition. Let's assume that Y has the value 3 as a result of your CountIf: "(" & Y & ")" resolves in a String "(3)". After that, you check if the string "(3)" is greater that 0. That makes no sense. Try
If Y > 0 then
Second: You write the String "(3)" into a cell. Now depending on how the cell is formatted, either you have "(3)" (as String) in the cell (when the cell is formatted as Text), or Excel tries to convert the string "(3)" into a number. However, numbers in Excel that are entered with brackets are interpreted as negative numbers (try it by entering "(3") into a cell manually. Use:
Range("L19").Value = 3
However, within the formula, =SumIF((I11:EZ11), "">0"") / (3), the (3) is just part of the calculation and the brackets tells Excel to evaluate anything within the brackets first before continuing the calculation. As 3 is already evaluated, there is nothing to do so the brackets are ignored.

VBA, 'Left' Different Strings Dynamically

Having trouble shortening strings in a column but making it dynamic for a directory. Ex: 3 strings in a column, 1 string may continue for 10 rows, another string 20 rows, and another for 15 rows. Each needing to be shorted a different amount
Specifically: I had several words that are either sepearated by a -, _ , +. So example one sheet has pv01_52352, pv+50, pv-100, irvega_242422, so the irvega word works. but for the pv's i am struggling with. The desired results are the works before the special characters, so it would be pv01, pv and irvega as a desired result .
How can I use left or anyway to shorten these all? It is quite hard for me since for one string ill need the first 4 characters, then another 5 characters to be shortened and will need to be done throughout a workbook.
Any input would be appreciated, Thanks.
I've found that determining the ASCII character number with the CODE function (using UPPER function to reduce the possibilities) produces satisfactory results.
        
The array formula in B2 for strictly alphabetic characters is,
=LEFT(A2, MIN(ROW(INDIRECT("1:"&LEN(A2)))+((CODE(MID(UPPER(A2), ROW(INDIRECT("1:"&LEN(A2))), 1))>64)*(CODE(MID(UPPER(A2), ROW(INDIRECT("1:"&LEN(A2))), 1))<91))*1E+99)-1)
An array formula in B2 for alphanumeric characters is,
=LEFT(A2, MIN(ROW(INDIRECT("1:"&LEN(A2)))+(((CODE(MID(UPPER(A2), ROW(INDIRECT("1:"&LEN(A2))), 1))>64)*(CODE(MID(UPPER(A2), ROW(INDIRECT("1:"&LEN(A2))), 1))<91))+((CODE(MID(A2, ROW(INDIRECT("1:"&LEN(A2))), 1))>47)*(CODE(MID(A2, ROW(INDIRECT("1:"&LEN(A2))), 1))<58)))*1E+99)-1)
Array formulas need to be finalized with Ctrl+Shift+Enter↵.
A VBA User Defined Function (aka UDF) for strictly alphabetic characters would be,
Function just_the_alpha(str As String)
Dim tmp As String, c As Long
For c = 1 To Len(str)
If Asc(Mid(UCase(str), c)) > 64 And _
Asc(Mid(UCase(str), c)) < 91 Then
tmp = tmp & Mid(str, c, 1)
Else
Exit For
End If
Next c
just_the_alpha = tmp
End Function
A VBA UDF for alphanumeric characters would be,
Function just_the_alphanum(str As String)
Dim tmp As String, c As Long
For c = 1 To Len(str)
If (Asc(Mid(UCase(str), c)) > 64 And _
Asc(Mid(UCase(str), c)) < 91) Or _
(Asc(Mid(str, c)) > 47 And _
Asc(Mid(str, c)) < 58) Then
tmp = tmp & Mid(str, c, 1)
Else
Exit For
End If
Next c
just_the_alphanum = tmp
End Function

VBA Excel 2013 Finding specific string length and adding a value

I am trying to write a macro to find if a cell has 5 numeric values and if it does, I need to add a 0 at the end.
My macro already has some steps in it.
For example
Cell BZ2 = 9.48E+00
My macro finds the decimal point and replaces it with 94811E-5
I need to add a Zero in this case, because there are 5 numeric values, AND only when the last three characters are E-5.
Expected result is 948110E-5.
I am using a number stored as text.
Can anyone help me out?
Sub TextFormat()
Dim c As Range
Dim d As Range
For Each c In Sheets("order_export").Range("F2:F10000").Cells
If StrComp(Right(c.Value, 1), "R", vbTextCompare) = 0 Then
c.Offset(0, -1).Value = c.Offset(0, -1).Value & "R"
c.Value = Left(c.Value, Len(c.Value) - 1)
End If
Next c
For Each d In Sheets("order_export").Range("BZ2:BZ10000").Cells
If InStr(1, d.Value, ".", vbTextCompare) > 0 Then
d.NumberFormat = "#"
d.Value = Replace(d.Value, ".", "")
d.Value = d.Value & "E-5"
End If
Next d
End Sub
using this conditional
if isNumeric(left(text,5)) AND right(text,3) = "E-5" then
'add zero
text = left(text,5) & "0" & right(text, len(text) - 5)
end if
will add the 0 after the first 5 if the first 5 characters are numeric and the last 3 are e-5. the left function takes the first 5 characters. the isNumeric checks if they are numeric. and then the rest, takes the first 5 characters, puts a 0, and then the right takes all characters starting from the right going up till length - 5 (we already have the first 5 characters)
edit
as pointed out, if there is already a 0, like 123450E-5 then an extra would be added.
add ANd len(text) = 8 so that it only adds the 0 if there are 8 characters.
Excel doesn't short circuit so for coding efficiency it is better to break an AND into IF's with the most likely errors first, then the breaches
Also never using the variant functions Left and Right use string functions Left$ and Right$ instead
This link is an excellent resource re coding optimisation.
Re-cutting the earlier answers would be something like this:
c = "94811E-5"
If Len(c) = 8 Then
If IsNumeric(Left$(c, 5)) Then
If Right$(c, 3) = "E-5" Then c = Left$(c, Len(c) - 3) & "0" & Right$(c, 3)
End If
End If
MsgBox c

Expression too complex error

I know this question gets asked quite a bit, but I haven't seen an answer that I can apply to my issue. It seems that this error can be caused by quite a few things.
First of all, here is the code:
SurfArea = 19.63495408
Volume = 12.2718463
DeSimpleFinal = 0.009336098
Counter = 13
pi = 4*atn(1)
tracker = 0
stepamount = (Range("A" & Counter + 1).Value) / 1000
If Range("XFD1048508").Value = 1 Then
For x = 0 To Range("A" & Counter + 1).Value Step Stepamount
tracker = tracker + 1
ActiveSheet.Range("XEY" & tracker).Value = ((2 * SurfArea) / Volume) * Sqr((DeSimpleFinal * x) / pi)
ActiveSheet.Range("XEX" & tracker).Value = x
Next
Else
End If
I've decided to leave (Range("A" & Counter + 1).Value) on, because I think it might be relevant to why the code is breaking down. That cell is A14 and has the value 11 inside of it.
The line that gets flagged when I debug is the first line of the For loop. The loop doesn't even go through one iteration.
Does anybody have an idea of what it could be? I changed all my data types to variant to see if that was the issue, but that did nothing. Thank you for your help!
EDIT: I should note that the value of that range SHOULD be one, so that it does go through the loop.
I don't know anywhere enough about VBA's internals to understand why, but I do know that simplifying the expression that sets the limit on a FOR loop will eliminate the Error 16 - Expression Too Complex problem. (The response to this SO post as well as discussion elsewhere on the web comes to pretty much the same conclusion.)
Just declare a new variable, say, StopAmount, assign to it the expression you used in the FOR condition, and then replace the expression in the FOR with the name of the new variable. You get something like:
StopAmount = Range("A" & Counter + 1).Value
......
For x = 0 To StopAmount Step Stepamount
......
That said, there are certainly some oddities here.
For example, your original FOR condition worked fine if the iterator variable x is declared as a Variant, either implicitly or explicitly. (I declared all the variables for my tests.)
However, if x is dimensioned as a Double, the error returned. This is despite the fact that TypeName(x) showed the Variant x as a Double after the Range(..).Value assignment is made.
For x = 0 To Range("A14").Value Step Stepamount also ran with no problem.
And For x = 0 To Cells(Counter + 1, 1).Value Step Stepamount worked, too.

Using trim function with special characters

I have a column (A) of values that I would like to trim to the left. Each value in column A has a / in it which separates a word in German and it's English translation. For example one value would be "nein / no". (note there is a space between the two words.
What I want to do is write a trim function that starts after the space that follows the /. In othe words I want the value in my example to trim from "nein / no" to just "no". The part that confuses me is the fact that each value changes in size so I don't know how to tell excel where to trim from. My code should look something like this
For each cl in range("A1:A300"). Trim cl.value. Next cl
Try below code :
Dim start As Long
For Each cl In Range("A1:A300")
str = c1
start = InStr(1, str, "/", vbTextCompare) + 1
strVal = Trim(Right(str, Len(str) - start))
msgbox strVal
Next cl
Start with something like this:
For each cl in Range("A1:A300")
With cl
.Value = Trim(Len(.Value) - Right(.Value, _
Application.WorksheetFunction.Find("/", .Value)))
End With
Next
You don't need VBA to solve this. A simple formula will suffice:
=RIGHT(A1,LEN(A1)-FIND(" ",A1,FIND(" ",A1)+1))
nein / no = no
lederhosen / breeches = breeches
doppelganger / doppelganger = doppelganger