index and length must refer to a location within the string vb - excel

I have to import an Excel file into an Access db. My Excel has a column called 'Description'. Usually the description is long a cell, but it can happens that is more long. If it is long more than 255 characters, I cut the string and I modify last 3 characters with '...'.
When I run the program, though, I have an error "Index and length must refer to a location within the string".
I tried even to erase the check on the length, but obviously I had this error "Field is too small to accept the amount of data you attempted to add"
If flag = 2 Then
stringVoice = grid(r, 3).Text
voc.Description = voc.Description & stringVoice
If voc.Description.Length > 255 Then
voc.Description = grid(r, 3).Text.ToString.Substring(0, 252) + "..."
End If
End If
This is the code that produced the Index and length error. Same check has done before if inside a single cell there are more than 255 characters
Case 1 'voce
id = id + 1
flag = 2
voc = New cVoce
c_Voc = voc.Cod_Chapter
p_Voc = voc.Cod_Paragraph
voc.Cod_Chapter = grid(r, 1).Text.Substring(0, 1)
voc.Cod_Paragraph = grid(r, 1).Text.Split(".")(0)
voc.Cod_Voice = Right(vett(0), 2)
If grid(r, 3).Text.Length > 255 Then
voc.Description = grid(r, 3).Text.ToString.Substring(0, 252) + "..."
Else
voc.Description = grid(r, 3).Text.ToString
If voc.Description.EndsWith("-") Then
a = Replace(voc.Description, "-", "")
voc.Description = a
End If
End If
stringVoice = voc.Description
voices.Add(voc)
but in this case I've never had an error.
Can anyone help me to fix my code?

Related

Grading system in excel sheet based on marks

I am trying to paste grades in excel sheet based on marks
i do this but this shows only F in excel sheet .. i want if anybody has marks >=80 then want to show A grade .. and if anybody hay >=70 then B
and if anybody have less than 70 then want to show F
UPDATED CODE
clc,clear all
filename = 'PROJECT..xlsx';
table = readtable(filename);
data = xlsread(filename);
[r,c] = size(data);
total_courses = c;
table.SumofMarks = zeros(r,1);
table.Percentage = zeros(r,1);
table.StudentGrade = repmat({''},r,1);
% Sum of marks in different courses and their percentage.
format bank
Sum_of_Marks = sum(data,2);
Student_Percentage = Sum_of_Marks./total_courses;
T = horzcat(Sum_of_Marks,Student_Percentage);
N = length(Student_Percentage);
table.SumofMarks = Sum_of_Marks;
table.Percentage = Student_Percentage;
for i = 1:63
sheet1=readtable(filename);
mark=sheet1{i,{'CALCULUS','DISCRETE','ECONOMICS','ISLAMIAT','STATISTICS'}};
if mark(mark<40)
grade='F';
sheet1(i,'StudentGrade')=cellstr(grade);
else
continue
end
end
writetable(table,filename)
xlswrite(filename,T,1, 'H2')
xlswrite(filename,grade,1,'J2')
these are the errors which I get
Error using getRowIndices (line 75)
Row index exceeds table dimensions.
Error in table/subsrefBraces (line 17)
[rowIndices,numRowIndices] =
getRowIndices(t, s(1).subs{1});
Error in table/subsref (line 60)
[varargout{1:nargout}] =
subsrefBraces(t,s);
Error in lab4 (line 38)
mark=sheet1{i,{'CALCULUS','DISCRETE','ECONOMICS','ISLAMIAT','STATISTICS'}};
i tried this but this code doesnt work
how i do this
i paste link where my file is located.. and I want if any student get less than 40 marks in any subject then want to show F grade.. this code shows if total marks is less than 40 .. where as I want to show if marks is less than 40 in any subject
this is the excel file
https://drive.google.com/file/d/1VQ8XxAQPu6reY0SCNV9Rxt65w1koduGA/view?usp=sharing
I don't have Excel installed, so I can't check the part about reading and writing to Excel, but you should replace
if R>=80
table.StudentGrade{i} = 'A';
elseif R>=70
table.StudentGrade{i} = 'B';
elseif R <70
table.StudentGrade{i}= 'F';
end
with
if R(i)>=80
table.StudentGrade{i} = 'A';
elseif R(i)>=70
table.StudentGrade{i} = 'B';
elseif R(i) <70
table.StudentGrade{i}= 'F';
end

replace fraction with decimal in Excel using vbscript

