Using Ms Access VBA, how do I check the value of a variable to see if it has a value other than "', " - vba

I have a variable with a string...and I want to know if it contains any value other than single quote, comma and a space ("', ") I'm using vba in excel.
for example, i have a varible strA = "'test', 'player'"
I want to check to see if strA has any characters other than "', " (single quote, comma and space).
Thanks

Here is a strategy based on Count occurrences of a character in a string
I don't have vba handy, but this should work. The idea is to remove all these characters and see if anything is left. text represents your string that is being tested.
Dim TempS As String
TempS = Replace(text, " " , "")
TempS = Replace(TempS, "," , "")
TempS = Replace(TempS, "'" , "")
and your result is Len(TempS>0)
Another approach is to use recursion by having a base case of false if the string is empty, if the first character is one of the three call ourselves on the rest of the string, or if not the value is true. Here is the code
function hasOtherChars(s As String) As Boolean
hasOtherChars=false
if (len(s)=0) then
exit function
end if
Dim asciiSpace As Integer
asciiSpace = Asc(" ")
Dim asciiComma As Integer
asciiComma= Asc(",")
Dim asciiApostrophe As Integer
asciiApostrophe = Asc("'")
Dim c as Integer
c = Asc(Mid$(s, 1, 1))
if ((c=asciiSpace) or (c=asciiComma) or (c=asciiApostrophe)) then
hasOtherChars = hasOtherChars(Mid$(s,2))
else
hasOtherChars=true
end if
End function
Again I am borrowing from the other thread.

Related

MS Access VBA: Split string into pre-defined width

