Rabu, 24 Februari 2010

search form pada microsoft access

Private Sub Command8_Click()
Dim LSQL As String
Dim LSearchString As String

If Len(Text6) = 0 Or IsNull(Text6) = True Then
MsgBox "You must enter a search string."

Else

LSearchString = Text6

'Filter results based on search string
LSQL = "select * from SISWA"
LSQL = LSQL & " where NAMA LIKE '*" & LSearchString & "*'"

Me.RecordSource = LSQL

'Clear search string
Text6 = ""

MsgBox "Berhasil. Ditemukan nama " & LSearchString & "."

End If
End Sub

VBA Excel

Option Explicit
Private Sub menu()
Dim obj As CommandBarPopup
Dim objbutton As CommandBarButton
Set obj = Application.CommandBars("Worksheet Menu Bar").Controls("Tools")
On Error Resume Next
Set objbutton = obj.Controls("Report")
If Err.Number <> 0 Then
Set objbutton = obj.Controls.Add(Type:=msoControlButton, before:=4)
End If
On Error GoTo 0
With objbutton
.Caption = "Report"
.OnAction = "Halo"
.FaceId = 248
End With
End Sub
====================================================
Dim obj As Object
Dim baris As Integer
Option Explicit
Private Sub CommandButton1_Click()
baris = baris + 1
Cells(baris, 1).Value = TextBox1.Value
Cells(baris, 2).Value = TextBox2.Value
Cells(baris, 3).Value = ComboBox1.Value

End Sub

Private Sub UserForm_Initialize()

Cells(1, 1).Value = "Nama"
Cells(1, 2).Value = "Alamat"
Cells(1, 3).Value = "Jenis Kelamin"
With ComboBox1
.AddItem "L"
.AddItem "P"
End With

baris = 1
End Sub
=========================================================
Sub Halo()
UserForm1.Show

End Sub

Jumat, 19 Februari 2010

REGULAR EXPRESSION

html
head
titleKATA KOTOR/title

script language="javascript"
function saring(huruf)
{
var kata=/fuck|shit/gi;
return huruf.replace(kata, function(cocok)
{
return cocok.replace(/./g,"*");
});
}

function tampil()
{
var oInput1=document.getElementById("txt1");
var oInput2=document.getElementById("txt2");
oInput2.value=saring(oInput1.value);
}
/script
/head
body
input type=text id="txt1"
input type="button" value="0k" onclick="tampil()"
br
Hasil:
br
input type=text id="txt2"

/body
/html

DHTML TEXT TICKER

html
head
title>Ticker1
/title
script language="javascript"
var delay=20;
var nextm=0;
var msg=new Array('satu','dua','tiga','empat');
function mulai()
{
ticker(msg[0], 0, 1);
}

function ticker(text, pos, dir)
{
var out='['+text.substring(0, pos)+']';
tick.innerHTML=out;
pos+=dir;
if(pos>text.length)
setTimeout('ticker("'+text+'",'+pos+','+(-dir)+')', delay*10);
else
{
if(pos<0)
{
if(++nextm>=msg.length)
nextm=0;
text=msg[nextm];
dir=-dir;
}
setTimeout('ticker("'+text+'",'+pos+','+dir+')', delay);
}
}
/script
body bgcolor=ffffff onload="mulai()"
div id="tick" style="position: absolute; top: 10; left: 10;"/div
/body
/html

DHTML TRANSITION EFFECT

HTML
HEAD
SCRIPT language=JavaScript
var g_awal="a.bmp";
var g_akhir="b.bmp";
function transisi()
{
gambar.filters.item(0).Apply();
gambar.src=g_akhir;
g_akhir=g_awal;
g_awal=gambar.src;
gambar.filters.item(0).Play();
}
/SCRIPT
/HEAD
BODY
IMG id=gambar style="FILTER: revealTrans(Duration=2)" src="a.bmp"
br
INPUT onclick="transisi()" type=button value="Mulai"
/BODY
/HTML

Rabu, 10 Februari 2010

READING TEXT FILE

Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("abc.txt", ForReading)

strContents = objFile.ReadAll
objFile.Close

i = False

Do Until i = True
intLength = Len(strContents)
If intLength < 28 Then
Exit Do
End If
strLines = strLines & Left(strContents, 28) & vbCrLf
strContents = Right(strContents, intLength - 28)
Loop

Wscript.Echo strLines

Scripting.Dictionary

Dim a, d, i 'Create some variables
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens" 'Add some keys and items
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
a = d.Items 'Get the items
For i = 0 To d.Count -1 'Iterate the array
msgbox a(i) 'Print item
Next

MERLIN

strAgentName="Merlin"
strAgentPath="C:\WINDOWS\msagent\chars\" & strAgentName & ".acs"
Set objAgent=CreateObject("Agent.Control.2")

objAgent.Connected=TRUE
objAgent.Characters.Load strAgentName, strAgentPath
Set objCharacter=objAgent.Characters.Character(strAgentName)

objCharacter.Show
objCharacter.Play "GetAttention"
objCharacter.Play "Greet"
objCharacter.Speak "Hello Dudi, Gimana Kabarnya"
objCharacter.Play "LookDown"
objCharacter.Speak "Jalan-jalan dulu di desktop, ah"
objCharacter.MoveTo 500, 400, 600
objCharacter.Play "DoMagic2"
objCharacter.Speak "Kenalin Namaku Merlin si penyihir"
objCharacter.Play "Decline"
objCharacter.Speak "Jalan jalan lagi ah"
objCharacter.MoveTo 400, 30, 3000
objCharacter.Play "DoMagic1"
objCharacter.Speak "Kamu belum tau aku bisa gini"
objCharacter.Play "Announce"
objCharacter.MoveTo 400, 300, 0
objCharacter.Speak "Makasih Dudi aku bisa muncul di desktop"
objCharacter.Play "Surprised"
objCharacter.Play "GetAttention"
objCharacter.MoveTo 500, 300
objCharacter.Play "Read"
objCharacter.Play "GestureRight"
objCharacter.Play "GestureDown"
objCharacter.MoveTo 40, 40, 0
objCharacter.Play "Search"
objCharacter.Play "Explain"
objCharacter.Play "Congratulate"
objCharacter.MoveTo 200, 400
objCharacter.Play "Pleased"
objCharacter.Play "Congratulate_2"
objCharacter.MoveTo 300, 300
objCharacter.Play "Think"
objCharacter.Play "LookDown"
objCharacter.Play "GestureDown"
objCharacter.GestureAt 700, 0
objCharacter.MoveTo 700,400
objCharacter.Play "Idle1_2"
objCharacter.Play "Idle1_3"
objCharacter.Play "Process"
objCharacter.MoveTo 600,400
objCharacter.Play "Uncertain"
objCharacter.Play "Write"
objCharacter.Play "Idle2_1"
objCharacter.Play "Idle2_2"
objCharacter.Play "WriteReturn"
objCharacter.Play "Suggest"
objCharacter.Play "Sad"
objCharacter.Play "DontRecognize"
objCharacter.Speak "Pulang dulu ya"
objCharacter.Play "Wave"
objCharacter.Hide

Do While objCharacter.Visible=TRUE
WScript.Sleep 250
Loop

ANIMASI TEKS BERJALAN PADA MICROSOFT EXCEL

Private Sub DAControl_Start()
Set m = DAControl.MeterLibrary

'// Set of number behaviors
Set zero = m.DANumber(0)
Set half = m.DANumber(0.5)
Set one = m.DANumber(1)
Set two = m.DANumber(2)

Set oscillatingNumber = m.Sin(m.LocalTime)

'// Create a time varying color
Set txtCol = m.ColorHslAnim(m.Abs(oscillatingNumber), m.DANumber(0.5), m.DANumber(0.5))

Set FontStyle = m.Font("Verdana", -24, txtCol)

Set textImg = m.StringImage("SELAMAT DATANG DI PEMROGRAMAN 2D & 3D GRAFIS MICROSOFT DIRECT X", FontStyle)

'// Get the height and width of the text.
Set scrollingTextBounds = textImg.BoundingBox

Set scrollingTextLength = m.Sub(scrollingTextBounds.Max.X, scrollingTextBounds.Min.X)
Set scrollingTextWidth = m.Sub(scrollingTextBounds.Max.Y, scrollingTextBounds.Min.Y)

