Home » excel » excel – VBA how to pass integer to range values

excel – VBA how to pass integer to range values

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m trying to simplify this function from the following

Public Sub freezeRow(sheetAct, sheetType As String, sheetRow As Integer)

sheetAct.Activate    'Activate sheet
ActiveWindow.FreezePanes = False 'Unfreeze all rows

Select Case sheetType
    Case "Sum"
        'Freeze the Summary spread sheet after row 9
        sheetAct.Range("10:10").Select

    Case "Data"
        'Freeze the Summary spread sheet after row 2
        sheetAct.Range("3:3").Select
End Select

ActiveWindow.FreezePanes = True 'Freeze selected rows

End Sub

to something like this

Public Sub freezeRow(sheetAct, sheetType As String, sheetRow As Integer)

sheetAct.Activate    'Activate sheet
ActiveWindow.FreezePanes = False 'Unfreeze all rows

sheetAct.Range("sheetRow:sheetRow").Select


ActiveWindow.FreezePanes = True 'Freeze selected rows

End Sub

I can’t seem to remove the quotes in the range and when I run it tosses some obscure error

How to&Answers:

I like to use Cells() all the time, since it’s more explicit (to me anyways)

sheetAct.Range("sheetRow:sheetRow").Select

with

With sheetAct
    .Range(.Cells(sheetRow,1),.Cells(sheetrow,1)).EntireRow.Select
End with

Or, just use sheetAct.Range(sheetRow & ":" & sheetRow).Select

But why use .Select? You can work around using .Select which is best practice. (Of course, if you’re using it to double check you have the right range, then that’s fine. It’s when you work with the data you want to be careful).

Answer:

As a quick solution, I suggest something like this:

Public Sub freezeRow(sheetAct As Worksheet, sheetRow As String)
  Application.Goto sheetAct.Rows(sheetRow)
  ActiveWindow.FreezePanes = False
  ActiveWindow.FreezePanes = True
End Sub

You may add the line ActiveWindow.Split = False between the ActiveWindow.FreezePanes = False and ActiveWindow.FreezePanes = True, because if the FreezePanes was done after a Split, then ActiveWindow.FreezePanes = False will change the window back to the Split-state as it was before. In that case ActiveWindow.FreezePanes = True will ignore the selected range and freeze it at the point where the Split is located.

Also I suggest using sheetAct.Rows(sheetRow + 1) because the panes will be freezed over sheetRow. But that is just for a better logic -> having 3 will freeze 3 rows instead if 2.

Answer:

I found that this method worked perfectly

Public Sub freezeRow(sheetAct, sheetRow As String)
  Dim rangeVal As String

   rangeVal = sheetRow & ":" & sheetRow
   sheetAct.Activate    'Activate sheet
   ActiveWindow.FreezePanes = False 'Unfreeze all rows
   sheetAct.Range(rangeVal).Select 'Select appropriate row

   ActiveWindow.FreezePanes = True 'Freeze selected rows

End Sub

This only for freezing Headers are visible while scrolling through the data