I have MS Access form where the user pastes a string into a field {Vars}, and I want to reformat that string into a new field so that (a) it retains whole words, and (b) "fits" within 70 columns.
Specifically, the user will be cutting/pasting variable names from SPSS. So the string will go into the field as whole names---no spaces allowed---with line breaks between each variable. So the first bit of VBA code looks like this:
Vars = Replace(Vars, vbCrLf, " ")
which removes the line breaks. But from there, I'm stumped---ultimately I want the long string that is pasted in the Vars field to be put on consecutive multiple lines that each are no longer than 70 columns.
Any help is appreciated!
Okay, for posterity, here is a solution:
The field name on the form that captures the user input is VarList. The call to the SPSS_Syntax function below returns the list of variable names (in "Vars") that can then be used elsewhere:
Vars = SPSS_Syntax(me.VarList)
Recall that user input into Varlist comes in as each variable (word) with a line break in between each. The problem is that we want the list to be on one line (horizontal, not vertical) AND a line can be no more than 256 characters in length (I'm setting it to 70 characters below). Here's the function:
Public Function SPSS_Syntax(InputString As String)
InputString = Replace(InputString, vbNewLine, " ") 'Puts the string into one line, separated by a space.
MyLength = Len(InputString) 'Computes length of the string
If MyLength < 70 Then 'if the string is already short enough, just returns it as is.
SPSS_Syntax = InputString
Exit Function
End If
MyArray = Split(InputString, " ") 'Creates the array
Dim i As Long
For i = LBound(MyArray) To UBound(MyArray) 'for each element in the array
MyString = MyString & " " & MyArray(i) 'combines the string with a blank space in between
If Len(MyString) > 70 Then 'when the string gets to be more than 70 characters
Syntax = Syntax & " " & vbNewLine & MyString 'saves the string as a new line
MyString = "" 'erases string value for next iteration
End If
Next
SPSS_Syntax = Syntax
End Function
There's probably a better way to do it but this works. Cheers.

How to replace a character within a string

I'm trying to convert WText into its ASCII code and put it into a TextBox; Numencrypt. But I don't want to convert the spaces into ASCII code.
How do I replace the spaces with null?
Current code:
Dim withSpace As String = Numencrypt.Text
For h = 1 To lenText
wASC = wASC & CStr(Asc(Mid$(WText, h, 1)))
Next h
Numencrypt.Text = wASC
Numencrypt2.Text = Numencrypt2.Replace(Numencrypt.Text, " ", "")
By the way, the TextBox Numencrypt2 is the WText without a space inside it.
Without knowing whether or not you want the null character or empty string I did the following in a console app so I don't have your variables. I also used a string builder to make the string concatenation more performant.
Dim withSpaces = "This has some spaces in it!"
withSpaces = withSpaces.Replace(" "c, ControlChars.NullChar)
Dim wASC As New StringBuilder
For h = 1 To withSpaces.Length
wASC.Append($"{AscW(Mid(withSpaces, h, 1))} ") ' Added a space so you can see the boundaries ascii code boundaries.
Next
Dim theResult = wASC.ToString()
Console.WriteLine(theResult)
You will find that if you use ControlChars.NewLine as I have, the place you had spaces will be represented by a zero. That position is completely ignored if you use Replace(" ", "")

reverse some text in cell selected - VBA

I'm rooky for VBA. I have some problem about reversing my data on VBA-Excel. My data is "3>8 , 6>15 , 26>41 (each data on difference cells)" that i could reverse "3>8" to "8>3" follow my requirement by using function reverse. But i couldn't reverse "6>15" and "26>41" to "15>6" and "41>26". It will be "51>6" and "14>62" that failure, I want to be "15>6" and "41>26".
Reverse = StrReverse(Trim(str))
Help me for solve my issue please and thank for comment.
You first need to find the position of the ">" in the cell. you do this by taking the contents of the cell and treating it as a String and finding the ">"
This is done in the line beginning arrowPosition. This is the integer value of the position of the ">" in you original string
Next use Left to extract the text up to the ">" and Right to extract the text after the ">"
Then build a new String of rightstr & ">" & leftStr.
Note I input my data from Sheet1 B5 but you can just use any source as long as it is a String in the correct format.
Sub Test()
Dim myString As String
myString = Sheets("Sheet1").Range("B5")
Debug.Print myString
Debug.Print reverseString(myString)
End Sub
Function reverseString(inputString As String) As String
Dim leftStr As String
Dim rightStr As String
Dim arrowPosition As Integer
arrowPosition = InStr(1, inputString, ">")
leftStr = Left(inputString, arrowPosition - 1)
rightStr = Right(inputString, Len(inputString) - arrowPosition)
reverseString = rightStr & ">" & leftStr
End Function
just because you look for a VBA, you can add this function into your code:
Function rev(t As String) As String
s = Split(t, ">", 2)
rev = s(1) & ">" & s(0)
End Function
of course only if you have to reverse 2 number, otherwise you'll loop the "s", but the function would lose its usefulness

Variable truncates when using messagebox

I have a strange problem here. In my code, variable b string, has the value "Test Test Test". This value we can see while debugging the variable as well as in the text visualizer.
Now the problem is, if I show the same string using Messagebox, the value is just "Test". What can I do here to get the complete value.
I am converting from an ebcdic encoded bytes to corresponding utf8 string and doing the above operation. Any thoughts. below is my sample code.
Dim hex As String = "e385a2a300000000e385a2a3000000e385a2a3"
Dim raw As Byte() = New Byte((hex.Length / 2) - 1) {}
Dim i As Integer
For i = 0 To raw.Length - 1
raw(i) = Convert.ToByte(hex.Substring((i * 2), 2), &H10)
Next i
Dim w As String = System.Text.Encoding.GetEncoding(37).GetString(raw)
Dim raw1 As Byte() = Encoding.UTF8.GetBytes(w)
Dim b As String = Encoding.UTF8.GetString(raw1)
MessageBox.Show(b)
Look at the byte array. You have 4 ASCII 0's after each "Test". ASCII character code 0 corresponds to nul, which is a string termination sequence. If you want spaces instead of nulls there...
Dim b As String = Encoding.UTF8.GetString(raw1).Replace(Chr(0), " ")
It is possible that the string "b" might contains some control character.
To test a control char in string.
For Each p As Char In b
MsgBox(p & " " & Char.IsControl(p) & " " & AscW(p))
Next
Use String#Replace to replace control chars.
b = b.Replace(ChrW(0), " ")
MsgBox(b)

Trim last "," delimiter of a string in VB.NET

This is my code:
With ad.Tables(2)
For i As Integer = 0 To .Rows.Count - 1
If .Rows(i)("name") & "" <> "" Then
temp &= .Rows(i)("name") & ", "
End If
Next
End With
temp = temp.Trim(",")
testing &= "&Name=" & temp & vbCrLf
With this is get a comma in the end of the string. But if I do
temp = temp.Trim.Trim(",")
all commas are deleted.
How do I keep all commas and only delete the last one?
temp = temp.TrimEnd(CChar(","))
That will do it and I think it is the easiest way.
temp = temp.Trim().Substring(0, temp.Length - 1)
or
temp = temp.Trim().Remove(temp.Length - 1)
You can avoid the Trim/extra character if you set a delimiter within the loop
Dim delimiter as string = ""
For i As Integer = 0 To .Rows.Count - 1
If .Rows(i)("name") & "" <> "" Then
temp &= delimiter & .Rows(i)("name")
delimiter = ","
End If
Next
The Trim() function has a Char() (static array of characters) parameter on it, you don't need to pass a Char explicitly.
' VB.Net Version
", Hello ^_^ ^_^ ,,, , ,, ,, ,".Trim({" "c, ","c})
//C# version
", Hello ^_^ ^_^ ,,, , ,, ,, ,".Trim({' ', ','})
Would produce the output
"Hello ^_^ ^_^"
The multi-parameter .Trim() removes the specified characters from both the beginning and the end of the string. If you want to only trim out the beginning or the end, use .TrimStart() or .TrimEnd() respectively.
This works:
dim AlarmStr as string="aaa , bbb , ccc , "
AlarmStr = AlarmStr.Remove(AlarmStr.LastIndexOf(","))
Check to see if the loop is done before adding the last comma. #cleaner
While dr.Read
For c As Integer = 0 To dr.FieldCount - 1
s.Append(dr(c).ToString.Trim)
'This line checks if the loop is ending before adding a comma
If (c < dr.FieldCount - 1) Then s.Append(",")
Next
s.Append(vbCrLf)
End While
I wonder, that based on the OP's code sample, nobody suggested to use String.Join or build an output with StringBuilder
Dim names As New List(Of String)
With ad.Tables(2)
For i As Integer = 0 To .Rows.Count - 1
' DataRow("columnName").ToString() returns value or empty string if value is DbNull
If .Rows(i)("name").ToString() <> "" Then
names.Add(.Rows(i)("name"))
End If
Next
End With
Dim temp As String = String.Join(", ", names)
testing &= "&Name=" & temp & vbCrLf
With LINQ and DataRow extension method .Field(Of T) code will look simpler
Dim names = ad.Tables(2).
AsEnumerable().
Select(row => row.Field<String>("name")).
Where(name => String.IsNullOrEmpty(name) = False)
Dim temp As String = String.Join(", ", names)
testing &= "&Name=" & temp & vbCrLf
If you go further you can(should) use StringBuilder for building a string and use Aggregate method to build string from the collection
I know that a little bit odd, but I found this works for me:
Visual Basic:
Every time: mystring = "today, I love go out , , , ," (less than five commas and spaces)
mystring.Trim.TrimEnd(",").Trim.TrimEnd(",").Trim.TrimEnd(",").Trim.TrimEnd(",").Trim.TrimEnd(",")
temp = temp.TrimEnd()
this trims the trailing spaces from a string.