I am trying to plot a chart in excel sheet using VB.
So now I am following the instructions given here
1- I started a new VB project in VS2010, called Excelgraph.
2- By default I got Form1.vb[Design].
3- On this Form I created a button by dragging it from the toolbox.
4-I doubled clicked it and new Form1.vb opens.
5- I removed everything that was automatically generated in this file i,e Form1.vb file and pasted the following code:
Updated Code
This is another code and is a latest one, compatible with Visual Basic 6.0.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim oXL As Object ' Excel application
Dim oBook As Object ' Excel workbook
Dim oSheet As Object ' Excel Worksheet
Dim oChart As Object ' Excel Chart
Dim iRow As Integer ' Index variable for the current Row
Dim iCol As Integer ' Index variable for the current Row
Const cNumCols = 10 ' Number of points in each Series
Const cNumRows = 2 ' Number of Series
ReDim aTemp(0 To cNumRows, 0 To cNumCols)
'Start Excel and create a new workbook
oXL = CreateObject("Excel.application")
oBook = oXL.Workbooks.Add
oSheet = oBook.Worksheets.Item(1)
' Insert Random data into Cells for the two Series:
Randomize(Now().ToOADate())
For iRow = 1 To cNumRows
For iCol = 1 To cNumCols
aTemp(iRow, iCol) = Int(Rnd() * 50) + 1
Next iCol
Next iRow
oSheet.Range("A1").Resize(cNumRows, cNumCols).Value = aTemp
'Add a chart object to the first worksheet
oChart = oSheet.ChartObjects.Add(50, 40, 300, 200).Chart
oChart.SetSourceData(Source:=oSheet.Range("A1").Resize(cNumRows, cNumCols))
' Make Excel Visible:
oXL.Visible = True
oXL.UserControl = True
End Sub
End Class
Update
I updated the code as shown above.
Error
'aTemp' is not declared. It may be inaccessible due to its protection level.
c:\users\ybf4 \documents\visual studio 2010\Projects\Excelgraph2
\Excelgraph2\Form1.vb
There were two more errors which I managed to remove. How do I remove this error?
I am compiling the above code on visual studio 2010 and Office is Office 2007.
A simple, trivial program reveals the error to be as I suspected - you can't change the size of something that doesn't exist!
As Derek said, you need to change the ReDim to Dim - OR you need to declare it first.
FAILS:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Const cNumCols = 10 ' Number of points in each Series
Const cNumRows = 2 ' Number of Series
ReDim aTemp(0 To cNumRows, 0 To cNumCols)
End Sub
PASSES:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Const cNumCols = 10 ' Number of points in each Series
Const cNumRows = 2 ' Number of Series
Dim aTemp
ReDim aTemp(0 To cNumRows, 0 To cNumCols)
End Sub
PASSES:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Const cNumCols = 10 ' Number of points in each Series
Const cNumRows = 2 ' Number of Series
Dim aTemp(0 To cNumRows, 0 To cNumCols)
End Sub
Hovering over aTemp should have told you this - it should also be underlined by a blue squiggly line to indicate a problem.
It's been a long time since I did this, but just looking at the code I suspect you need to change:
ReDim aTemp(0 To cNumRows, 0 To cNumCols)
To:
Dim aTemp(0 To cNumRows, 0 To cNumCols)
ReDim is used to re-dimension an array after it has been dimensioned (using the Dim statement)
That's remarkably old code (it's for VB3, so 4 generations before the first VB.Net, and Excel 5)
However, I believe your code should run fine if you just comment out the two lines indicated.
The randomness of the entries added to the worksheet may be different, but since you'll be replacing that code anyway (where Rnd() is used), it shouldn't matter. (I'm assuming your purpose isn't to generate random graphs)
As to DoEvents, I'm not sure that was ever necessary.
Related
Can anyone help with this school task I have
The task is to ask the user for items and the cost of the items until they chose to stop. Then combine all the costs and take 20% VAT and 10% off from 2 randomly selected items.
Here is the code I have so far (I have 2 buttons and a listbox)
Public Class Form1
Dim CurrentA As Integer
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim Items(CurrentA) As String
Dim Coins(CurrentA) As Single
Dim Stay As String
CurrentA = 0
Do Until CurrentA = 20
Items(CurrentA) = InputBox("Please Enter The Item")
Coins(CurrentA) = InputBox("Please Enter The Cost Of The Item")
Stay = InputBox("Type Yes If More Items or Type No if no More")
Stay = Stay.ToLower
If Stay = "yes" Then
End If
If Stay = "no" Then
Exit Do
End If
ListBox1.Items.Add(Items(CurrentA) & " " & Coins(CurrentA))
CurrentA += 1
Loop
End Sub
End Class
First, a few comments on the code you presented.
Dim CurrentA As Integer
'An Integers default value is zero, I don't see why this is a class level variable
'always declare variables with as narrow a scope as possible
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim Items(CurrentA) As String 'Declares an Array of Type String with an Upper Bound of 0
'Upper Bound is the highest index in the array
'Arrays start with index 0
'So your array will have 1 element at index 0
Dim Coins(CurrentA) As Single
Dim Stay As String
CurrentA = 0 'unnecessary because the default of CurrentA is already 0, but OK for clarity because it could have been changed elsewhere
'This is behaving like a console application with the code repeating in a loop.
'In Windows Forms it would be more likely to do this in a button click event (btnAddItem)
Do Until CurrentA = 20
'On the first iteration CurrentA = 0
'On the second iteration CurrentA = 1 - this exceeds the size of your array
'and will cause an index out of range error
Items(CurrentA) = InputBox("Please Enter The Item")
'With Option Strict on you must change the input to a Single
Coins(CurrentA) = CSng(InputBox("Please Enter The Cost Of The Item"))
Stay = InputBox("Type Yes If More Items or Type No if no More")
Stay = Stay.ToLower 'Good! The user might no follow directions exactly
If Stay = "yes" Then
'This is kind of silly because it does nothing
End If
'Lets say I say no on the first iteration
'This avoids the index out of range error but
'nothing is added to the list because you Exit the loop
'before adding the item to the ListBox
If Stay = "no" Then
Exit Do
End If
ListBox2.Items.Add(Items(CurrentA) & " " & Coins(CurrentA))
CurrentA += 1
Loop
End Sub
We could use arrays but not knowing how many items will be added means either making the array bigger than needed or using Redim Preserve on every addition. A much better choice is a List(Of T). They work a bit like arrays but we can just add items without the ReDim stuff.
Private lstCost As New List(Of Single)
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
'Pretend this button is called btnAdd, and you have 2 test boxes
lstCost.Add(CSng(TextBox2.Text))
'The $ introduces an interpolated string. It is a step up form String.Format
ListBox2.Items.Add($"{TextBox1.Text} - {CSng(TextBox2.Text):C}") 'The C stands for currency
TextBox1.Clear()
TextBox2.Clear()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Pretend this button is called btnTotal
'Dim total As Single = (From cost In lstCost
' Select cost).Sum
Dim total As Single = lstCost.Sum
Label1.Text = total.ToString("C") 'C for Currency
End Sub
Im trying to get a random number to generate and take said random number to display a certain line of text assigned to that number to a label through a Sub Procedure.
If this is any easier:
Generate Random Number 1 Through 5
Call Random Number using Sub Procedure
Display a string to a label that is connected to that random number.
I'll show my code just so you guys know what my direction is and if it's correct.
Public Class Form1
Private Sub btnInsult_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsult.Click
Dim strInsult As String
Dim intNumber As Integer
Randomize()
intNumber = Int((5 - 1 + 1) * Rnd() + 1)
End Sub
Sub showInsult()
End Sub
End Class
It really isn't much and I think I'm moving in the right direction. Please ask me if you need more clarification on things.
I had a similar piece of code for generating random messages.
Unlike your code above, this was written inside a form module, not a class one and prints to a text box, not a label. I am not sure whether by
Display a string to a label
you actually mean changing an actual label caption. If so, then use the showInsultEx sub instead. Here it is, adapted to your needs. I hope this helps.
Private arrInsults() As Variant
Private nInsultCount As Integer
Private Sub Insult_InitRepertoire()
'init the insult array
arrInsults = Array( _
"Insult 1", _
"Insult 2", _
"Insult 3", _
"Insult 4", _
"Insult 5")
nInsultCount = UBound(arrInsults) - LBound(arrInsults) + 1
End Sub
Private Sub showInsult()
'init the insult array if empty
If nInsultCount = 0 Then Insult_InitRepertoire
'get a random entry from the insult table
'and print it in the text field
Randomize
Me.TextBox1.Text = arrInsults(LBound(arrInsults) + Int(Rnd() * nInsultCount))
End Sub
Private Sub btnInsult_Click()
'invoke the pseudo-random inslut generator
showInsult
End Sub
Private Sub UserForm_Initialize()
'prevent user input
Me.TextBox1.Locked = True
End Sub
Private Sub showInsultEx()
Dim nId As Integer
'init the insult array if empty
If nInsultCount = 0 Then Insult_InitRepertoire
'get a random entry from the insult table
'and print it in the text field
Randomize
nId = LBound(arrInsults) + Int(Rnd() * nInsultCount)
'get a control associated with the insult number
'change its caption to the generated text
'you'll have to make sure to number the controls
'according to the array indices
Me.Controls("Label" & nId).Caption = arrInsults(nId)
End Sub
I'm developing an Excel Add-in using VB.NET. On this Add-in, I create a new Ribbon, and inside this Ribbon there will be a Menu of Excel Workbooks and each line of the Menu should have a submenu for the Workbooks' Worksheets (Those file names, paths and sheets are being retrieved from DB).
I'm having problems trying to insert those Workbooks as Menu Items. I created a DAL to retrieve all data that I need and tested , it works, my problem is to add each element of the Workbook list. Any suggestions are welcome.
Public Class Ribbon1
Private Sub Ribbon1_Load(ByVal sender As System.Object, ByVal e As RibbonUIEventArgs) Handles MyBase.Load
Dim listaWorkbooks As New List(Of Workbook)
Dim serviceExecuta As New ServiceExecuta
listaWorkbooks = serviceExecuta.BuscaWorkbooks()
For Each Workbook In listaWorkbooks
Menu1.Items.Add(Workbook.getNome)
Next
End Sub
End Class
I use a button to load the worksheets in to Combo boxes in the Ribbon...
Same way, you can check for workbooks as well.
please refer to below:
Private Sub Button1_Click(sender As Object, e As RibbonControlEventArgs) Handles Button19.Click
ComboBox1.Items.Clear()
Dim rdi As RibbonDropDownItem
Dim i As Integer
Dim nm() As String
For i = 1 To Globals.ThisAddIn.Application.Sheets.Count
ReDim nm(i)
nm(i) = Globals.ThisAddIn.Application.Sheets(i).Name
rdi = Globals.Factory.GetRibbonFactory().CreateRibbonDropDownItem()
rdi.Label = nm(i)
ComboBox1.Items.Add(rdi)
Next i
End Sub
May be you can try something like this :
For i = 1 To Globals.ThisAddIn.Application.Workbooks.Count
ReDim nm(i)
nm(i) = Globals.ThisAddIn.Application.Workbooks(i).Name
rdi = Globals.Factory.GetRibbonFactory().CreateRibbonDropDownItem()
rdi.Label = nm(i)
ComboBox1.Items.Add(rdi)
Next i
Good Luck!
I have 2 text files named sQue.txt containing single words in each lines (each word in each line) and sObj.txt also containing single word in each line (but no. of entries are more in this file than in sQue.txt).
Now, I have a blank form in which I want to read both the above files & display them in a manner such that:
Each entry from sQue.txt file gets displayed in separate labels in the form
All the entries of file sObj.txt are put in a CheckedListBox & this CheckedListBox appears for each label displayed in point 1. above.
Example:
sObj.txt contains 3 entries aaa, bbb & ccc (vertically i.e each in new line).
sQue.txt contains 5 entries p,q,r,s & t (vertically i.e each in new line).
Now, when the form loads, 3 labels are seen with texts aaa, bbb & ccc. Also 3 CheckedListBoxes are seen containg p,q,r,s & t in each box.
Can it be done? I'm trying to find a solution with no luck yet.
Please help.
Till now all I have is
Private Sub Form7_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim queue As String() = IO.File.ReadAllLines("C:\temp\sQue.txt")
Dim objects As String() = IO.File.ReadAllLines("C:\temp\sObj.txt")
For i = 0 To queue.Count - 1
'create labels here
For j=0 to objects.Count - 1
'create CheckedListBoxes
Next
Next
End Sub
If you use a groupbox you can use the text property as your label, and add a checkedlistbox to the groupbox with the items you want. This code will do that:
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim NewForm2 As New Form2
NewForm2.Show()
Dim sObj() As String = File.ReadAllLines("sobj.txt")
Dim sQue() As String = File.ReadAllLines("sQue.txt")
For Each s As String In sObj
Me.Controls.Add(MakeNewGB(s, sQue))
Next
End Sub
End Class
Public Module Module1
Friend WithEvents NewGB As System.Windows.Forms.GroupBox
Friend WithEvents NewCLB As System.Windows.Forms.CheckedListBox
Public NextColumn As Integer = 0
Public Function MakeNewGB(lbl As String, clbItems() As String) As GroupBox
NewGB = New System.Windows.Forms.GroupBox()
NewCLB = New System.Windows.Forms.CheckedListBox()
NewGB.SuspendLayout()
'GroupBox1
'
NewGB.Controls.Add(NewCLB)
NewGB.Location = New System.Drawing.Point(NextColumn, 0)
NewGB.Name = lbl
NewGB.Size = New System.Drawing.Size(126, 210)
NewGB.TabIndex = 0
NewGB.TabStop = False
NewGB.Text = lbl
'
'CheckedListBox1
'
NewCLB.FormattingEnabled = True
NewCLB.Location = New System.Drawing.Point(6, 19)
NewCLB.Name = "clb" + lbl
NewCLB.Size = New System.Drawing.Size(103, 184)
NewCLB.TabIndex = 0
NewCLB.Items.AddRange(clbItems)
NextColumn += NewGB.Size.Width + 10
Return NewGB
End Function
End Module
I think your code should look like this. But i am not sure what the purpose of it is.
Private Sub Form7_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim queue As String() = IO.File.ReadAllLines("C:\temp\sQue.txt")
Dim objects As String() = IO.File.ReadAllLines("C:\temp\sObj.txt")
For i = 0 To queue.Count - 1
'create labels here
Dim label as new Label
label.Text = queue(i)
Dim chklst as new CheckedListBox
For j=0 to objects.Count - 1
'create CheckedListBoxes
chklst.Items.Add(object(j))
Next
Me.Controls.Add(label)
Me.Controls.Add(chklst)
Next
End Sub
Here I have my vb6 code that plays around with an excel file. (I took this code off some other website.) This code compiles and builds but when I hit f5 it does the form does not po up. If I remove all the code in the Class then it pops up.
How would I fix this?
Sorry I am new at vb6, but not coding in general.
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Dim xl As New Excel.Application
Dim xlsheet As Excel.Worksheet
Dim xlwbook As Excel.Workbook
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'the benifit of placing numbers in (row, col) is that you
'can loop through different directions if required. I could
'have used column names like "A1" 'etc.
'Text1.Text = xlsheet.Cells(2, 1) ' row 2 col 1
'Text2.Text = xlsheet.Cells(2, 2) ' row 2 col 2
'don't forget to do this or you'll not be able to open
'book1.xls again, untill you restart you pc.
xl.ActiveWorkbook.Close(False, "f:\a.xls")
xl.Quit()
End Sub
Private Sub Form_Load()
xlwbook = xl.Workbooks.Open("f:\a.xls")
xlsheet = xlwbook.Sheets.Item(1)
End Sub
Private Sub Form_Unload(Cancel As Integer)
xlwbook = Nothing
xl = Nothing
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
xlsheet.Cells(2, 1) = "adsfasdfasdf"
xlsheet.Cells(2, 2) = "qwerqwer"
xlwbook.Save()
'don't forget to do this or you'll not be able to open
'book1.xls again, untill you restart you pc.
xl.ActiveWorkbook.Close(False, "f:\a.xls")
xl.Quit()
End Sub
End Class
Then it means that you are not adding reference to your project
follow the link to code and further details..
http://vb.net-informations.com/excel-2007/vb.net_excel_2007_open_file.htm
check file name, path and extension carefully.
("f:\a.xls")
extension may be xlsx.
Also check the name of sheet 1.