VBA Snippets

Post #519 written by Khodok in Code

Content

These might someday be useful again

VBA - Dynamic Range
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
Dim ws As Worksheet
Set ws = Sheets("SOMESHEET") ' Rename the sheet

Dim lastRow As Integer ' For optimisation, don't forget to change it to Byte (255), Integer (32,767) or Long (2B) depending on how many lines you have
Dim lastColumn As Byte ' For optimisation, don't forget to change it to Byte (255), Integer (32,767) depending on how many columns you have
Dim dynamicRng As Range

' Find the last non-blank cell in column A (1)
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

' Find the last non-blank cell in the first row (assuming data starts in row 1)
' Change "A1" to where your data starts if it's different
lastColumn = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
' lastColumn = Columns(ws.UsedRange.Column + ws.UsedRange.Columns.Count - 1).Column (this gets the absolute last column of the sheet) https://www.mrexcel.com/board/threads/trying-to-find-last-column-with-spaces-in-between-data.980158/post-4702880

' Define the range from A1 to the last non-blank cell in the last row and column
Set dynamicRng = ws.Range("A1").Resize(lastRow, lastColumn)
VBA - Get Column letter with its number
1
2
3
4
5
6
' https://stackoverflow.com/a/12797190
Function Col_Letter(Col As Integer) As String
    Dim vArr    
    vArr = Split(Cells(1, Col).Address(True, False), "$")
    Col_Letter = vArr(0)
End Function
VBA - Go to A1 in sheets
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Sub GoA1InEverySheet(Optional ByVal endSht As Worksheet)
    Dim ws As Worksheet, currentSht As Worksheet
    Set currentSht = ActiveWorkbook.ActiveSheet

    For Each ws In ActiveWorkbook.Worksheets
        If ws.Visible = xlSheetVisible Then
            With ws
                .Activate
                .Range("A1").Select
            End With

            With ActiveWindow
                .ScrollRow = 1
                .ScrollColumn = 1
            End With
        End If
    Next ws


    If Not endSht Is Nothing Then
        endSht.Activate
    Else
        currentSht.Activate
    End If
End Sub
VBA - Usage of Go to A1 in sheets
1
2
3
4
5
6
7
Call GoA1InEverySheet
Call GoA1InEverySheet(Sheets(1)) ' Change Sheet index or name

' Let's say we want to make it a button
Sub GoA1() ' Make this function the button's called function
    Call GoA1InEverySheet(Sheets(1)) ' You can also change the end Sheet here
End Sub
Comments

Please Log in to leave a comment.

No comments yet.