Search VBA Code here

Sunday
Jul152007

Add new sheet with automatically generated name: VBA Excel

Sub AddSheetWithNameCheckIfExists()
Dim ws As Worksheet
Dim newSheetName As String
newSheetName = Sheets(1).Range("A1")   '   Substitute your range here
    For Each ws In Worksheets
        If ws.Name = newSheetName Or newSheetName = "" Or IsNumeric(newSheetName) Then
            MsgBox "Sheet already exists or name is invalid", vbInformation
            Exit Sub
        End If
    Next
Sheets.Add Type:="Worksheet"
    With ActiveSheet
        .Move after:=Worksheets(Worksheets.Count)
        .Name = newSheetName
    End With
End Sub

 

Wednesday
Jan312007

Find largest column width, and set all columns to greatest column width: VBA Excel

This is a recursive function:

          

Sub Main()

Call AdjustCols(Range("B2"), 1)

'B2 represents the first cell to be used, 1 represents the next column, C2.   

'$H$2 represents the last cell in your comparison   

end sub

Function AdjustCols(Currentcell As Range, nextCell As Integer)


    If Currentcell(1, 1).Offset(0, nextCell).Address= "$H$2" Then
        Cells.ColumnWidth = Currentcell.Cells(1, 1).ColumnWidth
        Exit Function


    ElseIf Currentcell.Cells(1, 1).ColumnWidth < Currentcell.Cells(1, 1)._

        Offset(0, nextCell).ColumnWidth Then
        Call AdjustCols(Currentcell.Cells(1, 1).Offset(0, nextCell), 1)


    Else
        nextCell = nextCell + 1
        Call AdjustCols(Currentcell.Cells(1, 1), nextCell)
    End If


End Function

Page 1 ... 2 3 4 5 6