Thursday, 9 November 2017

VBA Add date by clicking Month Combobox


‘to add month date wise in combobox

Private Sub Req_Month_Change()

a = COmbobox_Month.Value
b = 1 & "-" & a & "-" & 17
c = WorksheetFunction.EoMonth(b, 0)
d = Format(c, "dd")
Combobox_Date.Clear
For i = 1 To d

Combobox_Date.AddItem i

Next i

End Sub

********************************************************************************************************************



Create text file

Sub CreateAfile

Set fs = CreateObject("Scripting.FileSystemObject")

Set a = fs.CreateTextFile("c:\testfile.txt", True)

a.WriteLine("This is a test.")

a.Close

End Sub





Sub OpenTextFileTest


Const ForReading = 1, ForWriting = 2, ForAppending = 3


Dim fs, f


Set fs = CreateObject("Scripting.FileSystemObject")


Set f = fs.OpenTextFile("c:\testfile.txt", ForAppending,TristateFalse)


f.Write "Hello world!"


f.Close


End Sub

Monday, 6 November 2017

LOOPING EXAMPLES

Looping in cell

Sub Cell_Loop()

Dim cell As Range

'Loop through each cell in a cell range
  For Each cell In ActiveSheet.Range("A1:Z100")
    Debug.Print cell.Value
  Next cell

'Loop through each cell in a Named Range
  For Each cell In ActiveSheet.Range("RawData")
    Debug.Print cell.Value
  Next cell

'Loop through each cell in a Table body range
  For Each cell In ActiveSheet.ListObjects("Table1").DataBodyRange
    Debug.Print cell.Value
  Next cell

End Sub
Looping in chart

Sub Chart_Loop()

Dim sht As Worksheet
Dim cht As ChartObject
'Loop through each chart in the active workbook
  For Each sht In ActiveWorkbook.Worksheets
    For Each cht In sht.ChartObjects
      Debug.Print cht.Name
    Next cht
  Next sht
End Sub
Looping Through shapes

Sub Shape_Loop()

Dim sht As Worksheet
Dim shp As Shape

'Loop through each shape in the active workbook
  For Each sht In ActiveWorkbook.Worksheets
    For Each shp In sht.Shapes
      If shp.Type = msoAutoShape Then
        Debug.Print shp.Name
      End If
    Next shp
  Next sht


End Sub

Wednesday, 1 November 2017

VBA -While Wend and Do Loop

while wend

While condition(s)
   [statements 1]
   [statements 2]
   ...
   [statements n]
Wend

example while wend

Private Sub Constant_demo_Click()
   Dim Counter :  Counter = 10  
  
   While Counter < 15     ' Test value of Counter.
      Counter = Counter + 1   ' Increment Counter.
      msgbox "The Current Value of the Counter is : " & Counter
   Wend   ' While loop exits if Counter Value becomes 15.
End Sub  

do while

Do While condition
   [statement 1]
   [statement 2]
   ...
   [statement n]
   [Exit Do]
   [statement 1]
   [statement 2]
   ...
   [statement n]
Loop          

examples
Private Sub Constant_demo_Click()
   Do While i < 5
      i = i + 1
      msgbox "The value of i is : " & i
   Loop
End Sub



Private Sub Constant_demo_Click()
   i = 10
   Do
      i = i + 1
      MsgBox "The value of i is : " & i
   Loop While i < 3 'Condition is false.Hence loop is executed once.

End Sub

JOTHIDAM KARPOM VANGA