Monday, May 26, 2008

Prompting for a password before running a VBA code

The macro below will help you set a custom password for running a macro in workbook. Let’s say you have a run query button on your worksheet and you want to make sure before running the codes behind this query user needs to be authenticated.


Private Sub CommandButton1_Click()

Dim strPass As String ' This sting is password

Dim lCount As Long

For lCount = 1 To 3

strPass = InputBox(Prompt:="Password Please", Title:="PASSWORD REQUIRED")

If strPass = vbNullString Then 'Cancelled

sLast.Select

Exit Sub

ElseIf strPass <> "Password" Then 'InCorrect password

MsgBox "Password incorrect", vbCritical, "Failed"

Else 'Correct Password

Exit For

End If


Next lCount

If lCount = 4 Then 'They use up their 3 attempts

MsgBox "The password is wrong, workbook is going close", vbInformation

ActiveWorkbook.Close SaveChanges:=False

Exit Sub

Else

MsgBox "Correct Password", vbOKOnly 'put your codes from hear on

End If

End Sub

Extract the RGB colour of a shape using VBA.

There are times when we want to replicate a Shapes RBG value in some other shape or at least know the Red, Green and Blue components distinctly.

Hear is function that will help us extract the RBG value of shape is any MS Office Application (Word, Excel, and PowerPoint).

The function returns two values, one as Text string and the other one as Hexadecimal value depending on the Boolean type you specify.

Paste the codes as below in any VBA mobule:







Function RBGExtract(myShape As Shape, IsHex As Boolean) As Variant

c = myShape.Fill.ForeColor.RGB

If IsHex = False Then

redComponent = c Mod 256

greenComponent = c \ 256 Mod 256

blueComponent = c \ 65536 Mod 256

RBGExtract = "RGB components: " & redComponent & _

", " & greenComponent & ", " & blueComponent

Else

RBGExtract = c

End If

End Function





Now, its time to test the function that we have created, we will test it in PPT through following subroutine:








Sub Test()

With ActivePresentation.Slides(1)

MsgBox RBGExtract(.Shapes(1), True), vbInformation,

'To test the Hexadecimal value
MsgBox RBGExtract(.Shapes(1), False), vbInformation, 'To test the Text value

End With

End Sub