Form not popping up upon running - vb.net

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.

Related

Read and write below a precise cell in a CSV

I'm stuck on a basic problem. What I want is to parse through a CSV in order to compare some string and write below if I find it.
Precisely, I have a programe where I can drag and drop some button, when I drop this button I want to save it's new location on the first empty cells below the corresponding column.
Here's a sample of my CSV :
So I substring the .x/.y from my CSV and compare the name from the drop button with each cell with the help of textFieldParser. It seems to work my loop stopped when it find an equal expression.
But here's the problem I don't know how to say to my program to write below it. The first reason I can figured it out is because my parser go until the endOfData and I want it to go until the endOfDat + one row.
The second one is because I don't know if I can use a fieldwriter into textFieldParser, I mean I tried to create a variable with row+1 and write below but nothing happen when I use fileWriter.
now a sample of my code :
Private Sub manageCsv(ByVal sender As Button)
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("..\..\Pic\csvPic.csv")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
Dim rowPlusOne As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
rowPlusUn = MyReader.ReadFields()
Dim currentField As String
Dim str As String = btnSender.Name.Substring(3)
Dim nameDelimited As String
Dim x As Integer
For Each currentField In currentRow
''Search the corresponding field''
x = InStr(currentField, ".")
If Not (currentField.Equals("imagefile")) Then ''imagefile is the first index of my csv''
nameDelimited = currentField.Substring(0, x) ''substr the extension''
If nameDelimited.Equals(str) Then
writeCsv("..\..\Image\csvPic.csv", nameDelimited, ",")
''Ofc the "+1" does not work but that was the idea''
currentRow(+1) = lblImgName.Text
currentRow(+1) = btnSender.Location.ToString
Exit For
End If
End If
Next
Catch ex As _
Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
End Try
End While
End Using
End Sub
I hope it's clear enough, if not i'll try to elaborate more. Thanks for your help
Show your teacher that there are better ways to do this with a simple text file. The file will only exist if buttons have been moved before in the application. See in line comments.
Private ButtonLocation As New Dictionary(Of Button, Point)
Private MouseIsDown As Boolean
Private ptX, ptY As Integer 'Starting point of mouse relative to the button
Private btn As Button 'The button being moved
Private ButtonPath As String = "C:\Users\maryo\Desktop\Code\DroppedButtons.txt"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Reposition the buttons to where they were dropped in the previous session.
If File.Exists(ButtonPath) Then
Dim lines = File.ReadAllLines(ButtonPath) 'returns an array of strings (each line)
For Each line In lines 'loop though each line in the file
Dim fields = line.Split(","c) 'The three values on the line are separated by a comma
Dim b = DirectCast(Controls(fields(0)), Button) 'Change the string Button.Name
'to an actual Button object by finding it in the controls collection
'Set the location with the next 2 values on the line
b.Location = New Point(CInt(fields(1)), CInt(fields(2)))
'Add the Button and Location to the list
ButtonLocation.Add(b, b.Location)
Next
End If
End Sub
'These three Event procedures are the normal code to Drag and Drop a control
Private Sub Button_MouseDown(sender As Object, e As MouseEventArgs) Handles Button1.MouseDown, Button2.MouseDown
btn = DirectCast(sender, Button)
ptX = e.Location.X
ptY = e.Location.Y
MouseIsDown = True
End Sub
Private Sub Button_MouseMove(sender As Object, e As MouseEventArgs) Handles Button1.MouseMove, Button2.MouseMove
If MouseIsDown Then
'e.X and e.Y are the coordinates of the Mouse relative to the control (the Button)
'not the Form or the Screen.
btn.Location = New Point(btn.Location.X + e.X - ptX, btn.Location.Y + e.Y - ptY)
End If
End Sub
Private Sub Button_MouseUp(sender As Object, e As MouseEventArgs) Handles Button1.MouseUp, Button2.MouseUp
MouseIsDown = False
'When we drop the button with the MouseUp event we record the new location in the list
RecordButtonLocation(btn, btn.Location)
btn = Nothing
End Sub
Private Sub RecordButtonLocation(Sender As Button, Location As Point)
'Check if the Button is already in the list
If ButtonLocation.ContainsKey(Sender) Then
'Record its new location
ButtonLocation.Item(Sender) = Location
Else
'If it is not in the list add it.
ButtonLocation.Add(Sender, Location)
End If
End Sub
Private Sub Form1_Closing(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles Me.Closing
SaveDictionary()
End Sub
Private Sub SaveDictionary()
If ButtonLocation.Count > 0 Then
'If there is anything in the list we will create or overwrite the file
Dim sb As New StringBuilder
For Each kv As KeyValuePair(Of Button, Point) In ButtonLocation
sb.AppendLine($"{kv.Key.Name},{kv.Value.X},{kv.Value.Y}")
Next
File.WriteAllText(ButtonPath, sb.ToString)
End If
End Sub

How to add an item to an Excel menu using VSTO?

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!

Trying to assign pictures to PictureBoxes in VB

I am trying to create a simple game, and first it needs to randomly load 16 PictureBoxes with images. I am not sure where the problem lies in this.
Public Class Form1
Private picArrows() As PictureBox = {pic11, pic12, pic13, pic14,
pic21, pic22, pic23, pic24,
pic31, pic32, pic33, pic34,
pic41, pic42, pic43, pic44}
Private Sub btnNew_Click(sender As Object, e As EventArgs) Handles btnNew.Click
'starts a new game
'declares RNG
Dim randGen As New Random
'uses RNG to determine arrow placement
For intPicBox As Integer = 0 To 15
Select Case randGen.Next(1, 5)
Case 1
picArrows(intPicBox).Image = My.Resources.Up
Case 2
picArrows(intPicBox).Image = My.Resources.Right
Case 3
picArrows(intPicBox).Image = My.Resources.Down
Case 4
picArrows(intPicBox).Image = My.Resources.Left
End Select
Next
End Sub
End Class
I get a NullReferenceException error on the line after Case X. Anyone know what I'm doing wrong?
I get a NullReferenceException error on the line after Case X
You cannot initialize your array like this:
Public Class Form1
Private picArrows() As PictureBox = {pic11, pic12, pic13, pic14,
pic21, pic22, pic23, pic24,
pic31, pic32, pic33, pic34,
pic41, pic42, pic43, pic44}
The Form has not been initialized yet, so it and all the controls on it have not been created yet. As a result, all those control references are going to be Nothing, leaving you with an array full of Nothings. The result is a NullReferenceException because Nothing does not have an Image property.
You can declare the array there, but you can only initialize it after the form's constructor runs (Sub New). Form Load is a good place:
Public Class Form1
Private picArrows As PictureBox()
' for best results you should use the same RNG over and over too:
Private randGen As New Random()
...
Private Sub Form_Load(....
picArrows = New PictureBox() {pic11, pic12, pic13, pic14,
pic21, pic22, pic23, pic24,
pic31, pic32, pic33, pic34,
pic41, pic42, pic43, pic44}
See also NullReference Exception in Visual Basic
Slightly different arrangement without the companion array:
Private Sub btnNew_Click(sender As Object, e As EventArgs) Handles btnNew.Click
With New Random
For col = 1 To 4
For row = 1 To 4
CType(Controls(String.Format("pic{0}{1}", col, row)), PictureBox).Image = {My.Resources.Up, My.Resources.Right, My.Resources.Down, My.Resources.Left}(.Next(0, 4))
Next
Next
End With
End Sub

Check if form is Opened

I give this question for more knowledge. How can I know if the form is Opened in my application or not, in order not to open it again I mean not to create an instance of the same form while it's running
Dim frmCollection As New FormCollection()
frmCollection = Application.OpenForms()
If frmCollection.Item("Form2").IsHandleCreated Then
MsgBox("Yes Opened")
Else
Dim f As New Form2()
With f
.Text = "form2"
.Show()
End With
End If
if I executes this code many times it will create more instances of the form Form2
How can I check if this form is not already opened
You can try it like this:
Imports System.Linq ' need to add
If Application.OpenForms().OfType(Of Form2).Any Then
MessageBox.Show("Opened")
Else
Dim f2 As New Form2
f2.Text = "form2"
f2.Show()
End If
You can use the following code:
If myForm.IsHandleCreated then
myForm is open
End If
As an extension of the answers given (thank you, all), here's a simple way to activate or show:
Dim frmCollection = System.Windows.Forms.Application.OpenForms
If frmCollection.OfType(Of Form2).Any Then
frmCollection.Item("Form2").Activate()
Else
Dim newForm2 = New Form2
newForm2.Show()
End If
For more simplicity you may create a public static bool variable which will tell whether the form is opened or not. On form load event assign 'true' and on closed event assign 'false' value.
ANOTHER refactoring way from the one initiated by HumbleBeginnings:
Dim xChildWindows = Application.OpenForms.OfType(Of frmForm2)
If xChildWindows.Any Then
xChildWindows.First().Focus() 'Focus if exists
Else
Dim xfrmNew As New frmForm2() 'Open window if doeasn't exists
xfrmNew.MdiParent = Me
xfrmNew.Show()
End If
Hate to be a kill joy but some day some one is going to try and understand your code.
Dim frm as New frmDontknow
Dim frmCollection = System.Windows.Forms.Application.OpenForms
For i As Int16 = 0I To frmCollection.Count - 1I
If frmCollection.Item(i).Name = frm.Name Then
frmCollection.Item(i).Activate()
Exit Sub
End If
Next i
Then do the show etc as required?
Check if form is Opened, To validate if a form is open we use this method and function to be able to invoke from any form and use less code.
Example :
This will use it in a form with mdiContainer and a panel object with 3 buttons that shows the 3 windows form.
Imports System
Imports System.Reflection
Private Sub OpenWindowsForm(ByVal FormName As String)
Dim instForm As Form = Application.OpenForms.OfType(Of Form)().Where(Function(frm) frm.Name = FormName).SingleOrDefault()
If instForm Is Nothing Then
Dim frm As New Form
frm = DirectCast(CreateObjectInstance(FormName), Form)
frm.MdiParent = Me
Me.Panel1.Controls.Add(frm)
Me.Panel1.Tag = frm
frm.Show()
Else
instForm.Select()
instForm.WindowState = FormWindowState.Maximized
instForm.BringToFront()
End If
End Sub
Public Function CreateObjectInstance(ByVal objectName As String) As Object
Dim obj As Object
Try
If objectName.LastIndexOf(".") = -1 Then
objectName = [Assembly].GetEntryAssembly.GetName.Name & "." & objectName
End If
obj = [Assembly].GetEntryAssembly.CreateInstance(objectName)
Catch ex As Exception
obj = Nothing
End Try
Return obj
End Function
How to use in click events
Private Sub btnRegistro_Click(sender As Object, e As EventArgs) Handles btnRegistro.Click
OpenWindowsForm("Registro")
End Sub
Private Sub btnBusqueda_Click(sender As Object, e As EventArgs) Handles btnBusqueda.Click
OpenWindowsForm("Busqueda")
End Sub
Private Sub btnCalendario_Click_1(sender As Object, e As EventArgs) Handles btnCalendario.Click
OpenWindowsForm("Calendario")
End Sub
Here is an image of the Sample code
you can try this
Dim formText As String
Dim prevText As String
Private Sub OpenForm(ByVal frm As Windows.Forms.Form)
formText = frm.Text
If formText = prevText Then Exit Sub
CloseForms()
' Make it a child of this MDI form before showing it.
frm.MdiParent = Me
frm.Show()
frm.Location = New Point(0, 0)
prevText = formText
End Sub
Private Sub CloseForms()
For Each ChildForm As Form In Me.MdiChildren
ChildForm.Close()
Next
End Sub
Private Sub NewToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PayablesToolStripMenuItem.Click
OpenForm(frmPayables)
End Sub
For Each frm As Form In Application.OpenForms
If frm.Name = Form1.Name Then
MessageBox.Show("Opened")
End If
Next

OLE: Inaccessible due to its protection level.

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.