Hello i have problem with sub
Sub lab1_5()
Dim displayText As String
Do
number = InputBox("Write number: ")
For i = 1 To 9
number = number * 2
displayText = displayText & " " & number
Next i
MsgBox displayText
Dim answer As VbMsgBoxResult
answer = MsgBox("KONIEC" & vbNewLine & "Chcesz spróbować jeszcze raz?", vbYesNo)
Loop While (answer = vbYes)
End Sub
If i write for example 2 it shows 2 4 8 16 etc and than after clicking yes and writing another number i have previous(2 4 8 etc) and new numbers. How can i repair it so i have only new numbers?
You need to reset displayText to an empty string at the start of the do loop.
Sub lab1_5()
Dim displayText As String
Do
Number = InputBox("Write number: ")
displayText = "" '<--- this line here
For i = 1 To 9
Number = Number * 2
displayText = displayText & " " & Number
Next i
MsgBox displayText
Dim answer As VbMsgBoxResult
answer = MsgBox("KONIEC" & vbNewLine & "Chcesz spróbowac jeszcze raz?", vbYesNo)
Loop While (answer = vbYes)
End Sub
Related
I am creating a program in vb6 with ms access. while i am searching the database from multi select list box in vb it displays the results wrongly.
if i click the first item it shows one time
if i click second item it shows that item two times
it i click third item it shows that item three times.
how to solve this
i tried the below code
For i = List1.ListCount - 1 To 0 Step -1
If List1.Selected(i) = True Then
If str <> "" Then str = str & ""
If Val(List1.SelCount) = 1 Then
str = List1.List(List1.ListIndex)
Else
str = str & " or name= " & List1.List(List1.ListIndex)
End If
End If
Next i
If str <> "" Then
Set rs = db.OpenRecordset("select * from Customers where name= '" & str & "'")
display
End If
result
Kumar vasanth vasanth kannan kannan kannan
Try this:
Option Explicit
Private Sub Command1_Click()
Dim i As Integer
Dim str As String
For i = List1.ListCount - 1 To 0 Step -1
If List1.Selected(i) Then str = str & " or name = '" & List1.List(i) & "'"
Next i
str = Mid(str, 4)
If str <> "" Then
Set rs = db.OpenRecordset("select * from Customers where " & str)
display
End If
End Sub
I creted a loop checking number of characters length with conditions but sadly it's not properly working,
with approriate no. of loops but not reading the next line, I want to post the result in a MsgBox,
but when I use the msgbox inside the loop I will get a msgbox for every result found or only one msgbox with one result.
What I would like is to display every result in 1 msgbox with a line vbNewLine after each result.
Below is my code:
Public Sub Rs()
Dim Text As String
Dim NumChar As String
Dim i As Integer
Dim NumRows As Long
Application.ScreenUpdating = False
'Get Cell Value
Text = Range("B2").Value
'Get Char Length
NumChar = Len(Text)
NumRows = Range("B2", Range("B2").End(xlDown)).Rows.Count
Range("B2").Select
For i = 1 To NumRows
'Character length validation
If Len(Text) <= 15 Then
MsgBox Chr(149) & " SVC_DESC " & Text & " has " & NumChar & " characters " & " and it's Valid !" & vbNewLine
Else
MsgBox Chr(149) & " SVC_DESC " & Text & " has " & NumChar & " characters " & " and Exceeded allowable number of characters!" & vbNewLine
End If
Next i
Application.ScreenUpdating = True
End Sub
Assign the new text to a string variable and display the string variable outside the loop:
Option Explicit
Sub TestMe()
Dim i As Long
Dim displayText As String
For i = 1 To 3
displayText = displayText & vbCrLf & i
Next i
MsgBox displayText
End Sub
Build a string through concatenation and display the strings after exiting the loop.
Public Sub Rs()
Dim Text As String
Dim NumChar As String
Dim i As Integer
Dim NumRows As Long
dim msg1 as string, msg2 as string
Application.ScreenUpdating = False
'Get Cell Value
Text = Range("B2").Value
'Get Char Length
NumChar = Len(Text)
NumRows = Range("B2", Range("B2").End(xlDown)).Rows.Count
Range("B2").Select
For i = 1 To NumRows
'Character length validation
If Len(Text) <= 15 Then
msg1 = msg1 & Chr(149) & " SVC_DESC " & Text & " has " & NumChar & " characters " & " and it's Valid !" & vbLF
Else
msg2 = msg2 & Chr(149) & " SVC_DESC " & Text & " has " & NumChar & " characters " & " and Exceeded allowable number of characters!" & vbLF
End If
Next i
Application.ScreenUpdating = True
if cbool(len(msg1)) then
msg1 = left(msg1, len(msg1)-1)
MsgBox msg1
end if
if cbool(len(msg2)) then
msg2 = left(msg2, len(msg2)-1)
MsgBox msg2
end if
End Sub
A MsgBox uses Chr(10) aka vbLF for new lines; vbNewLine is overkill.
I wanted to insert some texts(new line) in between existing texts in a textbox (multiline = true).
Example: (Textbox1.text's value is written below)
Name: Name of Client
DOB: 11/11/11
>>>THIS IS WHERE I WHAT TO INSERT THE VALUE OF TEXTBOX2.TEXT
Hospitalization: No
Serial Number: 12345678
Private Sub cmdTransfer_Click()
Dim SearchNote As Integer, SearchThis As String, tx2 As String
If cb9.Value = True Then
tx2 = "ADDRESS: " & vbTab & text2.Text & vbCrLf
End If
SearchThis = "Hospitalization"
SearchNote = InStr(Textbox1.Text, SearchThis)
If SearchNote Then
With textbox1
.SetFocus
.SelStart = SearchNote
.Text = .Text & .SelStart & tx2
End with
End If
End Sub
What I'm doing in my code is I'm getting the number of characters before the "Hospitalization" so that I can insert the value of Textbox2 before it. I dont know how to do that tho. Please help.
Thanks!
I believe the code you are looking for is this:
Left(SearchNote, InStr(1, SearchNote, "Hospitalization") - 1) & "new text to insert" & Mid(SearchNote, InStr(1, SearchNote, "Hospitalization"))
Left will take the first few letters up to the starting point of "Hospitalization". Then you insert the new string (possible with a new line before and after with & chr(10) &). Then you add with Mid everything after "Hospitalization".
Since I don't have a sample copy of your spreadsheet, there is a chance that one/some of my variables might be different. If you find problems with any of these, check all of the vars.
Solution #1: Create module and add this function:
Function addText(txtBox As String, addString As String)
Dim endIndex As Long
Dim SearchThis As String
Dim input1, input2, input3 As String
SearchThis = "Hospitalization"
' Get index of Hospitalization
endIndex = InStr(1, txtBox, SearchThis) - 1
If endIndex > 0 Then
input1 = Mid(txtBox, 1, endIndex)
input2 = addString & vbNewLine
input3 = Mid(txtBox, endIndex, Len(txtBox))
' Return with added text
addText = CStr(input1 & input2 & input3)
End If
End Function
then call in your button to update your text box:
Private Sub cmdTransfer_Click()
Dim tx2 As String
If cb9.Value = True Then
tx2 = "ADDRESS: " & vbTab & text2.Text & vbNewLine
Else
' Stop if there is nothing to add
End
End If
If textbox1.Value <> vbNullString Then
textbox1.Value = addText(textbox1.Value, tx2)
End If
End Sub
Solution #2: Call everything from within your button:
Private Sub cmdTransfer_Click()
Dim endIndex As Long
Dim SearchThis As String
Dim input1, input2, input3 As String
Dim txtBox As String, tx2 As String
'set tx2
If cb9.Value = True Then
tx2 = "ADDRESS: " & vbTab & text2.Text & vbNewLine
Else
' Stop if nothing to add
End
End If
If textbox1.Value <> vbNullString Then
' set txtBox variable
txtBox = textbox1.Value
Else
' Avoid Error if text box is null
End
End If
SearchThis = "Hospitalization"
' Get index of Hospitalization
endIndex = InStr(1, txtBox, SearchThis) - 1
If endIndex > 0 Then
input1 = Mid(txtBox, 1, endIndex)
input2 = tx2 & vbNewLine
input3 = Mid(txtBox, endIndex, Len(txtBox))
textbox1.Value = input1 & input2 & input3
End If
End Sub
What i would do is split text1 into an array then just add the text in the middle, mainString is text1, midStr is text2:
Dim mainStr as String, midStr as String, ArreStr() as String
mainStr=text1.text:midStr=text2.text
ArreStr=Split(mainStr,VBNewLine)
text1.text=ArreStr(0) & vbnewline & midStr & vbnewline & ArreStr(1)
I want to display a textlog string in a userform's textbox.
Code might look like this:
Dim public textlog as string
sub button1_click()
' do some action
textlog = textlog & event_string & vbCrLf
'event_string might exceed more than 2 line
textlog = textlog & "button1 action" & vbCrLf
userform1.textbox1.text = textlog
end sub
sub button2_click()
' do some action
textlog = textlog & event_string & vbCrLf
'event_string might exceed more than 2 line
textlog = textlog & "button2 action" & vbCrLf
userform1.textbox1.text = textlog
end sub
However, the textbox should only contain 20 lines of information, while my
the contents of my textlog will exceed 20 lines.
How can I display only the latest (last) 20 lines of the textlog in textbox1?
You can use this function to return only the last N lines of a string, and then display that in your textbox.
Note that you have to specify what the line break character is. Depending on your specific application, it could be vbCrLf, vbCr, vbLf, or even some other delimiter.
Function GetLastLines(ByVal s As String, ByVal nLinesToDisplay As Long, _
Optional ByVal lineBreakChar As String = vbCrLf)
'Split the string into an array
Dim splitString() As String
splitString = Split(s, lineBreakChar)
'How many lines are there?
Dim nLines As Long
nLines = UBound(splitString) + 1
If nLines <= nLinesToDisplay Then
'No need to remove anything. Get out.
GetLastLines = s
Exit Function
End If
'Collect last N lines in a new array
Dim lastLines() As String
ReDim lastLines(0 To nLinesToDisplay - 1)
Dim i As Long
For i = 0 To UBound(lastLines)
lastLines(i) = splitString(i + nLines - nLinesToDisplay)
Next i
'Join the lines array into a single string
GetLastLines = Join(lastLines, lineBreakChar)
End Function
Example usage:
MsgBox GetLastLines( _
"line 1" & vbCrLf & "line 2" & vbCrLf & "line 3" & vbCrLf _
& "line 4" & vbCrLf & "line 5" & vbCrLf & "line 6", _
4, vbCrLf)
Only the last 4 lines are displayed:
Note that this assumes that your last line is not terminated by a line break. If it is, then you can tweak the code to deal with that.
Alternatively, you can use Excel's built-in SUBSTITUTE function, which is useful in this particular case, because it can locate a specific instance of a given character. So instead of building arrays you can use a one-liner:
Function GetLastLines2(ByVal s As String, ByVal nLinesToDisplay As Long, _
Optional ByVal lineBreakChar As String = vbCrLf)
'An arbitrary character that will never be in your input string:
Dim delim As String: delim = Chr(1)
'How many lines are there?
Dim nLines As Long
nLines = UBound(Split(s, lineBreakChar)) + 1
If nLines <= nLinesToDisplay Then
'No need to remove anything. Get out.
GetLastLines2 = s
Exit Function
End If
'Replace one line break with delim, split the string on it,
'return only second part:
GetLastLines2 = Split( _
WorksheetFunction.Substitute( _
s, lineBreakChar, delim, nLines - nLinesToDisplay), _
delim)(1)
End Function
A = "Cat" & vbcrlf & "Tiger" & vbcrlf & "Lion" & vbcrlf & "Shark hunting florida lynxs" & vbcrlf & "Leopard" & vbcrlf & "Cheetah"
A= StrReverse(A)
NumLines = 3
i=1
For X = 1 to NumLines
i = Instr(i, A, vbcr) + 1
Next
Msgbox StrReverse(Left(A, i - 1))
This is a program that cuts or leaves lines from top or bottom of files.
To use
Cut
filter cut {t|b} {i|x} NumOfLines
Cuts the number of lines from the top or bottom of file.
t - top of the file
b - bottom of the file
i - include n lines
x - exclude n lines
Example
cscript //nologo filter.vbs cut t i 5 < "%systemroot%\win.ini"
The script
Set rs = CreateObject("ADODB.Recordset")
With rs
.Fields.Append "LineNumber", 4
.Fields.Append "Txt", 201, 5000
.Open
LineCount = 0
Do Until Inp.AtEndOfStream
LineCount = LineCount + 1
.AddNew
.Fields("LineNumber").value = LineCount
.Fields("Txt").value = Inp.readline
.UpDate
Loop
.Sort = "LineNumber ASC"
If LCase(Arg(1)) = "t" then
If LCase(Arg(2)) = "i" then
.filter = "LineNumber < " & LCase(Arg(3)) + 1
ElseIf LCase(Arg(2)) = "x" then
.filter = "LineNumber > " & LCase(Arg(3))
End If
ElseIf LCase(Arg(1)) = "b" then
If LCase(Arg(2)) = "i" then
.filter = "LineNumber > " & LineCount - LCase(Arg(3))
ElseIf LCase(Arg(2)) = "x" then
.filter = "LineNumber < " & LineCount - LCase(Arg(3)) + 1
End If
End If
Do While not .EOF
Outp.writeline .Fields("Txt").Value
.MoveNext
Loop
End With
I am looking to get the table that is generated at the end of the program below have the option to be saved into a .txt so that it can be looked back to at a later date but am struggling to get this to happen.
Module Module1
Dim kTick As Integer
Dim kName(64) As String
Dim kHours(64) As Integer
Dim kHoursPay(64) As Integer
Dim kGross(64) As Integer
Dim kTax As Integer = 20
Dim kNet(64) As Integer
Dim kTotal As Integer
Dim kAverage As Integer
Sub Main()
'Assigning kTick (Number of employee's)
Assign()
'Imputting the data
Entry()
'Calculating kGross, kTax, kNet and kTotal
Print()
End Sub
Sub Assign()
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("Please enter the total amount of employee's:")
Console.ForegroundColor = ConsoleColor.White
kTick = Console.ReadLine()
Console.Clear()
End Sub
Sub Entry()
For kCounter = 1 To kTick
Console.ForegroundColor = ConsoleColor.DarkGray
Console.WriteLine("Employee " & kCounter)
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("Please enter the employee name below:")
Console.ForegroundColor = ConsoleColor.White
kName(kCounter) = Console.ReadLine()
Do
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("Please enter the employees total hours worked below:")
Console.ForegroundColor = ConsoleColor.White
kHours(kCounter) = Console.ReadLine()
Loop Until kHours(kCounter) >= 0 And kHours(kCounter) <= 60
Do
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("Please enter the employees Hourly Pay below:")
Console.ForegroundColor = ConsoleColor.White
kHoursPay(kCounter) = Console.ReadLine()
Loop Until kHoursPay(kCounter) >= 6 And kHoursPay(kCounter) <= 250
Console.Clear()
Next
End Sub
Sub Print()
For kCounter = 1 To kTick
kGross(kCounter) = kHours(kCounter) * kHoursPay(kCounter)
Next
For kCounter = 1 To kTick
kNet(kCounter) = (kGross(kCounter) / 10) * 8
Next
For kCounter = 1 To kTick
kTotal = kTotal + kHours(kCounter)
Next
kAverage = kTotal / kTick
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("Name" & vbTab & "Hours" & vbTab & "Hourly Rate" & vbTab & "Gross Pay" & vbTab & "Tax" & vbTab & "Net Pay")
Console.ForegroundColor = ConsoleColor.White
For kCounter = 1 To kTick
Console.WriteLine(kName(kCounter) & vbTab & kHours(kCounter) & vbTab & "£" & kHoursPay(kCounter) & vbTab & vbTab & "£" & kGross(kCounter) & vbTab & vbTab & kTax & "%" & vbTab & "£" & kNet(kCounter))
Next
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("Total hours worked: " & kTotal)
Console.WriteLine("Total average hours worked: " & kAverage)
Console.WriteLine("Total number of employees: " & kTick)
Console.ReadLine()
Save()
End Sub
Sub Save()
End Sub
End Module
I am trying to get the code in the Save subroutine any help will be appreciated!
Thanks Kai
One note: you should not Save from Print since both are unrelated by nature. So you may want to print without saving or save without printing to the console.
A simple approach is using the File class, for example by using File.WriteAllText(path) or File.WriteAllLines(path). Therefore you need to store the text you want to output(to the console and the file) somewhere. For example in a List(Of String) variable.
You are looking for StreamWriter class. It has Write and WriteLine methods that can help you. It works in a same way as Console.WriteLine you are using.