I am creating a userform containing 2 textboxes, 4 different check boxes, 4 radial buttons and 2 command buttons, as seen below:
I want to change the row and column widths in the active sheet, or all the worksheets in a workbook, based on the selections in the form.
Frames
TextBox1 (Column Width), TextBox2 (Row Height)
To type the row height and column width.
Optionbutton1 (Column B onwards) , OptionButton2 (Column C onwards)
To select from which Column (B or C) you want to change the column width.
Optionbutton3 (Selected Sheet), OptionButton4 (All sheets)
To select on which sheet you want to change the row height and column width ( On Active sheet or On All the sheets).
CheckBox1 (Cover) , CheckBox2 (Trans_Letter), CheckBox3 (Abbreviations) CheckBox3 (Sheet ending with _Index)
One check box each for 4 of the sheets in my workbook. There are ~50 sheets in my workbook, these check boxes are for selecting which sheets to exclude while changing the column width and row height, when changing all of the sheets.
Please find below the code which I have put in the userform.
I am getting error on this line:
If IsError(WorksheetFunction.Match(ThisWorkbook.Worksheets(sheetNumber).Name, sheetsToExcludeArray, 0)) Then
Error Message: Run Time error '1004' Unable to get the Match property
of the worksheet function
Private Sub CommandButton1_Click()
Dim startColumn As Long
Dim formatAllSheets As Boolean
Dim sheetsToExcludeList As String
Dim sheetNumber As Long
startColumn = 3
If Me.OptionButton1.Value Then startColumn = 2
formatAllSheets = True
If Me.OptionButton3.Value Then formatAllSheets = False
If Me.CheckBox1.Value Then sheetsToExcludeList = sheetsToExcludeList & ",Cover"
If Me.CheckBox2.Value Then sheetsToExcludeList = sheetsToExcludeList & ",Trans_Letter"
If Me.CheckBox3.Value Then sheetsToExcludeList = sheetsToExcludeList & ",Abbreviations"
If Me.CheckBox4.Value Then sheetsToExcludeList = sheetsToExcludeList & ",Index"
sheetsToExcludeList = Mid(sheetsToExcludeList, 2)
Dim lastRow As Long
Dim lastColumn As Long
Dim itemInArray As Long
Dim rangeToFormat As Range
Dim sheetsToExcludeArray As Variant
If startColumn < 2 Or startColumn > 3 Then startColumn = 2
sheetsToExcludeArray = Split(sheetsToExcludeList, ",")
If formatAllSheets Then
For sheetNumber = 1 To ThisWorkbook.Worksheets.Count
If LBound(sheetsToExcludeArray) <= UBound(sheetsToExcludeArray) Then
If IsError(WorksheetFunction.Match(ThisWorkbook.Worksheets(sheetNumber).Name, sheetsToExcludeArray, 0)) Then
With ThisWorkbook.Worksheets(sheetNumber)
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
lastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
Set rangeToFormat = .Range(.Cells(1, startColumn), .Cells(lastRow, lastColumn))
rangeToFormat.Cells.RowHeight = me.textbox1.value
rangeToFormat.Cells.ColumnWidth = me.textbox2.value
End With
End If
Else
With ThisWorkbook.Worksheets(sheetNumber)
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
lastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
Set rangeToFormat = .Range(.Cells(1, startColumn), .Cells(lastRow, lastColumn))
rangeToFormat.Cells.RowHeight = me.textbox1.value
rangeToFormat.Cells.ColumnWidth = me.texbox2.value
End With
End If
Next sheetNumber
Else
With ThisWorkbook.Worksheets(sheetNumber)
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
lastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
Set rangeToFormat = .Range(.Cells(1, startColumn), .Cells(lastRow, lastColumn))
rangeToFormat.Cells.RowHeight = me.textbox1.value
rangeToFormat.Cells.ColumnWidth = me.textbox2.value
End With
End If
End Sub
Note, this answer uses an adaptation of the sub resizerowscols, which I wrote to answer your more recent question: Change column width and row height of hidden columns and rows (remaining hidden): Excel VBA
Main Click Sub
This (untested) sub takes the values from the form, then loops through the sheets (or just uses active sheet) and calls the other sub to do the resizing.
Sub CommandButton1_Click()
' Frame 1 values
Dim colwidth As Double
colwidth = Me.TextBox1.Value
Dim rowheight As Double
rowheight = Me.TextBox2.Value
' Frame 2 values
Dim selectedCol As String
If Me.OptionButton1.Value = True Then
selectedCol = "B"
Else
selectedCol = "C"
End If
' Frame 3 values
Dim doAllSheets As Boolean
doAllSheets = Me.OptionButton4.Value
'Frame 4 values
Dim sheetsToExcludeList As String
If Me.CheckBox1.Value Then sheetsToExcludeList = sheetsToExcludeList & ",Cover"
If Me.CheckBox2.Value Then sheetsToExcludeList = sheetsToExcludeList & ",Trans_Letter"
If Me.CheckBox3.Value Then sheetsToExcludeList = sheetsToExcludeList & ",Abbreviations"
If Me.CheckBox4.Value Then sheetsToExcludeList = sheetsToExcludeList & ",Index"
' Resizing
Dim shtrng As Range
Dim sht As Worksheet
If doAllSheets Then
' Loop through sheets
For Each sht In ThisWorkbook.Sheets
' Check sheet name isn't on exclude list
If InStr(sheetsToExcludeList, "," & sht.Name) = 0 Then
' Set range equal to intersection of used range and columns "selected column" onwards
Set shtrng = Intersect(sht.UsedRange, sht.Range(sht.Cells(1, selectedCol), sht.Cells(1, sht.Columns.Count)).EntireColumn)
' Resize columns / rows
resizerowscols rng:=shtrng, w:=colwidth, h:=rowheight
End If
Next sht
Else
' Just active sheet
Set sht = ThisWorkbook.ActiveSheet
Set shtrng = Intersect(sht.UsedRange, sht.Range(sht.Cells(1, selectedCol), sht.Cells(1, sht.Columns.Count)).EntireColumn)
resizerowscols rng:=shtrng, w:=colwidth, h:=rowheight
End If
End Sub
This is the adapted Sub from your other question, but now it takes the range, height and width as arguments. It unhides all rows/columns, resizes them, and re-hides all those which already were.
Sub resizerowscols(rng As Range, w As Double, h As Double)
' Resizes all rows and columns, including those which are hidden.
' At the end, hidden rows and columns remain hidden.
If rng Is Nothing Then Exit Sub
Dim n As Long
Dim hiddencols() As Long
Dim hiddenrows() As Long
Application.ScreenUpdating = False
' Get hidden rows/cols
ReDim hiddencols(rng.Columns.Count)
ReDim hiddenrows(rng.Rows.Count)
For n = 0 To UBound(hiddencols)
hiddencols(n) = rng.Columns(n + 1).Hidden
Next n
For n = 0 To UBound(hiddenrows)
hiddenrows(n) = rng.Rows(n + 1).Hidden
Next n
' Unhide all
rng.EntireColumn.Hidden = False
rng.EntireRow.Hidden = False
' resize all
rng.ColumnWidth = w
rng.rowheight = h
' Re-hide rows/cols
For n = 0 To UBound(hiddencols)
rng.Columns(n + 1).Hidden = hiddencols(n)
Next n
For n = 0 To UBound(hiddenrows)
rng.Rows(n + 1).Hidden = hiddenrows(n)
Next n
Application.ScreenUpdating = True
End Sub
Related
Im trying to create a table that pulls data from my raw data if certain conditions are met. The code I currently have does not seem to be working.
Public Sub insert_rows()
Dim datasheet As Worksheet
Dim datasheet2 As Worksheet
Dim r As Long
Dim tableA As ListObject
Set tableA = Worksheets(Sheet7).ListObject(Preventable)
Set datasheet = Worksheets(Sheet7)
Set datasheet2 = Worksheets("Data")
With datasheet2
nr = Cells(Rows.Count, 1).End(x1up).Row
For r = 1 To nr
If Cells(r, 17) = "Y" Then
Cells(r, 16).Copy Destination:=Sheets("Sheet7").Range("B4")
End If
Next
End With
End Sub
Basically I have several worksheets and need to pull data from one of them to add to this table in another worksheet. My condition is if the Column in the raw data worksheet contains "Y", then pull cell values into the table of the other worksheet. An image below is an example of the data I want to copy and paste over:
As you can see, they are string values separated by "," and can contain duplicates.
I only want to add just the unique entries into the new table; with no repetition of cells. Anyway I could modify this code to suit those conditions?
You could try something like this:
Public Sub insert_rows()
Dim datasheet As Worksheet
Dim datasheet2 As Worksheet
Dim r As Long, i As Long, nr As Long
Dim tableStartingRow As Long, currenttableitem As Long
Dim stringvalues As Variant
Dim stringseparator As String
Dim valueexists As Boolean
tableStartingRow = 4
stringseparator = ","
Set datasheet = Worksheets("Sheet7")
Set datasheet2 = Worksheets("Data")
With datasheet
currenttableitem = .Cells(.Rows.Count, 2).End(xlUp).Row
End With
With datasheet2
nr = .Cells(.Rows.Count, 16).End(xlUp).Row
For r = 1 To nr
If .Cells(r, 17) = "Y" Then
If InStr(.Cells(r, 16), stringseparator) > 0 Then 'If value contains comma
stringvalues = Split(.Cells(r, 16), stringseparator)
For i = LBound(stringvalues) To UBound(stringvalues)
valueexists = False 'Reset boolean
For x = tableStartingRow To currenttableitem
If datasheet.Range("B" & x).Value = Trim(stringvalues(i)) Then
valueexists = True
Exit For
End If
Next x
If Not valueexists Then
currenttableitem = currenttableitem + 1
datasheet.Range("B" & currenttableitem).Value = Trim(stringvalues(i))
End If
Next i
Else
valueexists = False 'Reset boolean
For x = tableStartingRow To currenttableitem
If datasheet.Range("B" & x).Value = .Cells(r, 16).Value Then
valueexists = True
Exit For
End If
Next x
If Not valueexists Then
currenttableitem = currenttableitem + 1
datasheet.Range("B" & currenttableitem).Value = .Cells(r, 16).Value
End If
End If
End If
Next
End With
End Sub
This code will check each value of the cells and will split the contents by ",". Then compare with the content of the table to see if this value is already in there. In case it is not, it will be added, otherwise omitted.
Also, I notice the use of the Cells inside of a With statement. That was making a reference to the active worksheet. To make reference to the item in the With statement, you need to use .Cells
I hope this will help.
I have the following table:
And a macro that loops through the first section of the table (rows 6-7) in order to create the Pie-Charts on the right. My target now is to loop through all other tables automatically as well. The next one would be in row11 and create a new Pie Chart for that row, then the next table (rows 15-16) and so on. The header of each table is always red. The problem is that the length of the tables vary, meaning for example in the table1 ("Build", A5:K7) there can be 2 rows like here or 50, but each time I need one PieChart for each row.
Currently I have the following working code for Table1 ("Build" A6:K79) to create the 2 PieCharts automatically, but Im unsure how to make one loop for all tables on the sheet.
Dim rownumber As Integer
Dim LabelRange As Range
Dim ValueRange As Range
Dim Chart As ChartObject
Dim LeftIndent As Long
Dim TopIndent As Long
Dim InhaltsRangeString As String
Dim LetzteZeile As Long
'Intialpositionen für Graphen
LeftIndent = 726
TopIndent = 60
rownumber = 6 'Anfang der Buildtabelle in Reihe 6 (Spalte 1)
Set LabelRange = ThisWorkbook.Worksheets("Testplan Überblick").Range("C5, E5, G5, I5")
Set TPsheet = Worksheets("Testplan Überblick")
Set ValueRange = Union(TPsheet.Cells(rownumber, 3), TPsheet.Cells(rownumber, 5), TPsheet.Cells(rownumber, 7), TPsheet.Cells(rownumber, 9))
'Loop through table 1 which always starts at row 6 (unlike the others which have no set starting point cause the ones before can vary in length!)
For rownumber = 6 To LetzteZeileFunktion Step 1 '"LetzteZeileFunktion" gives me the long value of the last row filled in table 1
Set Chart = Sheets("Testplan Überblick").ChartObjects.Add(Left:=180, Width:=270, Top:=7, Height:=210)
With Chart
.Chart.SetSourceData Source:=ValueRange
.Chart.ChartType = xlPie
.Chart.HasTitle = True
.Chart.SetElement (msoElementChartTitleAboveChart)
.Chart.ChartTitle.Text = Sheets("Testplan Überblick").Cells(rownumber, 1).Value
.Chart.FullSeriesCollection(1).XValues = LabelRange
.Left = LeftIndent
.Top = TopIndent
.Name = Sheets("Testplan Überblick").Cells(rownumber, 1).Value
End With
TopIndent = TopIndent + 225
Next rownumber
End Sub
Any ideas on how to loop through all the tables even though they can all differ in length (amount of rows filled with content for charts) would be greatly appreciated!
Cheers
Use the text in one of the headers to identify the start of the data rows and a blank in column A to end. I have used "testfall qty" in column B.
Option Explicit
Sub CreateCharts()
Const DATA = "Testplan Überblick"
Const ROW_START = 5
Const POSN_LEFT = 726
Const POSN_TOP = 60
Const COL = "B"
Const HEADER = "testfall qty"
Dim wb As Workbook, ws As Worksheet
Dim rngLabel As Range, rngValue As Range
Dim iRow As Long, iLastRow As Long, count As Integer
Dim oCht As ChartObject, sColA As String, bflag As Boolean
bflag = False
Set wb = ThisWorkbook
Set ws = wb.Sheets(DATA)
' scan down the sheet
iLastRow = ws.Cells(Rows.count, "A").End(xlUp).Row
For iRow = ROW_START To iLastRow
' look for Testfall Qty as header
sColA = ws.Cells(iRow, 1)
If LCase(ws.Cells(iRow, COL)) = HEADER Then
'set ranges
Set rngLabel = ws.Range("C1, E1, G1, I1").Offset(iRow - 1)
bflag = True
ElseIf Len(sColA) > 0 And bflag Then
' create chart
Set rngValue = ws.Range("C1, E1, G1, I1").Offset(iRow - 1)
Set oCht = ws.ChartObjects.Add(Left:=180, _
Width:=270, Top:=7, Height:=210)
With oCht
.Left = POSN_LEFT
.Top = POSN_TOP + (count * 255)
.Name = sColA
With .Chart
.SetSourceData Source:=rngValue
.SeriesCollection(1).XValues = rngLabel
.ChartType = xlPie
.HasTitle = True
.SetElement msoElementChartTitleAboveChart
.ChartTitle.Text = sColA
End With
End With
count = count + 1
Else
' end of chart data
bflag = False
End If
Next
MsgBox count & " Charts created", vbInformation
End Sub
I need help with writing some VBA that will read selected cells, ask for what you want to sort (for example you input FTA) and then it will take those three letters and the numbers following the "-" and put them into another sheet in the correct column. I will be adding more and more of these strings to cells and be able to run this multiple times till i use up all of the letter/number combinations. I have some code right now that just takes me to sheet labeled piece count and highlights cell E1. My sheets are called "Tracking log" and "Piece list"
Sub List()
Dim xLStr As String, xStrTmp As String
Dim xLStrLen As Long, xCount2 As Long, xCount As Long, I As Long, T As Long
Dim xCell As Range
Dim xArr
Dim xArr2
Dim xLnum As Long
On Error Resume Next
xLStr = Application.InputBox("What is the string to list:", , , , , , , 2) 'creates aplication box
If TypeName(xLStr) <> "String" Then Exit Sub '<> is not equal, "String" is the criteria
Application.ScreenUpdating = False 'nessecary for faster running time
xLStrLen = Len(xLStr) + Len(xLnum) 'sets string length to 7 in this case, len finds the length of a string
For Each xCell In Selection 'searches in the highlighted cells
xArr = Split(xCell.Value, xLStr) 'pulls the specific string that is to be searched
xCount = UBound(xArr)
If xCount > 0 Then
For I = 0 To xCount - 1
xCell.Copy (I)
Sheets("Piece list").Activate
Range("E1").Select
ActiveSheet.Paste
Next
' xArr2 = Split(xCell.Value, xLnum)
' xCount2 = UBound(xArr2)
' If xCount2 > 0 Then
' xStrTmp = ""
' For T = 0 To xCount2 - 1
' xStrTmp = xStrTmp & xArr2(T)
'
' xStrTmp = xStrTmp & xLStr
' Next
End If
Next
Application.ScreenUpdating = True
End Sub
[Here is my list of letters and numbers separated with "-" and commas
[Here is where I would like to put them sorted into the right column and by number in descending order
Here are my sheets
Split the strings into separate items. Then split the items into parts such that each item becomes a row with 3 columns e.g. ABC-123,ABC,123. Sort the data by columns 2 and 3 and then tabulate by column 1 onto a results sheet.
Option Explicit
Sub macro()
Dim wb As Workbook, ws As Worksheet, wsData As Worksheet, wsOut As Worksheet
Dim cell As Range, rng As Range, ar1 As Variant, ar2 As Variant
Dim n As Long, i As Long, r As Long, c As Long, iLastRow As Long
Dim s As String, prev As String
Set wb = ThisWorkbook
Set ws = wb.Sheets(1) ' data in col A
Set wsData = wb.Sheets(2) ' temp sheet
Set wsOut = wb.Sheets(3) ' output
' scan sheet 1, seperate and output to sheet 2
i = 1
iLastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
For r = 1 To iLastRow
s = ws.Cells(r, 1)
s = replace(s," ","") ' remove any spaces
If Len(s) > 0 Then
ar1 = Split(s, ",")
For n = 0 To UBound(ar1)
ar2 = Split(ar1(n), "-")
wsData.Cells(i, 1) = ar1(n)
wsData.Cells(i, 2) = ar2(0)
wsData.Cells(i, 3) = ar2(1)
i = i + 1
Next
End If
Next
iLastRow = i - 1
' sort on sheet 2
With wsData.Sort
.SortFields.Clear
.SetRange Range("A1:C" & iLastRow)
.SortFields.Add Key:=Range("B1:B" & iLastRow)
.SortFields.Add Key:=Range("C1:C" & iLastRow)
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
' tabulate onto sheet 3
c = 0
r = 0
prev = ""
For i = 1 To iLastRow
s = wsData.Cells(i, 2) 'abc
If s <> prev Then
' start new column
c = c + 1
wsOut.Cells(1, c) = s
wsOut.Cells(2, c) = wsData.Cells(i, 1)
r = 3
Else
wsOut.Cells(r, c) = wsData.Cells(i, 1)
r = r + 1
End If
prev = s
Next
MsgBox "Done"
End Sub
I have a macro that copies and pastes rows from input sheet to output sheet. I find PRODUCT NAME and END DATE, then copy the whole row and transpose when pasting it. I am using transpose because I want to have vertical table.
I have a problem with images because I don't know how to copy them to proper cell so they match with Name and Date. I've managed to write a script that is copying and pasting images but it puts all of them in cell A1. When I want to add range to target_sheet.Paste I am getting vba method intersect of object _application failed error.
Below you can see how input and output sheets look.
Input sheet:
Expected output sheet (with only 3 columns) :
It is very important to know that 'input' sheet contains many products with names, prices and images and there is always a blank row between them. The number of images in each row can be different (from 1 to 25).
Sub copy_paste()
Dim Cell As Range
Dim src_rng As String
Dim LR As Long
Dim source_sheet As Worksheet
Dim target_sheet As Worksheet
Dim pic As Shape
'worksheet with source data
Set source_sheet = ThisWorkbook.Sheets("input")
'worksheet with newly created template
Set target_sheet = ThisWorkbook.Sheets("output")
'range of cells I want to check
src_rng = "A14:A26"
Application.ScreenUpdating = False
target_sheet.Cells.Delete
'copy paste, transpose product line rows
For Each Cell In source_sheet.Range(src_rng)
LR = target_sheet.Range("A10000").End(xlUp).Row + 1
If Cell.Value = "Name" Then
Cell.EntireRow.Copy
target_sheet.Range("A" & LR).PasteSpecial Paste:=xlPasteValues, Transpose:=True
End If
Next
'copy paste, transpose end line rows
For Each Cell In source_sheet.Range(src_rng)
LR = target_sheet.Range("B10000").End(xlUp).Row + 1
If Cell.Value = "Date" Then
Cell.EntireRow.Copy
target_sheet.Range("B" & LR).PasteSpecial Paste:=xlPasteValues, Transpose:=True
End If
Next
'copy paste image
For Each Cell In source_sheet.Range(src_rng)
LR = target_sheet.Range("C10000").End(xlUp).Row + 1
If Cell.Value = "Image" Then
For Each pic In source_sheet.Shapes
If Not Application.Intersect(pic.TopLeftCell, Range(src_rng)) Is Nothing Then
pic.CopyPicture
target_sheet.Paste
End If
Next pic
End If
Next
Application.ScreenUpdating = True
End Sub
Please, try the next code. It follows the logic deduced from your last question edit, respectively: the former "Name" becomes "Product Name", "Date" becomes "End Date" and the row keeping the pictures is the one below "Product Name" row. It is able to process two or three product names/pictures per group:
Sub copy_paste()
Dim Cell As Range, src_rng As String, LR As Long
Dim source_sheet As Worksheet, target_sheet As Worksheet
Dim pic As Shape, arrPAddr, rngTr As Range, k As Long
Dim cellRHeight As Range, nrShapesPerRange As Long 'to be 2 or 3
nrShapesPerRange = 2 'Choose here initial number of shapes per row (2 or 3)
'worksheet with source data
Set source_sheet = ThisWorkbook.Sheets("input")
'worksheet with newly created template
Set target_sheet = ThisWorkbook.Sheets("output")
'range of cells I want to check
src_rng = "A14:A26"
Application.ScreenUpdating = False
ReDim arrPAddr(1 To 2, 1 To source_sheet.Shapes.count): k = 1
target_sheet.cells.Delete: For Each pic In target_sheet.Shapes: pic.Delete: Next
'copy paste, transpose product line rows
For Each Cell In source_sheet.Range(src_rng)
LR = target_sheet.Range("A" & rows.count).End(xlUp).row + 1
If Cell.value = "Product Name" Then
source_sheet.Range(Cell.Offset(, 1), Cell.Offset(, 3)).Copy
Set rngTr = target_sheet.Range("A" & LR)
rngTr.PasteSpecial Paste:=xlAll, Transpose:=True
arrPAddr(1, k) = Cell.Offset(1, 1).Address
arrPAddr(2, k) = rngTr.Offset(, 2).Address: k = k + 1
arrPAddr(1, k) = Cell.Offset(1, 2).Address
arrPAddr(2, k) = rngTr.Offset(1, 2).Address: k = k + 1
If nrShapesPerRange = 3 Then
arrPAddr(1, k) = Cell.Offset(1, 3).Address
arrPAddr(2, k) = rngTr.Offset(2, 2).Address: k = k + 1
End If
If cellRHeight Is Nothing Then Set cellRHeight = Cell.Offset(1)
End If
LR = target_sheet.Range("B" & rows.count).End(xlUp).row + 1
If Cell.value = "End Date" Then
source_sheet.Range(Cell.Offset(, 1), Cell.Offset(, 3)).Copy
Set rngTr = target_sheet.Range("B" & LR)
rngTr.PasteSpecial Paste:=xlAll, Transpose:=True
End If
Next
ReDim Preserve arrPAddr(1 To 2, 1 To k - 1)
'Making the row height in target_sheet equal to source_sheet column with:
target_sheet.Range("2:" & LR + 3).EntireRow.RowHeight = source_sheet.Range("A16").EntireRow.RowHeight
target_sheet.Range("A:C").EntireColumn.AutoFit
target_sheet.Range("C1").EntireColumn.ColumnWidth = cellRHeight.EntireColumn.ColumnWidth
'copy paste image:
Dim i As Long
For Each pic In source_sheet.Shapes
For i = 1 To UBound(arrPAddr, 2)
If pic.TopLeftCell.Address = arrPAddr(1, i) Then
pic.Copy: target_sheet.Paste
With target_sheet.Shapes(target_sheet.Shapes.count)
.top = target_sheet.Range(arrPAddr(2, i)).top + (target_sheet.Range(arrPAddr(2, i)).RowHeight - pic.height) / 2
.left = target_sheet.Range(arrPAddr(2, i)).left
End With
Exit For
End If
Next i
Next
Application.ScreenUpdating = True
target_sheet.Activate
MsgBox "Ready..."
End Sub
Plese, test the code and send some feedback
I wasn't able to find any vba zoom except for auto-changing based on resolution, but is it possible to autofit custom zoom level based on most furthest out column that has text?
Sub Workbook_Open()
ActiveWindow.Zoom = 100 'also you can change to other size
End Sub
Bonus Code:
To reset the scroll bar to far left, so it's looking at Column A/Row1, this code works :) I have it on a "reset" userbutton.
'Scroll to a specific row and column
ActiveWindow.ScrollRow = 1
ActiveWindow.ScrollColumn = 1
Thank you in advance.
Try this code:
Function FindFurthestColumn(S As Worksheet) As Integer
Dim CellsWithContent As Long
CellsWithContent = WorksheetFunction.CountA(S.Cells)
If CellsWithContent = 0 Then
FindFurthestColumn = 1
Exit Function
End If
Dim CellsCount As Long
Dim j As Integer
Do
j = j + 1
CellsCount = CellsCount + WorksheetFunction.CountA(S.Columns(j))
Loop Until CellsCount = CellsWithContent
FindFurthestColumn = j
End Function
Function CellIsVisible(cell As Range) As Boolean
CellIsVisible = Not Intersect(ActiveWindow.VisibleRange, cell) Is Nothing
End Function
Sub ZoomVisibleCells()
Application.ScreenUpdating = False
Dim LastColumn As Integer
LastColumn = FindFurthestColumn(ActiveSheet)
Dim SplitCell As Range
If ActiveWindow.Split = True Then
Set SplitCell = Cells(ActiveWindow.SplitRow + 1, ActiveWindow.SplitColumn + 1)
ActiveWindow.FreezePanes = False
End If
Dim Zoom As Integer
For Zoom = 400 To 10 Step -1
ActiveWindow.ScrollRow = 1
ActiveWindow.ScrollColumn = 1
ActiveWindow.Zoom = Zoom
If CellIsVisible(ActiveSheet.Cells(1, LastColumn + 1)) Then
Exit For
End If
Next Zoom
If Not SplitCell Is Nothing Then
SplitCell.Activate
ActiveWindow.FreezePanes = True
End If
Application.ScreenUpdating = True
End Sub
Credit for the CellIsVisible function:
https://stackoverflow.com/a/11943260/14370454
AUTO ZOOM RESPONSIVE VIEW EXCEL VBA CODE
In a sheet type any character on cell A1 and your last column view then type a character on first row with last column. That's it, see a magic of responsive view Excel sheet/s.
Note: copy this code and paste it to Thisworkbook module.
Thank you all.
Private Sub Workbook_WindowResize(ByVal Wn As Window)
Dim LastCol As Long
Dim rng As Range
Dim x As Integer
Dim y As Integer
With ActiveSheet
Set rng = .Rows(1).Find(What:="*", LookIn:=xlFormulas, SearchDirection:=xlPrevious)
End With
If Not rng Is Nothing Then
LastCol = rng.Column
Else
LastCol = 1
End If
x = 1 ' For First Column
y = LastCol ' For Last
Columns(Chr(64 + x) & ":" & Chr(64 + y)).Select
ActiveWindow.Zoom = True
ActiveSheet.Range("E1").Select
End Sub