As part of a larger script, I am trying to replace fraction values with decimal values in excel using vbscript. I can always count on the values to have a specific column and a specific format.
Excel example expected input column B:
51-7/16
1-1/2
2
15-7/8
Excel example desired output column B:
51.4375
1.5
2
15.875
I know it will always be to a 1/16th. So my idea was to go through the list looking for each possible fraction, find a cell that contains that fraction, and replace it with the corresponding decimal.
Questions: How do I tell the script to find a cell that contains a value and how do I replace that fraction with the decimal?
closest example Search and Replace a number of characters in Excel using VBscript
Attempt:
Dim FMember (14)
FMember(0) = "-1/16"
FMember(1) = "-1/8"
FMember(2) = "-3/16"
FMember(3) = "-1/4"
FMember(4) = "-5/16"
FMember(5) = "-3/8"
FMember(6) = "-7/16"
FMember(7) = "-1/2"
FMember(8) = "-9/16"
FMember(9) = "-5/8"
FMember(10) = "-11/16"
FMember(11) = "-3/4"
FMember(12) = "-13/16"
FMember(13) = "-7/8"
FMember(14) = "-15/16"
Dim DMember(14)
DMember(0) = ".0625"
DMember(1) = ".125"
DMember(2) = ".1875"
DMember(3) = ".25"
DMember(4) = ".3125"
DMember(5) = ".375"
DMember(6) = ".4375"
DMember(7) = ".5"
DMember(8) = ".5625"
DMember(9) = ".625"
DMember(10) = ".6875"
DMember(11) = ".75"
DMember(12) = ".8125"
DMember(13) = ".875"
DMember(14) = ".9375"
Dim endRow2
endRow2 = objSheet2.UsedRange.Rows.Count
For lngPosition = LBound(FMember) To UBound(FMember)
For r = 1 To endRow2
If objSheet2.Cells(r, objSheet2.Columns("B").Column).Value = FMember(lngPosition) Then
objSheet2.replace
End If
Next
Next
Use split()
Function fract(str As String) As Double
Dim strArr() As String
If InStr(str, "-") Then
strArr = Split(str, "-")
fract = strArr(0) + Application.Evaluate(strArr(1))
Else
fract = Application.Evaluate(str)
End If
End Function
Then you can use it as a worksheet function:
=fract(A1)

Converting Byte to String in Visual Basic

I am new to VB and I am trying to get a program to output text instead of hex. I found the code online, a program called maxiCOM. Here is the link http://www.innovatic.dk/knowledg/SerialCOM/SerialCOM.htm. The source code can be downloaded at the bottom of the page.
Unfortunately, the level of coding in the program is far above my level of understanding, and I don't really get how to change the output from hex to text. I would greatly appreciate it if someone could explain to me how to do this. The snippet of the code is
Public Class MaxiTester
Dim SpaceCount As Byte = 0
Dim LookUpTable As String = "0123456789ABCDEF"
Dim RXArray(2047) As Char ' Text buffer. Must be global to be accessible from more threads.
Dim RXCnt As Integer ' Length of text buffer. Must be global too.
' Make a new System.IO.Ports.SerialPort instance, which is able to fire events.
Dim WithEvents COMPort As New SerialPort
Private Sub Receiver(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs) Handles COMPort.DataReceived
Dim RXByte As Byte
Do
'----- Start of communication protocol handling -----------------------------------------------------------
' The code between the two lines does the communication protocol. In this case, it simply emties the
' receive buffer and converts it to text, but for all practical applications, you must replace this part
' with a code, which can collect one entire telegram by searching for the telegram
' delimiter/termination. In case of a simple ASCII protocol, you may just use ReadLine and receive
' in a global string instead of a byte array.
' Because this routine runs on a thread pool thread, it does not block the UI, so if you have any data
' convertion, encryption, expansion, error detection, error correction etc. to do, do it here.
RXCnt = 0
Do
RXByte = COMPort.ReadByte
RXArray(RXCnt) = LookUpTable(RXByte >> 4) ' Convert each byte to two hexadecimal characters
RXCnt = RXCnt + 1
RXArray(RXCnt) = LookUpTable(RXByte And 15)
RXCnt = RXCnt + 1
RXArray(RXCnt) = " "
RXCnt = RXCnt + 1
SpaceCount = (SpaceCount + 1) And 31 ' Insert spaces and CRLF for better readability
If SpaceCount = 0 Then ' Insert CRLF after 32 numbers
RXArray(RXCnt) = Chr(13) ' CR
RXCnt = RXCnt + 1
RXArray(RXCnt) = Chr(10) ' LF
RXCnt = RXCnt + 1
Else
If (SpaceCount And 3) = 0 Then ' Insert two extra spaces for each 4 numbers
RXArray(RXCnt) = " "
RXCnt = RXCnt + 1
RXArray(RXCnt) = " "
RXCnt = RXCnt + 1
End If
End If
Loop Until (COMPort.BytesToRead = 0)
'----- End of communication protocol handling -------------------------------------------------------------
Me.Invoke(New MethodInvoker(AddressOf Display)) ' Start "Display" on the UI thread
Loop Until (COMPort.BytesToRead = 0) ' Don't return if more bytes have become available in the meantime
End Sub
' Text display routine, which appends the received string to any text in the Received TextBox.
Private Sub Display()
Received.AppendText(New String(RXArray, 0, RXCnt))
End Sub
System.Text.Encoding.Unicode.GetString(bytes) 'bytes is your byte array'
Notice the first line after Do in your inner loop:
RXByte = COMPort.ReadByte
This is the only point in your code where you have the actual byte value read from the COM port. After this point the code converts the byte into two hex values using bit-shifting. You should create a global variable of string type and append the read byte value to this string before it is lost.
Add the following line immediately after the above line:
YourString &= Convert.ToChar(RXByte).ToString()
where YourString is your global string variable.
Note that you can attain some efficiency by using StringBuilder instead of string, but I'm leaving that for you as exercise.