'// Get the control width and hegiht.
Set icontrolWidth = m.Mul(m.DANumber(300), m.Pixel)
Set controlHeight = m.Mul(m.DANumber(40), m.Pixel)


'// first we move the text off the right hand side of the control
'// remember that text comes up centered, so we first move the left portion to the right of center
'// and then move by half the width of the control to the right. Also center the text vertically
'// across the control

Set horizontalOffset = m.Add(m.Neg(scrollingTextBounds.Min.X), m.Div(icontrolWidth, m.DANumber(2)))
Set verticalOffset = m.Neg(m.Div(scrollingTextWidth, m.DANumber(4)))

Set scrollingTextImage = textImg.Transform(m.Translate2Anim(horizontalOffset, verticalOffset))

'// Number of scrolling steps
Set scrollingSteps = m.DANumber(400)

'// how fast to scroll
Set scrollingSpeed = m.Mod(m.Mul(m.LocalTime, m.DANumber(9)), scrollingSteps)

'// we need to scroll the width of the control plus the length of the string
Set iScrollWidth = m.Add(icontrolWidth, scrollingTextLength)

'// this defines the translation
Set scrollingRate = m.Mul(m.Neg(scrollingSpeed), m.Div(iScrollWidth, scrollingSteps))

Set scrollingTextTranslation = m.Translate2Anim(scrollingRate, zero)

Set scrollingTextImage = scrollingTextImage.Transform(scrollingTextTranslation)


DAControl.TimerSource = 1

'// set the image to be displayed
DAControl.Image = m.Overlay(scrollingTextImage, m.SolidColorImage(m.Black))

DAControl.Sound = m.Silence

'// start the animation
DAControl.Start
End Sub

SQL STATEMENT IN VBA MICROSOFT ACCESS

SQL PADA VISUAL BASIC FOR APPLICATION UNTUK MICROSOFT ACCESS
1. DOUBLE KLIK FORM
2. BUAT TOMBOL PADA FORM
3. KLIK KANAN PADA FORM TERSEBUT
4. KLIK CODE BUILDER
5. KEMUDIAN COPY KODE DI BAWAH INI
6. YANG PERTAMA ADALAH CREATE TABLE PEGAWAI YAITU UNTUK MEMBUAT TABEL PADA ACCESS
7. KE DUA MENGISI TABEL DENGAN INSERT INTO
8. DST COBA SENDIRI


Option Compare Database

Private Sub Command0_Click()
Dim dbs As Database
Set dbs = OpenDatabase("db11.mdb")
dbs.Execute "CREATE TABLE PEGAWAI " & "(NAMA CHAR, GAJI CHAR);"
dbs.Close
End Sub

Option Compare Database

Private Sub Command1_Click()
Dim dbs As Database
Set dbs = OpenDatabase("db11.mdb")
dbs.Execute "INSERT INTO PEGAWAI " & "(NAMA,GAJI) VALUES " & "('Harry', '4000000');"
dbs.Close
End Sub


Private Sub Command2_Click()
Dim dbs As Database
Set dbs = OpenDatabase("db11.mdb")
dbs.Execute "ALTER TABLE PEGAWAI " & "ADD COLUMN PAJAK CURRENCY;"
dbs.Close
End Sub

Option Compare Database

Private Sub Command0_Click()
Dim dbs As Database
Set dbs = OpenDatabase("db11.mdb")
dbs.Execute "ALTER TABLE PEGAWAI " & "DROP COLUMN PAJAK;"
dbs.Close
End Sub


Option Compare Database

Private Sub Command0_Click()
Dim dbs As Database
Set dbs = OpenDatabase("db11.mdb")
dbs.Execute "DELETE * FROM " & "PEGAWAI WHERE NAMA = 'Harry';"
dbs.Close
End Sub

MEMBUAT OBJEK BERPUTAR MENGELILINGI GARIS LINGKARAN

HAPUS DULU TAG BR / SEBELUM MENGGUNAKAN KODE DI BAWAH INI


radio button array

HAPUS KODE BR/ SEBELUM MENGGUNAKAN KODE DI BAWAH INI


Minggu, 07 Februari 2010

BELAJAR ARRAY 4

html>
head>
script language="javascript">
var jeda=20;
var lanjut=0;
var pesan=new Array('fitri','karmin','gupron','aan','andi','asep');

function mulai()
{
animasi(pesan[0],0,1);
}

function animasi(teks,posisi,arah)
{
var tampil='['+teks.substring(0,posisi)+']';
tulisan.innerHTML=tampil;
posisi+=arah;
if(posisi>teks.length)
setTimeout('animasi("'+teks+'",'+posisi+','+(-arah)+')',jeda*10);
else
{
if(posisi<0)
{
if(++lanjut>=pesan.length)
lanjut=0;
teks=pesan[lanjut];
arah=-arah;
}
setTimeout('animasi("'+teks+'",'+posisi+','+arah+')',jeda);
}
}
/script>
body>
button onclick="mulai()">mulai/button>
br>
h1>div id="tulisan">/div>/h1>
/body>
/html>

ARRAY 3

html>
head>
title>Window Without a Title Bar/title>
HTA:APPLICATION
ID="objNoTitleBar"
APPLICATIONNAME="Window Without a Title Bar"
SCROLL="no"
SINGLEINSTANCE="yes"
CAPTION="no"
border="no"
icon="dg.ico"
>
/head>
SCRIPT LANGUAGE="VBScript">

Sub CloseWindow
self.close
End Sub

/SCRIPT>

body onkeypress='CloseWindow'>
script language="javascript">
function ar()
{
nama=new Array("Abdul", "Karmin", "Jajang", "Pardiansyah", "Indri", "Arif", "Arum", "Windi")
nama.sort()
for(c=0; c<8;c++)
{
document.write("h2>" + nama[c] + "h2>" + "br>")
}
}
/script>
button onclick="ar()">klik/button>
/body>
/html>

BELAJAR ARRAY 2

cOPY KODE DI bawah ini! Paste pada notepad. Save as (tes2.hta)
html>
body>
script>

