Im using visual basic and visual studio 2010.
I researched on importing csv files to access database and I found this generic codes. The problem is, I'm really new in visual basic. I declared the variables but I got the error: "Declaration expected".. and the Do while and Loop are having an error which is: "Statement cannot appear outside of a method
Public Class Form1
Dim strPathFile As String
Dim strFile As String
Dim strPath As String
Dim strTable As String
Dim blnHasFieldNames As Boolean
blnHasFieldNames = True
strPath = "C:\Users\vissia18\Desktop\ReportDB\"
strTable = "Report"
strFile = Dir(strPath & "*.csv")
Do While Len(strFile) > 0
strPathFile = strPath & strFile
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
strTable, strPathFile, blnHasFieldNames
strFile = Dir()
Loop
End Class
The first thing I see is that no method or subroutine has been declared.
That is essential.
How about declaring a Main like this:
Public Class Form1
Sub Main()
Dim strPathFile As String
Dim strFile As String
...
End Sub
End Class
This will give your application a staring point.
May I suggest MSDN - Microsoft Developer Network - specifically the video walk through labelled "Visual Basic Fundamentals: Development for Absolute Beginners".
Related
I am using GetDriveSerialNumber() to retrieve drive volume serial number in visual basic 2010.
I have the following imports:
Imports System
Imports System.IO
Imports System.Text
Imports System.Net.NetworkInformation
Imports System.Management
Imports System.Collections
Imports Microsoft.Win32
Imports Microsoft.VisualBasic
And then in the Module:
Dim path As String
'Get HD volume Serial Number from Function
Dim DriveVID As String = GetDriveSerialNumber()
The function is:
'Get HD Volume serial Number
Public Function GetDriveSerialNumber() As String
Dim DriveSerial As Long
Dim fso As Object, Drv As Object
'Create a FileSystemObject object
fso = CreateObject("Scripting.FileSystemObject")
Drv = fso.GetDrive(fso.GetDriveName(AppDomain.CurrentDomain.BaseDirectory))
With Drv
If .IsReady Then
DriveSerial = .SerialNumber
Else '"Drive Not Ready!"
DriveSerial = -1
End If
End With
'Clean up
Drv = Nothing
fso = Nothing
GetDriveSerialNumber = Hex(DriveSerial)
End Function
This works great for 9 out 10 computers,
Only one gives me back a different 7 characters,
Oppose to the 8 characters it should give me,
Even when I type vol command in cmd,
On that computer,
It gives me the correct 8 characters volume serial number,
Does anyone know what’s wrong?
This Function seems to work with all my test computers:
Private Function GetDriveSerialNumber(ByVal drive As String) As String
Dim driveSerial As String = String.Empty
Dim driveFixed As String = Path.GetPathRoot(drive)
driveFixed = Replace(driveFixed, "\", String.Empty)
Using querySearch As New ManagementObjectSearcher("SELECT VolumeSerialNumber FROM Win32_LogicalDisk Where Name = '" & driveFixed & "'")
Using queryCollection As ManagementObjectCollection = querySearch.Get()
Dim moItem As ManagementObject
For Each moItem In queryCollection
driveSerial = CStr(moItem.Item("VolumeSerialNumber"))
Exit For
Next
End Using
End Using
Return driveSerial
End Function
The only thing is that you have to send a drive letter to the Function,
Which is not a problem with me,
I'm trying to get Volume Serial Number using Visual Basic 2010,
Is there a whole code example that shows me how to do this?
Thanks
I guess the simplest answer to my question was given by:
Hans Passant:
From his link,
I just copied and pasted this function and it works for Microsoft Visual basic 2010 express, Without any modifications
Public Function GetDriveSerialNumber() As String
Dim DriveSerial As Long
Dim fso As Object, Drv As Object
'Create a FileSystemObject object
fso = CreateObject("Scripting.FileSystemObject")
Drv = fso.GetDrive(fso.GetDriveName(AppDomain.CurrentDomain.BaseDirectory))
With Drv
If .IsReady Then
DriveSerial = .SerialNumber
Else '"Drive Not Ready!"
DriveSerial = -1
End If
End With
'Clean up
Drv = Nothing
fso = Nothing
GetDriveSerialNumber = Hex(DriveSerial)
End Function
I would like to thank everyone for their help,
And i apologize for repeating the question,
I did do a google search and a stackflow search,
But my search was"
"get hard drive serial number in visual basic 2010"
So this website did not show up,
Thanks again
This thread here http://social.msdn.microsoft.com/Forums/vstudio/en-US/43281cfa-51c8-4c35-bc31-929c67abd943/getting-drive-volume-serial-number-in-vb-2010 has the following bit of code that you could use/adapt.
I made a piece of code for you to show all drive information.
The Volume serial number is included you can get that by simple
putting some more if's in the code
Imports System.Management
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim drivetype() As String = {"Unknown", "NoRootDirectory", _
"RemoveableDisk", "LocalDisk", "NetworkDrive", "CompactDisk", "RamDisk"}
Dim allDrives() As String = Environment.GetLogicalDrives()
For Each drive In allDrives
Dim win32Drive As String = _
"Win32_LogicalDisk='" & drive.Substring(0, 2) & "'"
Dim Disk As System.Management.ManagementObject _
= New System.Management.ManagementObject(win32Drive)
Me.ListBox1.Items.Add(drive.ToString & drivetype(CInt((Disk("DriveType").ToString))))
For Each diskProperty In Disk.Properties
If Not diskProperty.Value Is Nothing Then
Me.ListBox1.Items.Add("---" & diskProperty.Name & "=" & diskProperty.Value.ToString)
End If
Next
Next
End Sub
End Class
I'm having some trouble with looping and creating MS Excel docs, code snippet below
Private Sub selectedRowsButton_Click( _
ByVal sender As Object, ByVal e As System.EventArgs) _
Handles selectedRowsButton.Click
Dim selectedRowCount As Integer = _
DataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected)
If selectedRowCount > 0 Then
Dim sb As New System.Text.StringBuilder()
Dim objexcel As New Excel.Application
Dim i As Integer
Dim FACode As Integer
Dim Sitename As Integer
Dim Sitecode As Integer
Dim Address As Integer
Dim City As Integer
Dim State As Integer
Dim ZIP As Integer
FACode = 1
Sitename = 5
Sitecode = 2
Address = 6
City = 7
State = 9
ZIP = 10
Dim xlWorkbook As Excel.Workbook
xlWorkbook = objexcel.Workbooks.Open("template path")
For i = 0 To selectedRowCount - 1
objexcel.Visible = True
objexcel.Range("B2").Value = DataGridView1.SelectedCells(Sitename).Value.ToString()
objexcel.Range("B3").Value = DataGridView1.SelectedCells(Sitecode).Value.ToString()
objexcel.Range("B5").Value = DataGridView1.SelectedCells(FACode).Value.ToString()
Dim thisfile As Object
thisfile = objexcel.Range("B5").Value & "." & _
objexcel.Range("B3").Value & "." & "otherstring" & "." & "otherstring2" & "." & ".xls"
With objexcel
xlWorkbook.SaveAs(Filename:="c:\test\" & thisfile)
'~~> Close the Excel file without saving
xlWorkbook.Close(False)
End With
Next i
End If
I'm getting the error Exception from HRESULT: 0x800A03EC for the statement
objexcel.Range("B2").Value = DataGridView1.SelectedCells(Sitename).Value.ToString()
IF I select only one row of my DataGrid before creating the program works fine, it is when I select multiple rows that this error occurs. Since I'm creating the program specifically for multiple row selections I'm stumped as to where I've gone wrong. Any help or pointers appreciated, Thanks!
Two things
You have declared objexcel As Excel.Application so you shouldn't use objexcel.Range("B2").Value. Use xlWorkbook.Range("B2").Value. Change it everywhere in your code.
You cannot use SaveAs like that. See the snapshot below. If you want to save as xls file then you have to use FileFormat:=56
See this code example
'~~> Save As file
xlWorkbook.SaveAs(Filename:="c:\test\" & thisfile, FileFormat:=56)
If you do not specify the file format then you will get an error message when you open the file after opening.
You might want to look at this link on how to automate Excel from VB.Net
Topic: VB.NET and Excel
Link: http://www.siddharthrout.com/vb-dot-net-and-excel/
I am not too sure what you exactly are trying to do with the DGV. Like Sean mentioned you are not incrementing the values. If you can post a snapshot of how your DGV looks and how your Excel file should look after the export then we can help you in a much better way :)
I am trying to update an ancient VB6 project to enable communication with a remote OPC Server. I have installed the Siemens toolkit but I am unable to find any useful documentation on how to use it with VB6. (Works with C#)
The application is very simple. I just need to connect to the remote server and write/read single addresses.
I found the DatCon OCX control which I assume handles the communication but all the ServerName values I tried to enter by hand did not work.
Can anyone help?
Add a reference to the DLL or OCX (the seimens toolkit) to your VB6 project and then use the object browser to browse around the exposed objects. You can often times figure out what you need just be doing that.
The C# docs should also provide a wealth of info. If the library is a COM library, you'll use it essentially the same way from VB6.
Since posting, I did make some progress. The following example helped me to get going.
http://support.automation.siemens.com/WW/llisapi.dll?func=cslib.csinfo&objId=25229521&load=treecontent&lang=en&siteid=cseus&aktprim=0&objaction=csview&extranet=standard&viewreg=WW
Here is my current code. It's not much - just makes contact with the server and tries to write a value. I didn't get any further. I started getting COM errors and assumed the installation was bad (I had had problems installing) so I decided to reinstall. It didn't work. Installation was impossible. Waiting for an upgrade from Siemens.
'
' OPC Communication
'
' Paul Ramsden 24.11.2011
'
'
Option Explicit
Option Base 1
Public MyOpcServer As OPCServer
Public ServerHandle As Variant
Private ServerName As String
Private ServerNode As String
Private TestGroup As OPCGroup
Private MyOpcItem As OPCItem
Private IsInitialised As Boolean
Public Sub InitialiseOPC()
On Error GoTo ProcError
IsInitialised = False
Set MyOpcServer = New OPCServer
ServerNode = "xyz.abc.10.101"
ServerName = "OPC.SimaticNET.1"
Dim LocalServers
LocalServers = MyOpcServer.GetOPCServers(ServerNode)
Dim tmp
ServerHandle = ""
For Each tmp In LocalServers
If CStr(tmp) = ServerName Then
Call MyOpcServer.Connect(tmp)
MsgBox MyOpcServer.ServerNode & vbCr & MyOpcServer.ServerName & vbCr & MyOpcServer.ServerState
ServerHandle = tmp
Set TestGroup = MyOpcServer.OPCGroups.Add("TestGroup")
Exit For
End If
Next
If ServerHandle = "" Then
MsgBox "Could not find server " & ServerName & " on " & ServerNode
Else
IsInitialised = True
End If
ProcExit:
Exit Sub
ProcError:
MsgBox Err.Description
Resume ProcExit
End Sub
Private Sub ClearGroup()
Dim handles() As Long
Dim errors() As Long
Call TestGroup.OPCItems.Remove(TestGroup.OPCItems.Count, handles, errors)
End Sub
Public Sub WriteOPC(address As String, value As String)
On Error GoTo ProcError
Call ClearGroup
Set MyOpcItem = TestGroup.OPCItems.AddItem(address, 2011)
MyOpcItem.Write (value)
Exit Sub
ProcError:
MsgBox "Write error! " & Err.Description
End Sub
Public Function ReadOPC(address As String) As String
On Error GoTo ProcError
Call ClearGroup
Set MyOpcItem = TestGroup.OPCItems.AddItem(address, 2011)
Dim value As String
ReadOPC = MyOpcItem.Read
ProcError:
MsgBox "Read error! " & Err.Description
End Function
Public Sub TestOPC()
InitialiseOPC
WriteOPC "SIMATIC 300(1).CPU 315-2 DP.Q0_0TestAusgang1", "1"
End Sub
In Windows Explorer you can extract a compressed folder (a zip file)
Is there an API or command line to extract a zip file using the same method programatically?
You can use this VBScript script:
'Adapted from http://www.robvanderwoude.com/vbstech_files_zip.html
strFile = "c:\filename.zip"
strDest = "c:\files"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FolderExists(strDest) Then
objFSO.CreateFolder(strDest)
End If
UnZipFile strFile, strDest
Sub UnZipFile(strArchive, strDest)
Set objApp = CreateObject( "Shell.Application" )
Set objArchive = objApp.NameSpace(strArchive).Items()
Set objDest = objApp.NameSpace(strDest)
objDest.CopyHere objArchive
End Sub
Check Compress Zip files with
Windows Shell API and C#
You could use SharpZipLib which
is free for a dot net project.
I tried the above function Sub UnZipFile(...) under Excel 2010 and it was not working: Run-time error '91' (Object variable or With block not set) in the line
Set objArchive = objApp.Namespace(strArchive).Items()
and the line
Set objDest = objApp.Namespace(strDest)
is silently also not working: After execution the objDest is still nothing!
Microsoft's .Namespace() accepts as parameter either an object, a string constant or a string variable. With string variables there are often suspicious problems, which are requiring an workaround:
Set objArchive = objApp.Namespace(**CStr(** strArchive **)**).Items()
Set objDest = objApp.Namespace(**CStr(** strDest **)**)
or an alternative workaround
Set objArchive = objApp.Namespace(**"" &** strArchive).Items()
Set objDest = objApp.Namespace(**"" &** strDest)
And the line objDest.CopyHere objArchive was also not working: The destination folder remained empty!
Here a version, which is working in Excel 2010 and most probably also in other environments:
Sub UnZipFile(strZipArchive As String, strDestFolder As String)
Dim objApp As Object
Dim vItem As Variant
Dim objDest As Object
Set objApp = CreateObject("Shell.Application")
Set objDest = objApp.Namespace(CStr(strDestFolder))
For Each vItem In objApp.Namespace(CStr(strZipArchive)).Items
objDest.CopyHere vItem
Next vItem
End Sub
For C# or VB users, you can check the answer from MSDN:
https://msdn.microsoft.com/en-us/library/ms404280(v=vs.100).aspx
For .net 4.x, here is the sample code from MSDN
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.zip";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
}