Monday, March 12, 2012

VB Scripts which freeze the sheet from selected row

Sub Freez_funtions()
Worksheets("Sheet1").Select
With ActiveWindow
.SplitColumn = 0
.SplitRow = 8 'row number. sheet will freez from this row
End With
ActiveWindow.FreezePanes = True
End Sub

VB Scripts which create an array with unique values

Sub Array_With_Unique_Values()
Dim strArray(0 To 19) As String
j = 0
For i = 2 To 20
If Worksheets("Sheet1").Cells(i, 1).value <> "" Then
strArray(j) = Worksheets("Sheet1").Cells(i, 1).value
j = j + 1
End If
Next i

For n = 1 To 19
For p = 0 To 19
If strArray(n) = strArray(p) And n <> p Then
strArray(n) = ""
End If
Next p
Next n

m = 2
For k = 0 To 19
If strArray(k) <> "" Then
Worksheets("Sheet2").Cells(m, 2).value = strArray(k)
m = m + 1
End If
Next k
End Sub

VB Scripts which delete data from the SQL2005 DB

Sub DELETE_SQL()
Dim oCon As ADODB.Connection
Dim oRS As ADODB.Recordset
Set oCon = New ADODB.Connection
oCon.ConnectionString = "Driver={SQL Native Client};Server=Server_Name;Database=DB_Name; Trusted_Connection=yes;"
oCon.Open
'Set oRS = New ADODB.Recordset
Set rs = oCon.Execute("DELETE FROM Table_Name_001")
Set rs = oCon.Execute("DELETE FROM Table_Name_002")
Set rs = oCon.Execute("DELETE FROM Table_Name_003")
Set rs = oCon.Execute("DELETE FROM Table_Name_004")
rs.Open
oCon.Close
MsgBox ("Successfully Data Deleted from the Database")
End Sub

VB Scripts which import records from the 2005 SQL DB

Sub Create_CSV_File()
Dim oCon As ADODB.Connection
Dim oRS As ADODB.Recordset
Set oCon = New ADODB.Connection
oCon.ConnectionString = "Driver={SQL Native Client};Server=Server_Name;Database=DB_Name; Trusted_Connection=yes;"
oCon.Open
Set oRS = New ADODB.Recordset
oRS.ActiveConnection = oCon
oRS.Source = "Select * from table name"
oRS.Open
Worksheets("Sheet1").Range("A1").CopyFromRecordset oRS
oRS.Close
oCon.Close
If Not oRS Is Nothing Then Set oRS = Nothing
If Not oCon Is Nothing Then Set oCon = Nothing
MsgBox("Successfully data imported from the DB")
End Sub

VB Script which create a CSV file

Sub Create_CSV_File()
Dim FileName, CSVPath, CSVFile As String

CSVPath = "C:\CSV_Folder\"
CSVFile = "CSV_File_Name.csv"

FileName = CSVPath + CSVFile

Open FileName For Output As #1
Print #1, "records 01" & "," & "records 02" & "
For i = 2 To 10
Print #1, Worksheets("Sheet1").Cells(i, 1).Value & "," & Worksheets("Sheet1").Cells(i, 1).Value & "
Next i
Close #1

MsgBox ("Successfully cerated ")

End Sub