function jawaban()
{
var hasil=new Array("90.salah","22.salah","64.benar","72.salah")
for(var i=0;i{
if(form1.radio1(i).checked)
{
window.alert(hasil[i]);
}
}
}
/script>

form name=form1>
8x8=...br>
input type=radio name=radio1>90br>
input type=radio name=radio1>22br>
input type=radio name=radio1>64br>
input type=radio name=radio1>72br>
button onclick="jawaban()">jawab/button>
/form>
/body>
/html>

BELAJAR ARRAY 1

cOPY KODE DI BAWAH INI Pada NoTEPAD. Save as (tes.hta). Sengaja tanda < dihapus... ketik saja sendiri lagi oleh Anda.
html>
head>
title>Window Without a Title Bar
HTA:APPLICATION
ID="objNoTitleBar"
APPLICATIONNAME="Window Without a Title Bar"
SCROLL="no"
SINGLEINSTANCE="yes"
CAPTION="no"
border="no"
icon="dg.ico"
>
/head>
SCRIPT LANGUAGE="VBScript">

Sub CloseWindow
self.close
End Sub

/SCRIPT>

body onkeypress='CloseWindow'>
script language="javascript">
function ar()
{
nama=new Array("abdul", "Karmin", "Jajang", "Pardiansyah", "Indri", "Arif", "arum", "windi")
for(c=0; c<7;c++)
{
document.write("h2>" + nama[c] + "h2>" + "br>")
}
}
/script>
button onclick="ar()">klik/button>
/body>
/html>

WEB PART Menu pada halaman web

PUBLIC:COMPONENT
PUBLIC:ATTACH EVENT="oncontentready" ONEVENT="fnInit()" />
PUBLIC:ATTACH EVENT="onmousedown" ONEVENT="fnGrab()" />
PUBLIC:ATTACH EVENT="ondragstart" ONEVENT="fnCancel()" />


SCRIPT LANGUAGE="JScript">

window.onerror = function fnNoOp() {return true; };

// globals
var m_iSpacingTop = 10;
var m_iSpaceBetween = 5;
var m_iTop = 15;
var bUserData = false;
var bVisited = false;

//---- Setting the id for user data store ---------

if ("undefined" == typeof(sContentID) || sContentID == "" )
{
sContentID = fnFormatFileName(window.location.href) ;
}
else
{
sContentID = sContentID;
}


//////////////////////////////////////////////////////////////////////////////
////// Initializing the top and height values for the parts //////////////////
function fnInit()
{
var oStateArray = fnGetUserDataList();
element.parts = fnGetPartArray();
var oDragWindow = window.document.createElement( "SPAN" );
oDragWindow.className = "clsDragWindow";
element.dragwindow = oDragWindow;
element.rows(0).cells(0).insertAdjacentElement( "beforeEnd" , oDragWindow );
fnReOrder( oStateArray );

}


function fnReOrder( oStateArray )
{
if( null == oStateArray ) return;
var bDirty = false;
var oLastPart = null;
for( var i = 0; i < oStateArray.length; i++ )
{
if( bDirty || element.parts[i].id != oStateArray[i][0] )
{
bDirty = true;
var oPart = fnGetPartById( oStateArray[i][0] );
if( i != 0 ) oLastPart = element.parts[i-1];
if( null != oLastPart )
{
oLastPart.insertAdjacentElement( "afterEnd" , oPart );
}
else
{
element.rows(0).cells(0).insertAdjacentElement( "afterBegin" , oPart );
}
oLastPart = oPart;
}
if( !bDirty )
{
try{bClosed = ( oStateArray[i][1] == "close" );}
catch(e){bClosed = false;}
element.parts[i].state = bClosed ? "close" : "open";
if( bClosed ) fnShowHideContent( element.parts[i] , !bClosed );
}
}
if( bDirty )
{
element.parts = fnGetPartArray();
for( var i = 0; i < element.parts.length; i++ )
{
try{bClosed = oStateArray[i][1] == "close"}
catch(e){bClosed = false;}
element.parts[i].state = bClosed ? "close" : "open";
if( bClosed ) fnShowHideContent( element.parts[i] , !bClosed );
}
}
}

function fnGetPartById( sId )
{
return element.all( sId );
}

function fnGetPartArray()
{
var oParts = element.all.tags( "TABLE" );
var oReturn = new Array();
for( var i = 0; i < oParts.length; i++ )
{
if( oParts[i].className == "clsPart" )
{
oReturn[oReturn.length] = oParts[i];
}
}
return oReturn;
}

function fnGetMinMaxImg( oPart )
{
var oImgs = oPart.all.tags( "img" );
for( var i = 0; i < oImgs.length; i++ )
{
if( oImgs[i].className == "clsMinimize" ) return oImgs[i];
}
}

/////////////////////////////////////////////////////////////////////////////////////
/////// On mouse down grab the element and capture its ondrag event /////////////////

function fnGrab()
{
var oEl = event.srcElement;
var bCollapsed

if( oEl.className.indexOf( "clsPartRight" ) != -1 )
{
var oTableRow2 = oEl.parentElement.parentElement.parentElement.rows[1];
var bCollapsed = ( (oTableRow2.style.display == "none") ? true : false);
fnShowHideContent(oEl,bCollapsed);
}
else if( oEl.className == "clsPartHead")
{

if("img" == oEl.tagName.toLowerCase())
{
oEl.onDragStart = fnCancel;
oEl = oEl.parentElement;
}

m_iTop = event.clientY;
oEl = fnGetPart( oEl );
element.offsetY = event.offsetY + element.offsetTop;
element.offsetX = event.offsetX + element.offsetLeft + 15;
element.current = oEl;
fnShowDragWindow( oEl );

window.document.attachEvent( "onmousemove" , fnMove );
window.document.attachEvent( "onscroll" , fnMove );
window.document.attachEvent( "onmousemove" , fnCheckState );
window.document.attachEvent( "onmouseup" , fnRelease );
window.document.attachEvent( "onselectstart", fnSelect );
}

}

function fnShowDragWindow( oEl )
{
element.dragwindow.style.height = oEl.offsetHeight - 3;
element.dragwindow.style.top = oEl.offsetTop + 3;
element.dragwindow.style.left = oEl.offsetLeft;
element.dragwindow.style.width = oEl.offsetWidth;
element.dragwindow.zIndex = 100;
element.dragwindow.style.display = "block";
}

function fnHideDragWindow()
{
element.dragwindow.style.display = "none";
element.dragwindow.style.height = "";
element.dragwindow.style.top = "";
element.dragwindow.style.left = "";
element.dragwindow.style.width = "";
element.dragwindow.zIndex = "";
}

function fnGetPart( oEl )
{
while( null != oEl && oEl.className != "clsPart" )
{
oEl = oEl.parentElement;
}
return oEl;
}

////////////////////////////////////////////////////////////////////////////////
///////// function to set the top style for the object /////////////////////////
function fnMove()
{
if (event.button != 1)
{
fnRelease();
return;
}

element.dragwindow.style.top = event.clientY - element.offsetY + window.document.body.scrollTop;
element.dragwindow.style.left = event.clientX - element.offsetX + window.document.body.scrollLeft;
if (event.clientY > window.document.body.clientHeight - 10 )
{
window.scrollBy(0, 10);
}
else if (event.clientY < 10)
{
window.scrollBy(event.clientX, -10);
}

}

//////////////////////////////////////////////////////////////////////////////////////
////// on mouse up, detach the events and reposition the webparts ////////////////////

function fnRelease()
{

var oEl = event.srcElement;

//fnSaveState();

window.document.detachEvent( "onmousemove" , fnMove );
window.document.detachEvent( "onscroll" , fnMove );
window.document.detachEvent( "onmousemove" , fnCheckState );
window.document.detachEvent( "onmouseup" , fnRelease );
window.document.detachEvent( "onselectstart", fnSelect );


if( "object" == typeof(element.current) );
{

if (null != element.current )
{
fnSetPosition( element.dragwindow );
//element.current.style.position = "relative";
//element.current.style.top = "";
//element.current.style.zIndex = -1;
element.current = null;
fnHideDragWindow();
}
else
{
return false;
}

}

}

////////////////////////////////////////////////////////////////////////////////////////
/////// function to reorder the webparts after dragging ////////////////////////////////
function fnSetPosition( oEl )
{
var oPrevEl = fnGetPrevEl( oEl );
if( null != oPrevEl )
{
oPrevEl.insertAdjacentElement( "afterEnd" , element.current );
}
else
{
element.rows(0).cells(0).insertAdjacentElement( "afterBegin" , element.current );
}
element.parts = fnGetPartArray();
fnSaveState();
}

function fnGetPrevEl( oEl )
{
var oReturn = null;
for( var i = 0; i < element.parts.length; i++ )
{
if( element.parts[i].offsetTop < oEl.offsetTop ) oReturn = element.parts[i];
}
return oReturn;
}

//////////////////////////////////////////////////////////////////////////////
//////// function to strip out non-alpha numeric chars from input string /////

function fnFormatFileName(sFileName)
{
if( "string" == typeof( sFileName ) )
{
sFileName = sFileName.replace( /[\W]/gi , "" );
return sFileName;
}
}

//////////////////////////////////////////////////////////////////////////////
//////// This is a innerloop for function fnCheckWebPartIDs //////////////////

function fnInternalLoop(i,strElements)
{
for(j=0;j {
if ( parentElement.children[i].id == strElements[j].split("=")[0] )
{
bUserData = true;
return;
}
else
{
bUserData = false;
}
}
}


//////////////////////////////////////////////////////////////////////////////
////// function to get user data content /////////////////////////////////////
function fnGetUserDataList()
{

var oUserData = window.document.all("oLayout");
var oReturn = null;
try
{
oUserData.load(sContentID);
}
catch(e)
{
oUserData = null;
}

if (null != oUserData && oUserData != "" && "undefined" != oUserData )
{
var sUserData = oUserData.getAttribute( "userdata" );
if( null != sUserData )
{
oReturn = fnParseUserData( oUserData.getAttribute( "userdata" ) );
}
}
return oReturn;

}

function fnParseUserData( sUserData )
{
var oTmpArray = sUserData.split( ";" );
var oReturnArray = new Array( oTmpArray.length - 1 );
for( var i = 0; i < oTmpArray.length -1; i++ )
{
oReturnArray[i] = oTmpArray[i].split( "=" );
}
return oReturnArray;
}







/////////////////////////////////////////////////////////////////////////////////////
////// To expand and collapse the web part //////////////////////////////////////////

function fnShowHideContent(oEl,bCollapsed)
{
var oPart = fnGetPart( oEl );
var oTopBar = oPart.rows[0];
var oContent = oPart.rows[1];

var idName = oEl.parentElement.parentElement.parentElement.tagName;

var oTab1 = oPart.cells[0];
var oTab2 = oPart.cells[1];
var oTab3 = oPart.cells[2];
var oSwapImg = oTab1.children[0];

if ( bCollapsed )
{

// -- if the table row is already collapsed, expand it & swap the images --
oContent.style.display = "inline";
//oEl.src = "/library/shared/webparts/images/chevronUp.gif";

oTab1.style.backgroundColor="#6699cc";
oTab1.style.borderBottom='1px solid #6699cc';
oTab2.style.backgroundColor="#6699cc";
oTab2.style.borderTop='1px solid #6699cc';
oTab2.style.borderBottom='1px solid #6699cc';
oTab2.parentElement.cells[1].children[0].style.backgroundColor= "#6699cc";
oTab2.parentElement.cells[1].children[0].style.color = "#ffffff"
oTab3.style.backgroundColor="#6699cc";
oTab3.style.borderBottom='1px solid #6699cc';
oTab3.className = "clsPartRight";
oSwapImg.src = "/library/shared/webparts/images/gripBlue.gif";
//----- writing back the state info to the array -------
var id = oEl.parentElement.parentElement.parentElement.parentElement.id;
oPart.state = "open";
}
else
{
// expand the table row & swapping the images
oContent.style.display = "none";
//oEl.src = "/library/shared/webparts/images/chevronDown.gif";

oTab1.style.backgroundColor="#cccccc";
oTab1.style.borderBottom='1px solid #aaaaaa';

oTab2.style.backgroundColor="#cccccc";
oTab2.style.borderTop='1px solid #aaaaaa';
oTab2.style.borderBottom='1px solid #aaaaaa';
oTab2.parentElement.cells[1].children[0].style.backgroundColor= "#cccccc";
oTab2.parentElement.cells[1].children[0].style.color = "#003399"

oTab3.style.backgroundColor="#cccccc";
oTab3.style.borderBottom='1px solid #aaaaaa';
oTab3.className = "clsPartRightHidden";


oSwapImg.src = "/library/shared/webparts/images/gripGray.gif";
oPart.state = "close";

}

fnSaveState();

}

///////////////////////////////////////////////////////////////////////////////////
//////// function to cancel the dragstart event ///////////////////////////////////
function fnCancel()
{
if( event.srcElement.className == "clsPartHead" )
{
window.event.returnValue = false;
}
}



//////////////////////////////////////////////////////////////////////////////////////
//////// To save the order and state of web parts ////////////////////////////////////
function fnSaveState()
{
var oUserData = window.document.all["oLayout"];
var sUserData = "";
var sState = "";

for (i=0;i {
sState = "undefined" == String( element.parts[i].state ) ? "open" : element.parts[i].state;
sUserData += (element.parts[i].id + "=" + sState + ";");
}

oUserData.setAttribute("userdata",sUserData);
oUserData.save(sContentID);
}




////////////////////////////////////////////////////////////////////////////////////////
///////// function to check the state and release the element ////////////////
///////// if a mouse button is not depressed ////////////////

function fnCheckState()
{
if( event.button != 1 ) fnRelease();
}

///////////////////////////////////////////////////////////////////////////////
///////// function to return false ////////////////////////////////////////////
function fnSelect()
{
return false;
}


/SCRIPT>
/PUBLIC:COMPONENT>

XML Menu

Menu seperti START MENU Pada WINDOWS XP (Kode di bawah ini membutuhkan file xml), dan dibuat oleh Microsoft Corp.
var mnpMenuTop = null;
var mnpMenuKill = null;
var mnpMenuPopup = null;
var mnpMenuUrl = null;
var mnpMenuParent = null;
var mnpMenuScrollTimer = null;
var mnpMenuShadows = new Array();
var mnpMenuDirSave = "LTR";
var mnpMenuCTSave = false;
var mnpMenuRenderStart = null;
var mnpMenuShadowsEnabled = true;

window.attachEvent("onload", mnpMenuInit);

function mnpMenuInit()
{
try
{
mnpMenuDirSave = mnpMenuDir();
mnpMenuCTSave = mnpMenuCT();
}
catch(e)
{
return;
}
mnpMenuTop = document.getElementById("mnpMenuTop");
mnpMenuUrl = mnpMenuTop.getAttribute("url");
mnpMenuParent = mnpMenuTop.getAttribute("parent");
mnpMenuAttach(mnpMenuTop);
}

function mnpPage(label, url, target, menu, linkID)
{
this.label = label;
this.url = url;
this.target = target;
this.menu = menu;
this.linkID = linkID;
}

function mnpLabel(label)
{
this.label = label;
}

function mnpMenuEnter()
{
if (mnpMenuKill)
{
window.clearTimeout(mnpMenuKill);
mnpMenuKill = null;
}
}

function mnpMenuLeave()
{
mnpMenuKill = window.setTimeout("mnpMenuKiller()", 200);
}

function mnpMenuKiller()
{
mnpKillMenu(mnpMenuTop.getAttribute("currentMenu"));
mnpMenuTop.removeAttribute("currentMenu");
}

function mnpMenuAttach(el)
{
el.attachEvent("onmouseenter", mnpMenuEnter);
el.attachEvent("onmouseleave", mnpMenuLeave);
var divs = el.getElementsByTagName("DIV");
var t = divs.length;
for (var i=0; i < t; i++)
{
var div = divs.item(i);
if (div.className == "mnpMenuRow")
{
div.attachEvent("onmouseenter", mnpMenuMouseover);
div.attachEvent("onmouseleave", mnpMenuMouseout);
div.attachEvent("onmousedown", mnpMenuMousedown);
div.attachEvent("onmouseup", mnpMenuMouseup);
div.setAttribute("save-background", div.style.background);
div.setAttribute("save-border", div.style.borderColor);
var a = div.getElementsByTagName("A");
if (a.length > 0)
{
var a0 = a[0];
if (a0.getAttribute("aoff"))
a0.outerHTML = a0.innerHTML;
else
{
div.setAttribute("status", a0.href);
div.attachEvent("onclick", mnpMenuClick);
}
}
if (div.getAttribute("menu"))
{
var imgs = div.getElementsByTagName("IMG");
if (imgs.length > 0)
{
var img = imgs[0];
img.style.visibility = "visible";
}
else
{
var x;
if (mnpMenuDirSave == "LTR")
x = (div.offsetWidth - 10) + "px";
else if (mnpMenuTop.contains(div))
x = "4px";
else
x = "6px";
var img = "";
div.insertAdjacentHTML("afterBegin", img);
}
}
}
}
}

function mnpMenuClick()
{
var div = window.event.srcElement;
var a = div.getElementsByTagName("A");
if (a.length == 0) return;
if (window.event.shiftKey)
{
var target = a[0].target;
a[0].target = "_new";
a[0].click();
a[0].target = target;
}
else
a[0].click();
}

function mnpKillMenu(id)
{
if (id == null) return;
var menu = document.getElementById(id);
var current = menu.getAttribute("currentMenu");
if (current)
{
mnpKillMenu(current);
menu.removeAttribute("currentMenu");
}
var temp = mnpMenuShadows[id];
if (temp)
{
var i;
var tempLength = temp.length;
for (i=0; i if (temp[i])
document.body.removeChild(temp[i]);
mnpMenuShadows[id] = null;
}
var parent = document.getElementById(menu.getAttribute("parentMenu"));
var rows = parent.getElementsByTagName("DIV");
var rLength = rows.length;
for (var i=0; i {
var row = rows.item(i);
var m = row.getAttribute("menu");
if (m == id)
{
row.style.background = row.getAttribute("save-background");
row.style.borderColor = row.getAttribute("save-border");
}
}
show_elements("SELECT", menu);
show_elements("OBJECT", menu);
menu.style.display = "none";
}

function mnpMenuOpen(id, parentId, x, y)
{
var parent;
try
{
parent = document.getElementById(parentId);
}
catch(e)
{
return;
}
var current = parent.getAttribute("currentMenu");
if (id == current) return;
mnpKillMenu(current);
if (id)
parent.setAttribute("currentMenu", id);
else
{
parent.removeAttribute("currentMenu");
return;
}

var div = document.getElementById(id);
if (div == null)
{
var menu = eval("new " + id + "()");
var html = "
";
html += "";
html += "
";
var isThisPage = false;
var mLength = menu.items.length;
for (var i=0; i {
var item = menu.items[i];
var url = item.url;
if (url == mnpMenuUrl)
{
isThisPage = true;
break;
}
}
for (var i=0; i {
var item = menu.items[i];
var label = item.label;
var re = /'/g;
var url = item.url;
if (url)
url = url.replace(re, "'");
var target = item.target;
var submenu = item.menu;
var linkID = item.linkID;
html += " if (submenu)
html += " menu='" + submenu + "'";
if (url)
{
html += " class='mnpMenuRow'";
if (url == mnpMenuUrl)
html += " style='border-color: #999999; background: white; cursor: default";
else if (!isThisPage && (url == mnpMenuParent))
html += " style='border-color: #999999; background: #F1F1F1";
else
html += " style='border-color: #F1F1F1; background: #F1F1F1";
if (mnpMenuDirSave == "LTR")
html += "; padding-left: 11px";
else
html += "; padding-right: 11px";
html += "'";
}
else
html += " class='mnpMenuLabel'";
html += ">";
if (url && (url != mnpMenuUrl))
{
var targetAttr = target == "" ? "" : " target='" + target + "'";
if (mnpMenuCTSave)
html += "" + label + "";
else
html += "" + label + "";
}
else
html += "" + label + "";
html += "
";
}
html += "
";
html += "";
html += "
";
document.body.insertAdjacentHTML("afterBegin", html);
var div = document.getElementById(id);
var sa = div.childNodes.item(1);
var max = 0;
var saLength = sa.childNodes.length;
for (var i=0; i {
var it = sa.childNodes.item(i).childNodes.item(0);
var w = it.offsetWidth;
if (w > max) max = w;
}
max += 34;
if (max < 100) max = 100;
else if (max > 410) max = 410;
div.style.width = max + "px";
for (var i=0; i {
var it = sa.childNodes.item(i);
if (it.className == "mnpMenuRow")
it.style.width = (max - 6) + "px";
}
mnpMenuAttach(div);
div.setAttribute("parentMenu", parentId);
}
else
{
div.style.display = "";
}
var bodyHeight = document.body.clientHeight;
var bodyTop = document.body.scrollTop;
var bodyWidth = document.body.clientWidth;
var bodyLeft = document.body.scrollLeft;
var up = div.children.item(0);
var box = up.nextSibling;
var down = box.nextSibling;
up.style.display = "none";
down.style.display = "none";
box.style.height = "";
if (div.offsetHeight > bodyHeight)
{
up.style.display = "";
up.childNodes.item(0).src = "/library/mnp/2/gif/up_disabled.gif";
down.style.display = "";
down.childNodes.item(0).src = "/library/mnp/2/gif/down_enabled.gif";
box.style.height = (bodyHeight - up.offsetHeight - down.offsetHeight - 6) + "px";
}
var bodyBottom = bodyTop + bodyHeight;
if (y + div.offsetHeight > bodyBottom)
{
y -= div.offsetHeight - 25;
if (y < bodyTop)
y = bodyTop + (bodyHeight - div.offsetHeight) / 2;
}
if (mnpMenuDirSave == "RTL")
x -= div.offsetWidth;
div.style.left = x + "px";
div.style.top = y + "px";
div.style.zIndex = parent.style.zIndex + 10;
if (div.offsetLeft + div.offsetWidth > bodyWidth + bodyLeft)
document.body.scrollLeft = div.offsetLeft + div.offsetWidth - bodyWidth;
hide_elements("SELECT", div);
hide_elements("OBJECT", div);
if (mnpMenuShadowsEnabled)
{
mnpMenuShadows[id] = mnpMenuShadow(div, "#666666", 4, div.offsetWidth, div.offsetHeight);
mnpMenuRenderStart = mnpMenuTime();
window.setTimeout("mnpMeasureRenderTime()", 1);
}
}

function mnpMeasureRenderTime()
{
var msec = mnpMenuTime() - mnpMenuRenderStart;
if (msec > 100)
{
// client is slow or document is huge, so disable shadows
mnpMenuShadowsEnabled = false;
}
}

function mnpMenuPt(el)
{
this.left = 0;
this.top = 0;
while (el)
{
this.left += el.offsetLeft;
this.top += el.offsetTop;
el = el.offsetParent;
}
}

function mnpMenuMouseover()
{
var div = window.event.srcElement;
var status = div.getAttribute("status");
if (status) window.status = status;
div.style.background = "#CCCCCC";
div.style.borderColor = "#999999";
var pt = new mnpMenuPt(div);
var x;
if (mnpMenuDirSave == "LTR")
x = pt.left + div.offsetWidth - 1;
else
x = pt.left + 2;
var y = pt.top - 3;
var menu = div.getAttribute("menu");
if (menu)
menu = "'" + menu + "'";
else
menu = "null";
if (mnpMenuPopup)
window.clearTimeout(mnpMenuPopup);
var parent = div.parentElement.parentElement;
mnpMenuPopup = window.setTimeout("mnpMenuOpen(" + menu + ", '" + parent.id + "', " + x + ", " + y + ")", 200);
}

function mnpMenuMouseout()
{
var div = window.event.srcElement;
window.status = "";
var menu = div.getAttribute("menu");
if (menu != null && menu == div.parentElement.parentElement.getAttribute("currentMenu"))
{
div.style.background = "#CCCCCC";
div.style.borderColor = "#CCCCCC";
}
else
{
div.style.background = div.getAttribute("save-background");
div.style.borderColor = div.getAttribute("save-border");
}
if (mnpMenuPopup)
{
window.clearTimeout(mnpMenuPopup);
mnpMenuPopup = null;
}
}

function mnpMenuMousedown()
{
var div = window.event.srcElement;
if (div.tagName != "DIV") div = div.parentElement;
div.style.background = "#999999";
}

function mnpMenuMouseup()
{
var div = window.event.srcElement;
if (div.tagName != "DIV") div = div.parentElement;
div.style.background = div.getAttribute("save-background");
}

function mnpMenuTime()
{
var time = new Date();
return time.valueOf();
}

function mnpStartScroll(dy)
{
var src = window.event.srcElement;
src.style.background = "#CCCCCC";
src.style.borderColor = "#999999";
var div = src.parentElement;
div.setAttribute("scrollTime0", mnpMenuTime());
div.setAttribute("scrollTop0", div.childNodes.item(1).scrollTop);
mnpMenuScrollTimer = window.setInterval("mnpMenuScroll('" + div.id + "', " + dy + ")", 35);
}

function mnpStopScroll()
{
var src = window.event.srcElement;
src.style.background = "#F1F1F1";
src.style.borderColor = "#F1F1F1";
if (mnpMenuScrollTimer)
window.clearInterval(mnpMenuScrollTimer);
mnpMenuScrollTimer = null;
}

function mnpMenuScroll(id, dy)
{
var div = document.getElementById(id);
var current = div.getAttribute("currentMenu");
if (current)
{
mnpKillMenu(current);
div.removeAttribute("currentMenu");
}
var box = div.childNodes.item(1);
var y = div.getAttribute("scrollTop0") + Math.round((mnpMenuTime() - div.getAttribute("scrollTime0")) * 0.150) * dy
box.scrollTop = y;
if (y != box.scrollTop)
{
window.clearInterval(mnpMenuScrollTimer);
mnpMenuScrollTimer = null;
if (box.scrollTop == 0)
div.childNodes.item(0).childNodes.item(0).src = "/library/mnp/2/gif/up_disabled.gif";
else
div.childNodes.item(2).childNodes.item(0).src = "/library/mnp/2/gif/down_disabled.gif";
}
else if (dy < 0)
div.childNodes.item(2).childNodes.item(0).src = "/library/mnp/2/gif/down_enabled.gif";
else
div.childNodes.item(0).childNodes.item(0).src = "/library/mnp/2/gif/up_enabled.gif";
}

function mnpMenuShadow(el, color, size, width, height)
{
var temp = new Array();
var i;
for (i=size; i>0; i--)
{
var rect = document.createElement('div');
var rs = rect.style
rs.position = 'absolute';
rs.left = (el.style.posLeft + i) + 'px';
rs.top = (el.style.posTop + i) + 'px';
rs.width = width + 'px';
rs.height = height + 'px';
rs.zIndex = el.style.zIndex - i;
rs.backgroundColor = color;
var opacity = 1 - i / (i + 1);
rs.filter = 'alpha(opacity=' + (100 * opacity) + ')';
document.body.appendChild(rect);
temp[i] = rect;
}
return temp;
}

function hide_elements(tagName, menu)
{
windowed_element_visibility(tagName, -1, menu)
}

function show_elements(tagName, menu)
{
windowed_element_visibility(tagName, +1, menu)
}

function windowed_element_visibility(tagName, change, menu)
{
var els = document.getElementsByTagName(tagName)
var i
var rect = new element_rect(menu)
var elsLength = els.length;
for (i=0; i < elsLength; i++)
{
var el = els.item(i)
if (elements_overlap(el, rect))
{
if (el.visLevel)
el.visLevel += change
else
el.visLevel = change
if (el.visLevel == -1 && change == -1)
{
el.visibilitySave = el.style.visibility;
el.style.visibility = "hidden";
}
else if (el.visLevel == 0 && change == +1)
{
el.style.visibility = el.visibilitySave;
}
}
}
}

function element_rect(el)
{
var left = 0
var top = 0
this.width = el.offsetWidth
this.height = el.offsetHeight
while (el)
{
left += el.offsetLeft
top += el.offsetTop
el = el.offsetParent
}
this.left = left;
this.top = top;
}

function elements_overlap(el, rect)
{
var r = new element_rect(el);
return ((r.left < rect.left + rect.width) && (r.left + r.width > rect.left) && (r.top < rect.top + rect.height) && (r.top + r.height > rect.top))
}
function jsTrim(s) {return s.replace(/(^\s+)|(\s+$)/g, "");}

function trackInfo(objLink)
{
if (!objLink) return;
if (!objLink.LinkID || !objLink.href) return;

// For Link Text - take innerText if available, or ALT if image

var LinkText;
//if (objLink.innerText) LinkText = objLink.innerText; // text link
//change made 7/19/2002 marmca
if (objLink.innerText && jsTrim(objLink.innerText)) LinkText = jsTrim(objLink.innerText);// text link
else if (objLink.alt) LinkText = objLink.alt; // image map link
else if (objLink.all(0)) LinkText = objLink.all(0).alt; // ... link

if (!LinkText || typeof(LinkText)=="undefined") return;
LinkText = jsTrim(LinkText);
if (LinkText=="") return;

// override link's HREF and send on its way
// Sometimes with slow browser reaction and rapid clicks this can get called more than once -
// ensure there's no repetition.
if (objLink.href.toString().indexOf("CTRedir") < 0)
objLink.href = "/isapi/CTRedir.asp?type=CT&source=MSDN&sPage="
+ ((objLink.LinkID)?escape(objLink.LinkID):"") + "|"
+ ((objLink.LinkArea)?escape(objLink.LinkArea):"") + "|"
+ ((objLink.LinkGroup)?escape(objLink.LinkGroup):"") + "|"
+ escape(LinkText)
+ "&tPage=" + objLink.href;
}
function trackSearch(objLink, objText)
{
if (!objLink) return true;
if (!objText) return true;
if (!objLink.LinkID || !objLink.href || !objText.value) return true;

// override link's HREF and send on its way
// For Link Text - take innerText if available, or ALT if image
// Sometimes with slow browser reaction and rapid clicks this can get called more than once -
// ensure there's no repetition.
if (objLink.href.toString().indexOf("CTRedir") < 0)
objLink.href = "/isapi/CTRedir.asp?type=CT&source=MSDN&sPage="
+ ((objLink.LinkID)?escape(objLink.LinkID):"") + "|"
+ ((objLink.LinkArea)?escape(objLink.LinkArea):"") + "|"
+ ((objLink.LinkGroup)?escape(objLink.LinkGroup):"") + "|"
+ "Search"
+ "&tPage=" + objLink.href + escape(objText.value).replace(/(\+)/g,"%2B");

objLink.click(); // click on the link to navigate - allows to have HTTP_REFERRER in CTRedir.asp

return false;
}

ADODB RECORDSET

Microsoft Office Applications

Welcome to Office Space, the column that offers tips and tricks for scripting Microsoft® Office applications. We’ll post new tips every Thursday; to see an archive of previous tips, visit the Office Space Archive. And if you have particular questions about Microsoft Office scripting, feel free to send them to scripter@microsoft.com. We can’t promise to answer all the questions we receive, but we’ll do our best.

Adding New Records to and Modifying Existing Records in a Microsoft Access Database
We’ve decided to let you in on a little secret: the Scripting Guys (unlike the rest of you, of course) have their good days and their bad days. Some days we come in excited and ready to work; other days (well, OK, most days) it’s a bit different. How are you, the readers of the Office Space column, supposed to know whether you’ve hit the Scripting Guys on a good day or a bad day? Well, here’s a hint: any time the Scripting Guys decide to “expand upon a previous column” then you know they’re taking the lazy way out and not even trying to think up something new.
So what does that have to do with this week’s column? Why, nothing, nothing at all…. Since you mentioned it, though, this week we’ve decided to expand upon a previous column, one in which we showed you how to connect to and read from a Microsoft Access database. Today we’re going to take the next logical step and show you how you can add records to an Access database. And then, just for the heck of it, we’ll take another step and show you how to modify existing records as well.
OK, we admit it: we didn’t exactly knock ourselves out trying to come up with a brand-new topic for this week’s column. But we’ll rationalize that by pointing out that, as useful as it is to be able to extract data from a database, it’s just as useful (if not more so) to be able to add data to that database. So while we are being a tad bit lazy at least we’re covering an important topic. Besides, you can simply think of this as the second part in a multi-part series: you don’t have to worry that we’re just taking the easy way out!
Seeing as how we are being a tad bit lazy, we won’t review any of basic concepts behind connecting to an Access database; if you need a brief refresher on that, take a look at last week’s column. Today we’re going to get right down to business: let’s show you how to add a new record to an existing database.
To begin with, we’re assuming you have an Access database named Inventory.mdb living in the C:\Scripts folder. We’re also assuming that this database has a table named GeneralProperties, and that the GeneralProperties table includes the following fields:
• ComputerName
• Department
• OperatingSystem
• Owner
Needless to say, if you don’t have such a database then none of these sample scripts will work. That doesn’t mean you can’t learn anything from them; you just won’t be able to run them and get them to do anything.
With that in mind, let’s take a look at a script that adds a new record to the database:
On Error Resume Next

Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source = c:\scripts\inventory.mdb"

objRecordSet.Open "SELECT * FROM GeneralProperties" , _
objConnection, adOpenStatic, adLockOptimistic

objRecordSet.AddNew
objRecordSet("ComputerName") = "atl-ws-99"
objRecordSet("Department") = "Human Resources"
objRecordSet("OperatingSystem") = "Microsoft Windows XP Professional"
objRecordSet("Owner") = "Ken Myer"
objRecordSet.Update

objRecordSet.Close
objConnection.Close
Note. We should note that this is not the only way to add a new record to a database. For example, SQL aficionados can also use an Insert Into query. We’re using the AddNew method simply because it’s easier; Insert Into queries can get extremely complicated, especially when you’re dealing with many fields, values stored in variables, and fields of different data types. In the lazy spirit of the day, we’re taking the easy way out.
The script starts out by connecting to the database C:\Scripts\Inventory.mdb. Like we said, we won’t discuss this in any detail, but that’s what these lines of code are for:
Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source = c:\scripts\inventory.mdb"
After making the connection we then use the Recordset object’s Open method to run a SQL query that retrieves all the records from the GeneralProperties table; that’s what we do here:
objRecordSet.Open "SELECT * FROM GeneralProperties" , _
objConnection, adOpenStatic, adLockOptimistic
What gives us is a recordset that we can add a new record to. And that’s what we do here:
objRecordSet.AddNew
objRecordSet("ComputerName") = "atl-ws-99"
objRecordSet("Department") = "Human Resources"
objRecordSet("OperatingSystem") = "Microsoft Windows XP Professional"
objRecordSet("Owner") = "Ken Myer"
objRecordSet.Update
We begin by calling the AddNew method; this sets up a blank template to work with, but doesn’t actually add anything to the database. (At the moment, all the work we’re doing is taking place solely in memory.) We then have a series of lines that assign values to the individual fields for this new record. (These fields, of course, are the fields found in the table GeneralProperties.) For example, this line sets the value of the ComputerName field to atl-ws-99:
objRecordSet("ComputerName") = "atl-ws-99"
Note that the value being assigned (atl-ws-99) is enclosed in double quote marks; that’s because ComputerName is a text field and is expecting to be assigned a string value. If a database field is numeric or Boolean (true/false) then you should not enclose the values in double quote marks:
objRecordSet("IsLaptop") = False
objRecordSet("NumberOfPrcoessors") = 2
But you knew that already, didn’t you?
Finally, we call the Update method, which actually writes the new record to the database:
objRecordSet.Update
Don’t forget that line of code: if you do, the recordset in memory will be updated to contain the new record, but the actual database will remain unchanged.
As you can see, adding a new record to an Access database is pretty easy. But what about modifying an existing record? For example, suppose we no sooner add the computer atl-ws-99 to the database then Ken Myer gets transferred from the Human Resources department to the Finance department. That means we now have to update the department field for that particular computer. How hard is that going to be?
Relax: it’s not going to be hard at all. Again, there are different ways to update records in a database, but for now we’ll focus on what we feel is the easiest way to update a record: you search for the record, update the appropriate field (or fields), and then call the Update method. In other words, a process that looks remarkably like this:
On Error Resume Next

Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source = c:\scripts\inventory.mdb"

objRecordSet.Open "SELECT * FROM GeneralProperties" , _
objConnection, adOpenStatic, adLockOptimistic

strCriteria = "ComputerName = 'atl-ws-99'"

objRecordSet.Find strCriteria
objRecordset.Fields.Item("Department") = "Finance"
objRecordset.Update

objRecordSet.Close
objConnection.Close
You probably already noticed that the first half of this script is identical to the script that adds a new record: we connect to the database, then use the Open method to return a recordset consisting of all the records in the GeneralProperties table. In fact, you won’t find any differences between the two scripts until we get to here:
strCriteria = "ComputerName = 'atl-ws-99'"
In this line of code we’re simply assigning the search criteria to a variable named strCriteria. We want to update the record for the computer named atl-ws-99; as you might expect, that becomes our search criteria, using the format FieldName = Value. Or, ComputerName = ‘atl-ws-99’.
After establishing the search criteria we call the Find method to locate that record in the recordset:
objRecordSet.Find strCriteria
We then use these two lines of code to update the Department field and then to save the changes:
objRecordset.Fields.Item("Department") = "Finance"
objRecordset.Update
Note the somewhat unusual syntax we use when referring to the Department field: objRecordset.Fields.Item(“Department”). Don’t worry too much about that; that’s just the way you have to do things. On the bright side, odd as it might look, at least it’s the same way we refer to fields when reading from a database (as we did last week).
Also, don’t overlook the Update method; once again a record will not be changed in the database until you call Update.
As we said, there are other ways we can modify existing records; however, those will have to wait for another day. Which day? Let’s put it this way: the next time we’re too lazy to think up a brand-new topic for this column, well, you can probably figure out for yourself what the topic will be.
Office Space: Tips and Tricks for Scripting Microsoft Office Applications

Welcome to Office Space, the column that offers tips and tricks for scripting Microsoft® Office applications. We’ll post new tips every Tuesday and Thursday; to see an archive of previous tips, visit the Office Space Archive. And if you have particular questions about Microsoft Office scripting, feel free to send them to scripter@microsoft.com. We can’t promise to answer all the questions we receive, but we’ll do our best.

Using ADO to Query an Excel Spreadsheet
A month or so ago CBS aired the final episode of the beloved sitcom Everybody Loves Raymond, a show that had been ranked No. 1 in viewership for hundreds of years, despite the fact that at least one of the Scripting Guys never caught even the briefest glimpse of the program. (Of course, cultural literacy isn’t exactly this Scripting Guy’s forte: he’s never seen American Idol or Survivor either, and has absolutely no idea which one is Nelly and which one is P Diddy.) With Raymond gone CBS has a void to fill in its schedule, but the rest of the world has an empty spot to fill as well: now who are we all supposed to love?
Personally, we’d like to nominate Microsoft Excel as a candidate to fill that void. After all, what’s not to love about Excel? Do you need a traditional spreadsheet program, something that can help you with budgets, accounting and other financial-type things? Excel can do that. Do you need to make charts and graphs? Excel can do that. Create an organizational chart? Calculate statistics? Excel has you covered; Excel can do anything.
Of course, some of you might not be convinced of that. “Excel can do anything?” you muse. “Well, how about this: can Excel function as a flat-file database? Can you use ADO to access the information found in an Excel spreadsheet? Can you send SQL queries to Excel and get back information?”
We’ll put it this way: the Office Space column is published on the Internet, and obviously something couldn’t be published on the Internet if it wasn’t 100% true. Of course Excel can function as a flat-file database that can be accessed using ADO and SQL queries. And in today’s column we’ll explain how to do just that.
Let’s take a look at a very simple spreadsheet and then explain how we can access the data using ADO (ActiveX Data Objects). Here’s a rudimentary spreadsheet – named C:\Scripts\Test.xls – that consists of two columns, one labeled Name, the other labeled Number. To better ensure that your database queries work against an Excel spreadsheet, make sure your spreadsheets are set up in a similar fashion; that is, make row 1 a header row, start the data itself in row 2, and don’t skip any rows or columns. And to make coding easier, don’t include blank spaces in your headers; for example, use a column header like SocialSecurityNumber and don’t use a column header like Social Security Number. It just makes life much easier. (Incidentally, that’s true when using any kind of database, not just Excel.)
Here’s what our spreadsheet looks like:


And, yes, we did put a lot of time and effort into creating this sample spreadsheet. All part of the service we offer.
But now for the big question: how do we access this data using ADO? Well, one way is to use a script that looks like this:
On Error Resume Next

Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Scripts\Test.xls;" & _
"Extended Properties=""Excel 8.0;HDR=Yes;"";"

objRecordset.Open "Select * FROM [Sheet1$]", _
objConnection, adOpenStatic, adLockOptimistic, adCmdText

Do Until objRecordset.EOF
Wscript.Echo objRecordset.Fields.Item("Name"), _
objRecordset.Fields.Item("Number")
objRecordset.MoveNext
Loop
We should probably start by pointing out that the first half of the script simply defines some constants and creates the two objects – ADODB.Connection and ADODB.Recordset – that are required to connect to and retrieve data from a data source. This is largely boilerplate code that you use as-is in any ADO script. And because this is boilerplate you can use as-is we won’t discuss the first half of the script in any detail; for more information you might take a look at the Working with Databases section of the Microsoft Windows 2000 Scripting Guide.
We’ll begin our discussion with this bit of code, which actually opens a connection to the Excel spreadsheet:
objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Scripts\Test.xls;" & _
"Extended Properties=""Excel 8.0;HDR=Yes;"";"
Again, this is largely boilerplate code. The only section you need to worry about is the Data Source, where you specify the path to your spreadsheet.
Note. What if the path to your spreadsheet includes spaces, something that can cause problems for ADO scripts working with text files (for more information, see this Hey, Scripting Guy! column)? In this case, there’s no problem whatsoever; just write out the entire file path, spaces and all:
Data Source=C:\Scripts\My Spreadsheet.xls
Incidentally, you should resist the temptation to change Excel 8.0 to whatever version of Excel you happen to be running on your machine. In this case the Excel 8.0 refers not to your version of Excel but to the ADO provider used to access Excel. Leave the provider as Excel 8.0 and everything will be fine.
As long as we’re on the subject we should also mention that the code HDR=Yes simply indicates that our spreadsheet has a header row; if our spreadsheet didn’t have a header row we’d set HDR to No. But seeing as how we said you should always have a header row and seeing as how people always do what the Scripting Guys tell them to, well, this is a moot point.
After making a connection to the data source we can use a SQL query to retrieve the information stored in that data source. Here’s the code we use to return a recordset consisting of all the rows in the spreadsheet:
objRecordset.Open "Select * FROM [Sheet1$]", _
objConnection, adOpenStatic, adLockOptimistic, adCmdText
Again, there’s a lot of ADO boilerplate in here; the only part we’re really concerned about for now is the actual SQL query:
Select * FROM [Sheet1$]
This is a standard SQL query, one that selects all the fields (columns) in the database (worksheet). Notice that we specify the name of an individual worksheet in the query, the same way that we would specify an individual table name were we connecting to a database. Notice, too, that the worksheet name is enclosed in square brackets and that the actual name – Sheet1 – has a $ appended to it. Make sure you do both those things when writing your own ADO scripts for accessing data in a spreadsheet.
The recordset returned to us is exactly the same sort of thing we’d get back were we making a connection to, say SQL Server. Because of that we can use these lines of code to simply report back the Name and Number for each record in the recordset, something that corresponds to each row in our spreadsheet:
Do Until objRecordset.EOF
Wscript.Echo objRecordset.Fields.Item("Name"), _
objRecordset.Fields.Item("Number")
objRecordset.MoveNext
Loop
When we run the script we should get back a report that looks like this:
A 1
B 1
C 2
D 2
E 1
F 1
Yes, very cool, but some of you are skeptical: after all, couldn’t we retrieve this same information using a plain-old Excel script? Yes, we could, which means that in this case, there’s really no reason to use ADO at all.
So then why did we even bother writing this column? (That, by the way, is something we get asked pretty much any time we write a column.) Well, we admit it: if all you want to do is echo back every row in the spreadsheet there’s no point in using ADO (unless you’re more comfortable writing ADO scripts than you are writing Excel scripts). However, suppose we wanted to echo back only the rows where Number was equal to 2. Using a standard Excel script we’d need to examine each row, determine whether the Number column was equal to 2, and then echo (or not echo) the row based on that value. This isn’t necessarily hard, but it can be a bit cumbersome, especially if you need to look at values in more than one column (for example, if you were looking for all users with the title Administrative Assistant who work for the Finance department).
With ADO, by contrast, we can get back this same information without having to individually examine each row in the spreadsheet. In fact, we can use pretty much the exact same script we just showed you; all we have to do is modify the SQL query. Because we want only those rows where the Number is equal to 2 we just need to use a SQL query like this:
objRecordset.Open "Select * FROM [Sheet1$] Where Number = 2", _
objConnection, adOpenStatic, adLockOptimistic, adCmdText
That’s it; the preceding query will give us back data like this:
C 2
D 2
Why use ADO? There’s your answer: because you can easily use SQL queries to return a subset of the information found in the spreadsheet. That’s why you might want to use ADO to access an Excel file.
By the way, here’s a complete script that returns just the rows where the Number column is equal to 2:
On Error Resume Next

Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Scripts\Test.xls;" & _
"Extended Properties=""Excel 8.0;HDR=Yes;"";"

objRecordset.Open "Select * FROM [Sheet1$] Where Number = 2", _
objConnection, adOpenStatic, adLockOptimistic, adCmdText

Do Until objRecordset.EOF
Wscript.Echo objRecordset.Fields.Item("Name"), _
objRecordset.Fields.Item("Number")
objRecordset.MoveNext
Loop
Before you ask, yes, there are other things you can do with ADO besides simply retrieve data. In a future column we’ll show you how you can use ADO to write data to a spreadsheet.
Hey, is it any wonder why everyone loves Excel?

Sabtu, 06 Februari 2010

Menubar pada Halaman Web

MEMBUAT MENU PADA INTERNET EXPLORER DENGAN ICON DI SEBELAH KIRI (SAMA DENGAN PROGRAM MICROSOFT OFFICE)
COPY KODE DI BAWAH INI! JALANKAN PADA INTERNET EXPLORER

HAPUS TAG BR/


Intel Web Design Effect 9 membuat efek api

Buat tag HTML,HEAD dan SCRIPT
Copy dan paste rumus di bawah ini pada tag SCRIPT LANGUAGE=VBSCRIPT:

sub window_onload
screen.bufferDepth=-1
Call doThem()
Call doInit()
end sub

sub dodetach
theTetonImg.filters.item("IntelAdditive").enabled=false
end sub

sub doThem
theTetonImg.filters.item("IntelAdditive").enabled=true
theTetonImg.filters.item("IntelAdditive").GenerateSeed=1
end sub

sub doInit
theTetonImg.filters.item("IntelAdditive").NoiseScale=8
theTetonImg.filters.item("IntelAdditive").NoiseOffset=-40
theTetonImg.filters.item("IntelAdditive").ScaleX=2
theTetonImg.filters.item("IntelAdditive").ScaleY=2
theTetonImg.filters.item("IntelAdditive").ScaleT=3
theTetonImg.filters.item("IntelAdditive").TimeY=2

theTetonImg.filters.item("IntelAdditive").Harmonics=4
theTetonImg.filters.item("IntelAdditive").ColorKey=65280
theTetonImg.filters.item("IntelAdditive").Alpha=0
theTetonImg.filters.item("IntelAdditive").MaskMode=1
end sub

sub OnTetonPokeEffect
n=theTetonImg.filters.item("IntelAdditive").NoiseScale
theTetonImg.filters.item("IntelAdditive").NoiseScale=n
end sub

sub theTetonImg_OnFilterChange
Call SetTimeout("OnTetonPokeEffect",400)
end sub

Setelah itu buat tag BODY
Copy dan Paste kode di bawah ini pada tag IMG
src=awan.bmp width=500 height=140 id="theTetonImg" style="filter:IntelAdditive(enabled=false)"

Anda membutuhkan file awan.bmp supaya terlihat animasi, buat file gambar bmp di
Start, Accessories, Paint. Gunakan warna hijau pada gambar tersebut. Bila tidak ada animasi
ganti oleh warna merah.

Jalankan program di atas di Internet Explorer versi 5.0 pada windows XP.

Intel Web Design Effect 8

Buat tag HTML,HEAD dan SCRIPT
Copy dan paste rumus di bawah ini pada tag SCRIPT LANGUAGE=VBSCRIPT:

sub window_onload
screen.bufferDepth=-1
Call doThem()
Call doInit()
end sub

sub dodetach
theTetonImg.filters.item("IntelAdditive").enabled=false
end sub

sub doThem
theTetonImg.filters.item("IntelAdditive").enabled=true
theTetonImg.filters.item("IntelAdditive").GenerateSeed=2
end sub

sub doInit
theTetonImg.filters.item("IntelAdditive").NoiseScale=10
theTetonImg.filters.item("IntelAdditive").NoiseOffset=80
theTetonImg.filters.item("IntelAdditive").ScaleX=4
theTetonImg.filters.item("IntelAdditive").ScaleY=2
theTetonImg.filters.item("IntelAdditive").ScaleT=3
theTetonImg.filters.item("IntelAdditive").TimeY=-1
theTetonImg.filters.item("IntelAdditive").TimeX=-4
theTetonImg.filters.item("IntelAdditive").Harmonics=4
theTetonImg.filters.item("IntelAdditive").ColorKey=65280
theTetonImg.filters.item("IntelAdditive").Alpha=1
theTetonImg.filters.item("IntelAdditive").MaskMode=1
end sub

sub OnTetonPokeEffect
n=theTetonImg.filters.item("IntelAdditive").NoiseScale
theTetonImg.filters.item("IntelAdditive").NoiseScale=n
end sub

sub theTetonImg_OnFilterChange
Call SetTimeout("OnTetonPokeEffect",400)
end sub

Setelah itu buat tag BODY
Copy dan Paste kode di bawah ini pada tag IMG
src=awan.bmp width=500 height=140 id="theTetonImg" style="filter:IntelAdditive(enabled=false)"

Anda membutuhkan file awan.bmp supaya terlihat animasi, buat file gambar bmp di
Start, Accessories, Paint. Gunakan warna hijau pada gambar tersebut. Bila tidak ada animasi
ganti oleh warna merah.

Jalankan program di atas di Internet Explorer versi 5.0 pada windows XP.