Strange errors when making queries to excel - vb.net

Im making an application in vb.net to connect to an Excel file and edit it.
At the moment attempting to modify the Excel file ,the following errors appear:
With this function
Protected Friend Function obtenerHojaActual(ByVal columna As String, ByVal con As String) As String
Dim cmd As String
Dim WorkSheet As String = ""
Try
libro = app.Workbooks.Open(con)
For Each hoja As Microsoft.Office.Interop.Excel.Worksheet In libro.Worksheets
cmd = "SELECT [" & columna & "] FROM [" & hoja.Name & "$]"
Dim adapter As New OleDbDataAdapter(cmd, conexion)
Dim tabla As New DataTable
adapter.Fill(tabla)
adapter.Dispose()
//Code
//Code
//Code
tabla.Dispose()
Next
libro.Close()
app.Quit()
Return WorkSheet
Catch ex As Exception
repairmanMessage("Error inesperado", ex.Message, My.Resources._error).ShowDialog()
principal.lbldireccion.ForeColor = Color.Red
Return WorkSheet
End Try
End Function
Got this:
"No specified values ​​for some of the parameters required"
And with this:
Protected Friend Function obtenerErrores(ByVal columna As String, ByVal hoja As String, ByVal tipo As String) As Integer
Dim cmd As String = "SELECT [" & columna & "] FROM [" & hoja & "$]"
Dim errores As Integer = 0
Dim fecha As Date
Dim tabla As New DataTable
Try
Dim adapter As New OleDbDataAdapter(cmd, conexion)
adapter.Fill(tabla)
adapter.Dispose()
//Code
//Code
//Code
tabla.Dispose()
Return errores
Catch ex As Exception
repairmanMessage("Error inesperado", ex.Message, My.Resources._error).ShowDialog()
principal.lbldireccion.ForeColor = Color.Red
Return errores
End Try
Get this error...
I tried using parameterized queries, but looks like excel dont works fine with that thing (or maybe, i dont know the syntax of the query of that to use with excel).
The strangest thing of all is that in other parts of the code , do not give me errors , the program just throws errors when Im trying to modify the file, and
although I get these two errors , excel sheet is modified just as I wanted ..
What can be ?