Adding a space in a String after a certain character(VB Code)

Hello everyone.
Dim txt1 As Double = Convert.ToDouble(TextBox1.Text) / 100
Dim txt2 As Double = Convert.ToDouble(TextBox2.Text)
Dim txt3 As Double = Convert.ToDouble(TextBox3.Text)
Dim txtResult As Double = Convert.ToDouble(TextBox4.Text)
Dim result As Double = txt1 * txt2 * txt3
TextBox4.Text = result
As you can see I get my result depending on what the user types in. So I have to add a space after a certain character. Textbox14.text(0) <--- after this do I want my space. It's so that after the value is higher than 999 it should type out 1 000 and not 1000. Thank you very much for any useful help, I've truly looked everywhere, I just can't find anything.
You talking about group separator. Custom Numeric Format Strings
You can use .ToString() method and define group separator in the format.
TextBox4.Text = result.ToString("0,0.000")
Different separators will be used based on the local system's language/region settings.
You can define your custome separator manually
var cultureInfo = new System.Globalization.CultureInfo("en-US");
var numberInfo = cultureInfo.NumberFormat;
numberInfo.NumberGroupSeparator = " ";
TextBox4.Text = result.ToString("0,0.000", numberInfo)
If I get it right, you want every 3 chars a space, right ?
Like 1 000 000 ?
try this :
Dim result As String, str As String, ret As String
Dim i As Integer
Dim arr As Char()
'your text to space
result = "10000000"
'reverte so we start with the end
result = StrReverse(result)
i = 0
ret = ""
' make a char array which each char is an own array element
arr = result.Take(result.Length).ToArray
'iterate through all elements
For Each str In arr
' skip the first element .
' only add a space every 3 elements
If (i <> 0) And (i Mod 3 = 0) Then
ret = ret + " "
End If
ret = ret + str
i = i + 1
Next
' revers again the output
ret = StrReverse(ret)
MsgBox(ret)

How to insert a space every two characters?

I would like to split byte strings, for example AAFF10DC, with spaces, so it becomes AA FF 10 DC.
How to do this in AutoIt (v3)?
I would like to split byte strings … with spaces …
Example using StringRegExpReplace() :
Global Const $g_sString = 'AAFF10DC'
Global Const $g_sPattern = '(.{2})'
Global Const $g_sReplace = '$1 '
Global Const $g_sResult = StringRegExpReplace($g_sString, $g_sPattern, $g_sReplace)
ConsoleWrite($g_sResult & #CRLF)
Returns AA FF 10 DC.
This is sorta ugly, but it works:
$string = "AAFF10DC"
$strArray = StringSplit($string, "") ; No delimiter will separate all chars.
$strResult = ""
If IsEvenNumber($strArray[0]) Then
For $i = 1 to $strArray[0] Step 2
$strResult = $strResult & $strArray[$i] & $strArray[$i+1] & " "
Next
MsgBox(0, "Result", $strResult)
Else
MsgBox(0, "Result", "String does not contain an even number of characters.")
EndIf
Func IsEvenNumber($num)
Return Mod($num, 2) = 0
EndFunc
Global $s_string = "AAFF10DC"
MsgBox(64, "Info", _str_bytesep($s_string))
Func _str_bytesep($s_str, $s_delim = " ")
If Not (Mod(StringLen($s_str), 2) = 0) Then Return SetError(1, 0, "")
Return StringRegExpReplace($s_str, "(..(?!\z))", "$1" & $s_delim & "")
EndFunc
Is just another way to do it. For huge amounts of byte data, I would not suggest using this method.

Resources