Sunday, June 17, 2012

Write Excel Data into a Text File

Hi friends,

I have a new small code for you all who are learning Excel VBA.
This piece of code writes the data which is in excel sheet, into a
text file.



Here is the code:


Private Sub btnWrite_Click()
  Dim id, name As String
  Dim salary As Double
  Dim fName As String
  Dim fNumber As Integer
  Dim lRow As Long
  
  fName = "E:\MyData\EmpData.txt"
  fNumber = FreeFile
  
  Open fName For Output As #fNumber
  lRow = 2
  
  Do
    With Sheet17
     id = .Cells(lRow, 1)
     name = .Cells(lRow, 2)
     salary = .Cells(lRow, 3)
    End With
    
    Write #fNumber, id, name, salary
    lRow = lRow + 1
  Loop Until IsEmpty(Sheet17.Cells(lRow, 1))
  Close #fNumber
End Sub

Thursday, June 14, 2012

How to use Message Box (MsgBox) ?

MsgBox() is a very common function in VBA. It is used to display a user defined message on the screen.
We can use a MsgBox in different manners. Examples are as follow :

1 - Simple Message Box


A message box with a single argument is called Simple Message Box. We need to pass the message as a string in MsgBox() funtion. It displays the default Title and Button.

Code :
MsgBox "Welcome To VBA"


2 - Message Box with Title


A message box with an user-defined message and a title.


Code:
MsgBox "This is a message box with a title", "Message Box Title"


3 - Message Box with Title and Buttons


A message box with user defined message, title and buttons.

Code:



Private Sub btnHome_Click()
  Dim result As VbMsgBoxResult
  result = MsgBox("Do you want to navigate to Home sheet ?", vbQuestion + vbYesNo, "Switch to Home Sheet")
  If (result = vbYes) Then
    Sheets("Home").Activate
  End If
End Sub

Change Date Format with Combo Box Control

Hi friends, I am giving you a new example on Changing Date Format.
Here is the Screen Shot


Here is the code...


Private Sub ComboBox1_Change()
  Range("K8").NumberFormat = ComboBox1.Text
End Sub


Private Sub Worksheet_Activate()
  ComboBox1.Clear
  ComboBox1.Text = "dd/mm/yy"
  ComboBox1.AddItem "dd/mm/yy"
  ComboBox1.AddItem "dd-mm-yyyy"
  ComboBox1.AddItem "dd-mm-yy"
  ComboBox1.AddItem "dddd, d mmmm, yyyy"
  ComboBox1.AddItem "mmmm dd, yyyy"
End Sub




I hope you would like this small and useful code.
Thanks