Ok , I sat down to check everything and I had to think a little about what was happening. I discovered that my code did not have any error (that's why even though the program gave me errors , the file is modified anyway)... and discovered this too, let me explain it with an Excel file example:
Im using in my connection string the HDR property ("HDR=Yes;" indicates that the first row contains columnnames, not data. "HDR=No;" indicates the opposite.) as you can see , I have defined 4 columns (Name, Last name, Date, Age... not more! ).
We run the program now with this sample file and look carefully what happens:
As we saw in the first picture , I've never created a column in that position ('F1') ... apparently , there are times where you create without realizing it what I call "phantom columns " in Excel . I imagine it as the first cell of the column has nothing written on it , the program automatically gives it its name, according to their position ('F1 ' is the ghost column).
To fix this problem , when I make a query, first I check if my parameter "column " is not empty.
Protected Friend Function obtenerHojaActual(ByVal columna As String, ByVal con As String) As String
If (Not String.IsNullOrEmpty(columna)) Then
//Blah blah
//Blah blah
//Blah blah
End If
Return "Desconocida"
End Function
And there we go!

Related

Strange Update clause error (VB.NET)

I'm experiencing a really strange error. I have a table with only two columns (User and pass , both with text type).
The program asks first, what column I want to modify. With a radio button , I point which column I want to modify.
By pressing any radio button, two text boxes appear . You have to enter the password and the new data to modify it.
The problem is that when making the modification , if I want to change the user column , all is work well... But if I want to change a thing of the Password column , release "update error clause".
Honestly, I do not see any error in this code:
Protected Friend Sub modificarAcesso(ByVal column As String, ByVal dato As String)
Dim cmd As String = "Update Login SET " & column & "=#dato"
Try
con.Open()
comando = New OleDbCommand(cmd, con)
comando.Parameters.AddWithValue("#dato", dato)
comando.ExecuteNonQuery()
comando.Dispose()
con.Close()
Catch ex As Exception
con.Close()
MsgBox("Problemas en la consulta: " + ex.Message(), MsgBoxStyle.Critical)
End Try
End Sub
Password is a keyword, so you must put it in brackets. You should do this anyway if a column name has a space in it, too:
Dim cmd As String = "Update Login SET [" & column & "] = #dato"

VB.NET WCF - Error Using my function

I have a function to get information on a SQL Server Table. I know the function is correct and returning everything as suposed too (I used msgBox to check it). The problem is when I try to use that function it displays an error:
My WCF Function:
Public Function GetCLInfo(ByVal cl_ID As Integer) Implements SQLOperator.GetCLInfo
Dim CLInfo(7) As String
Try
SQLCon.ConnectionString = SQLConString
SQLCon.Open()
SQLCMD = New SqlCommand("Select * from dbo.cl Where ID=" & cl_ID & ";", SQLCon)
SQLDataReader = SQLCMD.ExecuteReader()
While SQLDataReader.Read
CLInfo(0) = SQLDataReader("ID")
CLInfo(1) = SQLDataReader("Name")
CLInfo(2) = SQLDataReader("Address")
CLInfo(3) = SQLDataReader("Contact")
End While
Return CLInfo
Catch ex As Exception
MsgBox("Error: " & Environment.NewLine & ex.ToString)
CLInfo(0) = "False"
Return CLInfo
Finally
SQLCon.Close()
SQLCon.Dispose()
End Try
Return CLInfo
End Function
In the picture you can see aswell how I'm trying to use the function.
Can someone kindly tell me what am I doing wrong?
Your problem is that you are calling a function to return string array and program doesn't catch by itself. As #Matt Wilko point out use Option Strict On.
Second if you have more than one client your logic fails.
For I as integer = 1 to AllCl
Dim cl(7) as String
cl = Service.GetClInfo(I)
next
Above code will reset every each time, plus when you leave for loop you are loosing access to cl.
Ugly fix could be multidimensional array.
Now you should specify your return type
Public Function GetCLInfo(ByVal cl_ID As Integer) As String() Implements SQLOperator.GetCLInfo

Preventing exceptions when an Access SQL query returns a blank record

The following function will throw an exception if the resulting field it found from the Access SQL query is empty.
If the query turns up empty, I just want retvalue to = nothing, but I get an error saying that I can't assign a null value to a string. So I put it in a catch, but the catch lags the application as this function is used quite often, and the query results are frequently empty.
An example situation would be:
checkRecord("Notes", "Table1", "First Name", "Steve")
The function returns the notes field for the record with a first name value of "Steve" in Table 1. If Steve's notes are empty (they often are), the function will throw an exception about converting a string to null.
How can I have it declare retvalue = nothing if the returned database record is empty, without having to do a catch?
Public Shared Function CheckRecord(Table As String, refcol As String, refcolvalue As String, targetcol As String)
Dim retvalue As String
Using cn As New OleDbConnection(mystr)
cn.Open()
Dim custCMDcr As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT [" & targetcol & "] FROM [" & Table & "] WHERE [" & refcol & "] =" & refcolvalue)
custCMDcr.Connection = cn
Try
retvalue = CType(custCMDcr.ExecuteScalar(), String).ToString
Catch fail As Exception
retvalue = Nothing
End Try
Return retvalue
End Using
End Function
Testing the result using isDBNULL worked, thank you!
If IsDBNull(custCMDcr.ExecuteScalar()) Then
retvalue = Nothing
else
(rest of code)
end if

OleDbDataAdapter - read tab delimited file

(I don't need alternatives to OleDbDataAdapter.)
The code below finds and reads the file OK but the DGV has four columns (as expected) but all the data rows just have text in the first column.
Dim sDir As String = "c:\temp\"
Dim sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sDir & ";Extended Properties='text;HDR=Yes;FMT=TabDelimited';"
Dim dt As New DataTable()
Using adapt As New OleDbDataAdapter(String.Format("SELECT TOP 100 * FROM robo.txt"), sConn)
adapt.Fill(dt)
End Using
DataGridView1.DataSource = dt
I would think the Extended Properties would be the only requirement. I've tried add a Schema.ini to no avail - I don't think it is even being read as the column headers never match the schema.
The header row in the most successful pass used commas as separator - this resulted in four columns with the proper names but the tab separated data all in Col1. If I use tabs in the header row I get some system assign columns (3) which sort of corresponds to a data row with two commas.
What am I doing wrong?
Here are the first few rows with the tab character being replaced by <tab> . I since noticed that I have an extra column in the data. The fix to the header row below did not fix the problem - all data is dumped into the first field.
Use a tab separator in the header, instead of commas, results in all header text and the data being dumped into the first field.
col1,state,col3,size,path
<tab> same<tab><tab> 102912<tab>\\APCD04T\Data\Thumbs.db
<tab> same<tab><tab> 22016<tab>\\APCD04T\Data\APCD Topical Info\APCD_Boards&Committees_List.doc
<tab> same<tab><tab> 4.3 m<tab>\\APCD04T\Data\APCD Topical Info\LOSSAN-LAtoSLORailCorridorStrategicPlan.pdf
Learned several things while trying to load a RoboCopy log into a DataTable using OLEDB.
log file needs to have a .txt or .csv (or ?) extension, .log fails.
Schema.ini seems to be needed for tab delimited robocopy log, good for column definition anyway.
Datagridview takes a long time to display 30MB of data so I used
filters
I borrowed code from the net to create a Schema.ini as noted below
(SO bug: code will not paste from Visual Studio anymore. Code tool flips to other web page for Java.)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Cursor = Cursors.WaitCursor
'http://ss64.com/nt/robocopy.html can suppress header and summary
Dim sFile As String = "c:\temp\robo.txt" ' seems to need a .txt or .csv, .log didn't work
CreateRoboLogSchema(sFile) ' recreates each pass, no needed once things work
Dim sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & IO.Path.GetDirectoryName(sFile) & ";Extended Properties='text';"
' use Schema.ini for: HDR=Yes;FMT=TabDelimited' and column definitions
Dim dt As New DataTable()
Dim SQL As String = "SELECT * FROM " & IO.Path.GetFileName(sFile)
'SQL &= " WHERE State <> 'Same'"
Using adapt As New OleDbDataAdapter(SQL, sConn)
adapt.Fill(dt)
End Using
Debug.Print("|" & dt.Rows(0)(1) & "|") ' show import trimmed leading spaces (trims trailing too)
' DGV slow to load large files, use filter to display target rows
Dim dv As New DataView(dt)
dv.RowFilter = "State <> 'Same'" ' not case sensitive
DataGridView1.DataSource = dv
DataGridView1.Columns(0).Visible = False
DataGridView1.AutoResizeColumns()
Catch ex As Exception
MsgBox(ex.Message)
Finally
'Cursor=Cursors.Default
End Try
End Sub
Private Function CreateRoboLogSchema(ByVal strFileName As String) As Boolean
' edit http://www.vb-tips.com/CSVDataSet.aspx
Dim ascii As System.Text.Encoding = System.Text.Encoding.ASCII
Dim swSchema As System.IO.StreamWriter = Nothing
Dim blnReturn As Boolean
Dim strSchemaPath As String = System.IO.Path.GetFileName(strFileName)
Try
strSchemaPath = IO.Path.GetDirectoryName(strFileName) & "\Schema.ini"
swSchema = My.Computer.FileSystem.OpenTextFileWriter(strSchemaPath, False, ascii)
Dim strFile As String = System.IO.Path.GetFileName(strFileName)
swSchema.WriteLine("[" & IO.Path.GetFileName(strFileName) & "]")
swSchema.WriteLine("ColNameHeader=False")
swSchema.WriteLine("Format=TabDelimited")
swSchema.WriteLine("Col1=Value1 Text") ' file specific
swSchema.WriteLine("Col2=State Text")
swSchema.WriteLine("Col3=DirChanges Text")
swSchema.WriteLine("Col4=Size Text")
swSchema.WriteLine("Col5=Filepath Text")
'Continue for all fields
blnReturn = True
Catch ex As Exception
blnReturn = False
Finally
If swSchema IsNot Nothing Then
swSchema.Close()
End If
End Try
Return blnReturn
End Function

Searching Excel Document Columns with Visual Basic and Interop

I'm struggling with a problem that involves interop and excel.
Basically, I have excel files with columns that contain "headers" and the rows beneath the columns have the data. For example, the column Age will have 12,14,etc underneath it. I am new to Interop and I'm trying to allow the user to enter the name of the column header they wish to extract data from, so if they enter "Age", it'll find age is colum B for example and then extract all the data from the proceeding rows.
I've Googled extensively and haven't found anything solid, all rather context orientated and being new to Interop makes this a little tricky.
What I've got so far:
Public Sub getExcelData(ByVal directory As String)
Dim excelAppFirstFile As Excel.Application = Nothing
excelAppFirstFile = CreateObject("Excel.Application")
Try
excelAppFirstFile.Workbooks.Open(directory)
Dim excelSheet As Excel.Worksheet = excelAppFirstFile.Worksheets(1)
Catch ex As Exception
MsgBox("There was a problem: " + ex.Message)
End Try
End Sub
I know it isn't much but I've gone in circles with ranges,etc and can't figure out how to get where I need to.
EDIT:
I forgot to add that the Column name being searched for is a variable called field which is set at an earlier stage by the user.
If all you want to do is read data in the Excel file, I suggest you to use OleDb instead of interop (which is much faster):
Dim filePath As String = "C:\Book1.xls"
Dim connectionString As String = (Convert.ToString("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=") & filePath) + ";Extended Properties=""Excel 8.0"";"
Dim connection As New OleDbConnection(connectionString)
Dim cmdText As String = "SELECT * FROM [Sheet1$]"
Dim command As New OleDbCommand(cmdText, connection)
command.Connection.Open()
Dim reader As OleDbDataReader = command.ExecuteReader()
If reader.HasRows Then
While reader.Read()
Console.WriteLine("{0}" & vbTab & "{1}", reader(0).ToString(), reader(1).ToString())
End While
End If