Archive for category Visual Basic 6 (vb6)
Copy Data from Excel to SQL Server (or any DBMS) Script to generate Insert Statements in Excel
Posted by Anthony in Microsoft Access, SQL, SQL Server, VBScript (VBS), Visual Basic 6 (vb6) on May 31, 2011
Unfortunately sometimes copy / paste from Excel into SQL server doesn’t work. Since moving data from Excel into SQL server (or another DBMS) can sometimes prove trickier than it should be I’ve created this handy script to help with just that. To get it to work:
1) Paste it into your excel project as a macro.
2) Select the sheet you want to copy
3) The first row of your sheet must contain the column names of the table to be inserted into.
4) Update the macro to use the correct table (look for TABLE_NAME_HERE)
That’s it! Put your cursor in the method and press F5. Upon completion you’ll get a message box with “complete” in it. Once the file is generated copy the contents of c:\temp\insert.txt into Management Studio / Toad / etc and run it.
Sub GenerateInsertRecords()
'Code thanks to http://anthonystechblog.wordpress.com
'Feel free to use, change and re-distribute the code you find on my site,
'all I ask is you leave these these comments intact!
Dim i As Integer, ii As Double, iColumn as integer
Dim str As String, strInsert As String, strComplete As String
str = ""
str = "insert into TABLE_NAME_HERE ("
For i = 1 To 999
If Len(Cells(1, i)) < 1 Then Exit For
str = str & Cells(1, i) & ","
Next i
str = Left(str, Len(str) - 1)
str = str & ") values ("
Dim oConvert As Variant
strInsert = str
strComplete = ""
For ii = 2 To 65000
If Len(Cells(ii, 1)) < 1 Then Exit For
strComplete = strComplete & strInsert
str = ""
For iColumn = 1 To i - 1
oConvert = getInput(Cells(ii, i))
str = str & oConvert & ","
Next iColumn
str = Left(str, Len(str) - 1)
str = str & ")"
strComplete = strComplete & str & vbNewLine
Next ii
Dim oFS As Scripting.FileSystemObject
Set oFS = CreateObject("Scripting.FileSystemObject")
Dim oText As Scripting.TextStream
Set oText = oFS.OpenTextFile("c:\temp\insert.txt", ForWriting, True)
oText.Write (strComplete)
oText.Close
MsgBox ("complete")
End Sub
Function getInput(theInput As Variant) As Variant
Dim retval As Variant
If IsNull(theInput) Then
retval = "Null"
ElseIf UCase(theInput) = "NULL" Then
retval = "Null"
ElseIf IsNumeric(theInput) Then
retval = theInput
Else
retval = "'" & theInput & "'"
End If
getInput = retval
End Function
Calculating PI, ASin, ACos in VB (VBScript, Excel, Word, Access)
Posted by Anthony in Microsoft Access, VBScript (VBS), Visual Basic 6 (vb6) on May 27, 2011
I was recently surprised when I found out a number of numerical functions don’t exist in Access. Granted I believe they do exist in Excel, and probably word, but if you’re doing any coding you may find this useful anyway. Here is the code to accomplish all three:
'Code thanks to http://anthonystechblog.wordpress.com
'Feel free to use, change and re-distribute the code you find on my site,
'all I ask is you leave these these comments intact!
Public Function PI() As Double
PI = 4 * Atn(1)
End Function
Public Function ASin(val As Double) As Double
ASin = 2 * Atn(val / (1 + Sqr(1 - (val * val))))
End Function
Public Function ACos(val As Double) As Double
ACos = PI / 2 - ASin(val)
End Function
If you’re wondering, Atn() IS built into Access, so these functions should work as is, they do for me!
ICO Files – add a image to your application
Posted by Anthony in .Net, Forms, Visual Basic 6 (vb6) on August 30, 2010
I developed a great n-tiered application for my customer recently. I put the webservices on their IIS server and ran my client showing how they could get data using click once installation and not have to manage the resources at all.
It was pretty awesome, I was proud of it and expected my client to be wowed. Guess what their first comment was?
Them: “That icon is no good”
Me: “Uh, yeah, it’s just a demo app”
Them: “Can you fix that? Oh, and the project name is no good either”
Me: “Yeah, again, demo app. I’ll change those things for sure. So, how do you like click once?”
So, I thought this was pretty amusing. After that meeting I went out to get him an icon suitable to a business app and I found this site:
http://www.iconarchive.com/
It’s a great resource with thousands of icons! I’m sure you’ll find it a great resource on your next project.
Oh, and if you were wondering which icon I picked, I recommend the Tie Fighter. Nothing says scheduling like a Tie Fighter
How to automate mapping network drives via script – VBS Logon Script – MapNetworkDrive
Posted by Anthony in Legacy, Management, VBScript (VBS), Visual Basic 6 (vb6), Windows on July 13, 2010
How to automate mapping network drives via script
My coworkers were constantly managing their clients mapped drives so I wrote a script to automate setting them up. I wrote it both in VB6 and VBScript for those of you interested in seeing it written both late and early bound. Here it is:
==== VBScript ====
(to use this put it in a file with a .vbs extension and then double click on it)
Main
Sub Main()
Dim sNetworkString
sNetworkString = "I:,\\somenetworklocation\somefolder;
J:,\\someothernetworklocation\asubfolder;M:,\\onemorenetworklocation\something"
Dim sNetworkArray
sNetworkArray = Split(sNetworkString, ";")
Dim sNetworkLine
Dim objNetwork
Set objNetwork = CreateObject("WScript.Network")
'To remove a network drive: call objNetwork.RemoveNetworkDrive("I:",true,true)
Dim item
For Each item In sNetworkArray
sNetworkLine = Split(item, ",")
On Error Resume Next 'This is here to ignore the drive errors if they
'already exist
objNetwork.MapNetworkDrive sNetworkLine(0), sNetworkLine(1)
On Error GoTo 0
Next
End Sub
==== VB6 ====
(to use this put it in a VB6 forms or console app, add a reference to
‘”Windows Script Host Object Model” and compile)
Private Sub Form_Load()
Dim sNetworkString As String
sNetworkString = "I:,\\somenetworklocation\somefolder;
J:,\\someothernetworklocation\asubfolder;M:,\\onemorenetworklocation\something"
Dim sNetworkArray() As String
sNetworkArray = Split(sNetworkString, ";")
Dim sNetworkLine() As String
Dim objNetwork As WshNetwork
Set objNetwork = CreateObject("WScript.Network") ' WshNetwork
'To remove a network drive: call objNetwork.RemoveNetworkDrive("I:",true,true)
Dim item As Variant
For Each item In sNetworkArray
sNetworkLine = Split(item, ",")
On Error Resume Next 'This is here to ignore the drive errors if they already exist
objNetwork.MapNetworkDrive sNetworkLine(0), sNetworkLine(1)
On Error GoTo 0
Next item
End Sub
If you want to make this smarter you could play with objNetwork.EnumNetworkDrives(). By using this collection you could bypass my messy method of ignoring already mapped drives by ignoring the error they throw.
How it works:
You may of noticed above there is a variable declared like so:
sNetworkString = “I:,\\somenetworklocation\somefolder;
J:,\\someothernetworklocation\asubfolder;M:,\\onemorenetworklocation\something”
This variable is key to this function working. If you want to map more / less / different paths all you need to do is add your own to this string. It is delimited by comma and semi colon, so this maps the X drive:
sNetworkString = “X:,\\mycomputer\afolder”
and this maps X and Y:
sNetworkString = “X:,\\mycomputer\afolder;Y:,\\anothercomputer\folder1\folder2″
Note that there is no semi-colon (;) at the end of the string. This is intentionally omitted because of the way Split() works.
If you use this script in your company I would love to hear about it! Feel free to post your comments here, I always enjoy hearing about other people’s experiences.
Date Time stuff
Posted by Anthony in Oracle, SQL, SQL Server, VBScript (VBS), Visual Basic 6 (vb6) on August 20, 2009
I write code in VB6, VB.Net, C#, VB Script, TSQL, Java, JavaScript, and I find I’m regularly scrambling for the proper date time code for each. I find myself asking “What on earth did they name THAT date function in THIS language again? I just did this X months ago, why on earth can’t I remember…”. So I finally decided to write some of it down. Hopefully you find it useful. My intention is to update this page as I use different features.
In SQL for Microsoft SQL Server:
How to get the Month / Day in the format “Aug20″:
select Left(DateName(Month,getdate()),3) + Convert(varchar(50),Day(getdate()))
In SQL for Oracle
How to get all the records created in the last 15 minutes:
select * from tableName where theDate > (sysdate – (15/(24*60))
How to view the full date when selecting columns:
Option 1) Run this statement:
alter session set nls_date_format=’dd-mm-yyyy hh24:mi:ss’
Then run any sql containing a date column after.
Option 2) Us the to_char() function:
select to_char(theDateColumn, ‘DD-MON-YYYY HH:MI:SS’) as aDate from theTableName
In VB6
Get the current Date / Time: Now()
Incrementing / Decrementing a date reliably, use the DateAdd() function, for decrementing just pass a negative parm. This is the best method because it will automatically handle things like leap years, months with different days (30, 31, 28, 29), etc:
dim dDateVariable as Date
dDateVariable = DateAdd(“n”, -3, Now())
More on the Interval format here: http://msdn.microsoft.com/en-us/library/cb7z8yf9
NOTES:
Oracle stores dates as a number, where hours, minutes and seconds are fractions of that number. So a value of 1 = 1 day, and a value of 1.125 = 1 day and .125 of a day or .125 * 24 = 3 hours. To get minutes you multiply the date by hours in a day (24) and then by minutes in a hour (60). Since 24 * 60 = 1440 many examples out there just say to multiply 1440 to get minutes.
Thanks goes out to Mike for the math correction in my original post.
Parameterized SQL / Transactional SQL in VB / Access
Posted by Anthony in Microsoft Access, Visual Basic 6 (vb6) on August 6, 2009
I have got to get out of the legacy world and start posting something more current. I’m currently working for a client that has an enormous amount of data and code invested in MS Access and I have the go ahead to convert it to .Net… But. But I have to continue to support and debug the current system at the same time. It will be a while, but I’ll have this thing in tip top shape yet.
So, if you’re a poor sap like me and have to maintain some legacy code you may find this tidbit useful. How to write parameterized SQL in VB / Access code and I added transaction support to boot.
Private Sub DoBatch(ByRef rs As ADODB.Recordset)
Dim cn As ADODB.Connection
Dim cmd As New ADODB.Command
Set cn = CurrentProject.AccessConnection
Call cn.BeginTrans
Dim sCMD As String
sCMD = “update t_TableName set Var1=@inVar1, Var2=@inVar2, Var3=@inVar3, ” & _
“Var4=@inVar4 Where Var5=@inVar5″
Do While Not rs.EOF
With cmd
.ActiveConnection = cn
.CommandText = sCMD
Call .Parameters.Append(CreateParameter(“@inVar1″, nz(rs.Fields(“Var1″), 0), 4, adNumeric))
Call .Parameters.Append(CreateParameter(“@inVar2″, nz(rs.Fields(“Var2″), 0), 4, adNumeric))
Call .Parameters.Append(CreateParameter(“@inVar3″, nz(rs.Fields(“Var3″), 0), 4, adNumeric))
Call .Parameters.Append(CreateParameter(“@inVar4″, nz(rs.Fields(“Var4″), 0), 50, adVarChar))
Call .Parameters.Append(CreateParameter(“@inVar5″, nz(rs.Fields(“Var5″), 0), 4, adNumeric))
Call .Execute()
End With
Call rs.MoveNext
Loop
Call cn.CommitTrans
End Sub
Private Function CreateParameter(ByVal Name As String, ByVal value As Variant, ByVal Size As ADO_LONGPTR, ByVal theType As ADODB.DataTypeEnum, Optional ByVal direction As ParameterDirectionEnum = dbParamInput) As ADODB.Parameter
Dim tempP As New ADODB.Parameter
tempP.Name = Name
tempP.value = value
tempP.direction = adParamInput
tempP.Size = Size
tempP.Type = theType
Set CreateParameter = tempP
End Function
Disconnected RecordSet VB / Access with ADO
Posted by Anthony in Microsoft Access, Visual Basic 6 (vb6) on August 6, 2009
Code to run a disconected recordset (which by the way will allow the .RecordCount property to be calculated). This is useful mainly for reads of data where you don’t need to lock the recordset for any reason. Before we migrated to .Net we used this in our enterprise web applications all the time.
Public Sub GetData()
On Error GoTo err_des
Dim cn As ADODB.Connection
Dim rs As New ADODB.Recordset
Set cn = CurrentProject.AccessConnection ‘Here we’re using Microsoft Access, you could create your own connection in much the same way.
rs.CursorLocation = adUseClient
Call rs.Open(“q_GetSomeData”, cn, adOpenStatic, adLockBatchOptimistic)
Set rs.ActiveConnection = Nothing
‘do something with rs here.
Exit Sub
err_des:
MsgBox “oops: ” & Err.Description
End Sub
How to decode a blob datatype to string in VB / Access
Posted by Anthony in Microsoft Access, Visual Basic 6 (vb6) on August 6, 2009
Private Function Decode(ByRef rc As ADODB.Recordset) As String
Dim myStream As New ADODB.Stream
myStream.TYPE = adTypeBinary
myStream.Open
Call myStream.Write(rc.Fields(“theBlob”))
myStream.Position = 0
Dim sResults As String
sResults = “”
Do While Not myStream.EOS
sResults = sResults & Chr(AscB(myStream.Read(1)))
Loop
Decode= sResults & vbNewLine
End Function
This code had me scratching my head at first. The Stream.Write() method writes into the stream from the record field, not to some standard output like a file IO object would. Also be sure you’re referencing one of the newer versions of Microsoft ActiveX Data Objects X.X Library. I’m referencing 2.8 which works like a charm. The project I modified originally referenced 2.0 which didn’t even have a .Stream class in ADODB.
How to use ADO in MS Access / Visual Basic
Posted by Anthony in Microsoft Access, SQL, Visual Basic 6 (vb6) on August 6, 2009
Just a quick example of data access code that uses ADO to get a recordset. Typically this type of code ports well from Access to VB and vice versa. It also nearly ports to script files, remove the variable types and you’re good to script.
Private Sub SetSomeData()
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim param As ADODB.Parameter
Set param = New ADODB.Parameter
param.NAME = “theColumn_Id”
param.value = “Some Value”
param.TYPE = adVarChar
param.Size = 40
param.Direction = adParamInput
Set cn = CurrentProject.AccessConnection
Set cmd = New ADODB.Command
With cmd
Call .Parameters.Append(param)
.ActiveConnection = cn
.CommandText = “q_GetSomeData” ‘uses a MS Access query
.CommandType = adCmdTable
Set rs = .Execute()
End With
If rs.RecordCount > 0 Then
tSomeData = GetSomeDataFromTheRecordset(rs)
Else
tSomeData = “”
End If
Call rs.Close
End Sub
This is what the Access query looks like:
q_GetSomeData:
PARAMETERS theColumn_ID Text ( 255 );
SELECT Column1, Column2
FROM my_Table
WHERE Column_ID = theColumn_ID
How to decode a hex string in vb6
Posted by Anthony in Visual Basic 6 (vb6) on August 5, 2009
I find I’m always re-inventing the wheel when it comes to application development. Hopefully this will become a useful library of code snippets that not only I will find useful, but the development community at large. Feel free to ask any questions you may have on any items I post as I’m not likely to have time to provide a walk through for every post I make.
Private Sub Command1_Click()
Dim sStr As String
sStr = “0x74657374206161616120746573740D0A2D2D53595341444D”
Dim sResult As String
sResult = “”
Dim i As Integer
For i = 1 To Len(sStr) Step 2
sResult = sResult & (Chr(Val(“&H” & Mid(sStr, i, 2))))
Next i
Debug.Print sResult
End Sub