Coding Tips (JavaScript/CSS/VBA/Win32)
Useful code snippets, tips and some Windows applications
Excel VBA functions
- Get current directory in Excel VBA
- Export all worksheets in a workbook in the CSV format
- Change the background color of the data range
- Get the number of rows in the Worksheet
- A function to truncate a string
- Get the number of sheets in the active workbook
Get Current Directory in Excel VBA
This function retrieves the directory of the current workbook.Function GetCurDir() Dim str As String Dim pos As Integer str = ActiveWorkbook.FullName pos = InStrRev(str, "\") str = Mid(str, 1, pos) GetCurDir = str End Function
Export all worksheets in a workbook in the CSV format
Sub SaveAllWorkSheetsAsCSV() Dim ws As Worksheet Dim wb As Workbook Set wb = ActiveWorkbook Dim i As Integer i = 0 Dim Dir As String Dim Name As String Dir = GetCurDir For Each ws In wb.Worksheets Name = Dir & ws.Name + ".csv" ws.SaveAs Name, xlCSV i = i + 1 Next MsgBox "Saved " & i & " worksheets" End Sub
For Each ws In wb.Worksheets ws.Rows(1).Delete Name = Dir & ws.Name + ".csv" ws.SaveAs Name, xlCSV i = i + 1 Next
Change the background color of the data range
The following example highlights the range containing data in green.Dim ws As Worksheet Dim rng As Range Set ws = ActiveSheet Set rng = ws.UsedRange rng.Interior.ColorIndex = 4Alternatively, you can use a short version:
ActiveSheet.UsedRange.Interior.ColorIndex = 4
Get the number of rows in the Worksheet
ActiveSheet.UsedRange.Rows.Count
Function to Truncate a String
Function Truncate(str As String, intEndPos As Integer) Truncate = Left(str, intEndPos) End Function
Get the number of sheets in the active workbook
Function getNumberSheets() getNumberSheets = ActiveWorkbook.Sheets.Count End Function
More Excel VBA Tips