Excel 2010 VBA Length of Column given column index - excel

I am finding this surprisingly hard to find an answer for, given its simple description. I hope this is not a duplicate, though it probably is because of its simplicity, and I simply cannot find the answer.
In VBA, I have hundreds of columns, and I'd like to know all their lengths. I know there are exactly "COLS" columns. I want something like this:
For i in COLS
length = 'Some one line formula to find the length of column i
'Some code that works with the value of length
Next i
By length I mean the number of non-empty cells... For my specific purposes there will be no blank cells in the columns, and all the cells in the column I wish to count will contain text (all the rest will be empty).
Help would be much appreciated on this seemingly simple matter!
Edit: I also want to make this dependent on the column index (which will be 'i' in the loop above). I won't always know the column letter...

This will count text non-empty cells in VBA:
For i = 1 To Columns.Count
n = WorksheetFunction.CountA(Columns(i))
Next

It is best to use a routine that works automatically from the last row in all Excel versions.
Dim lngRow As Long
lngRow = Cells(Rows.Count, "A").End(xlUp).Row

I think you could use
LastRowColA = Range("A" & Rows.Count).End(xlUp).Row
to find last used row in column A.
Navigating through every column you can have what you want...

You can find the last non-empty row using Range(large row number, column).End(xlUP).row where large row number should be large enough to always be beyond your last used cell.

You can use an alternative approach using the worksheet function CountA as follows
Test Data:
Col1 Col2 Col3
A A A
B B
C C C
D D D
E E
VBA function:
Sub Test()
Dim sht As Excel.Worksheet
Set sht = Worksheets("Sheet1")
Dim i As Integer
Dim max As Integer
Dim length As Integer
max = 0
For i = 1 To 3
'CountA returns the number of non-blank cells in a range
length = WorksheetFunction.CountA(sht.Columns(i))
If length > max Then max = length
Next i
MsgBox max - 1 ('remove 1 if you have column headers)
End Sub

len = sheet1.Range("B" & Rows.Count).End(xlUp).Row ' gives the count of B column
len = sheet1.Range("A" & Rows.Count).End(xlUp).Row ' gives the count of A column

dim i as integer
For i = 1 To Columns.Count
debug.print i, cells(i, rows.count).end(xlup).row
Next

Related

Filtering through a list of tables to only include useful lines

Given the lack of elegance with the data
the record sheet continues for many MANY rows, each entry having its own set of identical headings
I was hoping to just extract the data from rows 7, 14 and so on, then populate the data into a simple table to be used on the 'Protocol Summary' form, then sort them all into alphanumeric order based on the data that is in the A column so they all become grouped by 'Event Type'.
Because the potential data that could be under the 'Event Type' heading can vary a lot (generally has the format of [number 1-32/letter/number 1-30] but can also be all letters, with a few thousand possibilities, I thought it might be easier to filter the other lines OUT, given they don't change. I would love to redesign the table, but unfortunately it's not my table so I have to work with what I'm given.
Thanks for your time.
This will loop over your sheet up to the last used row, starting from Row 7 and stepping 7 rows each iteration.
Within each iteration, each cell in the row is written into an array which is then written to another sheet ready for sorting (however you want to do that).
This code is sample and may not work by copy/paste.
I have written this in the Sheet1 code module, so Me refers to ThisWorkbook.Sheets("Sheet1").
I have made this from a blank workbook and did not rename any sheets therefore you will need to make adjustments to any sheet references to match your appropriate sheet names.
The code will only reference columns A, B and C in the TargetRow (I only tested with 3 columns of data as I don't know your working range). I'll reference what to update to extend this after the code block.
Currently the array is put back into Sheet2 starting from cell A2. This is assuming row 1 contains table headers as this will write the data directly into the table format. Naturally if you want to change where the data is written, change the cell it is written to (when writing an array to sheet, you only need to define the top left cell of the range it is written to, Excel works out the rest based on the size and dimensions of the array).
Sub WriteEverySeventhRowToAnotherSheet()
Dim SeventhRowCount As Long
Dim myArray() As Variant
Dim lastrow As Long
Dim TargetCell As Variant
Dim TargetRow As Range
Dim ArrFirstDimension As Long
Dim ArrSecondDimension As Long
lastrow = Me.Range("A" & Me.Rows.Count).End(xlUp).Row
ReDim myArray(1 To lastrow / 7, 1 To 3)
ArrFirstDimension = 1
ArrSecondDimension = 1
'------------------Loop over every 7th row and enter row data to array---------------
For SeventhRowCount = 7 To lastrow Step 7
Set TargetRow = Me.Range("A" & SeventhRowCount & ":C" & SeventhRowCount)
For Each TargetCell In TargetRow
If Not ArrSecondDimension > UBound(myArray) Then
myArray(ArrFirstDimension, ArrSecondDimension) = TargetCell
'Debug.Print TargetCell
ArrSecondDimension = ArrSecondDimension + 1
End If
Next TargetCell
ArrFirstDimension = ArrFirstDimension + 1
ArrSecondDimension = 1
Set TargetRow = Nothing
Next SeventhRowCount
'---------------------Write array to another sheet------------------
Dim Destination As Range
Set Destination = ThisWorkbook.Sheets("Sheet2").Range("A2")
Destination.Resize(UBound(myArray, 1), UBound(myArray, 2)).Value = myArray
End Sub
To extend the number of columns the loop will write to the array, change the following instance of C to the correct column letter (in the below line the range is set from Column A to Column C):
Set TargetRow = Me.Range("A" & SeventhRowCount & ":C" & SeventhRowCount)
Also change the 2nd dimension of the Array to match the number of the Column set above (i.e Column E = 5 and Column L = 13 etc.) - You need to replace the number 3 with the correct number.
ReDim myArray(1 To lastrow / 7, 1 To 3)

Loop: add sequence number, delete columns

I want to know the VBA script for the Loop: Add sequence number (start number 1000 and 1001,1002,1003 so on) to the specific column and delete the another specific columns from multiple excel files into one folder. The purpose is to have the exact excel format to process the data in the special software.
I am beginner with VBA code.
Thank you for your time.
A possible solution:
Option Explicit
Sub test()
Dim LastRowC As Long, i As Long
With ThisWorkbook.Worksheets("Sheet1")
'Let us assume that values appear in Column C. Find last row of column C
LastRowC = .Cells(.Rows.Count, "C").End(xlUp).Row
'Add Values in Column B
For i = 1 To LastRowC
.Range("B" & i).Value = i + 1000
Next i
'Clear Column A
.Columns("A:A").Clear
End With
End Sub
dim i as integer
i = 1000
dim max as integer
max = 1000000
while i < max
begin
set i = i + 1
' do funky column editing , deleting, whatever
end

Creating a print button based on conditional criteria in Excel

So first my disclaimer. While I have some programming background, im not proficient in VB scripting so I may need some hand holding on this but I am mighty grateful for any help you wonderful people can render.
Im creating a print button that will print a worksheet based on criteria that the user will type in. Well basically I need the script to check certain cells in a row and if there is data in those cells, move to the next line. Rinse and repeat until you get to a row with no data in those certain cells and then automatically print the correct number of pages based on the data. I hope that makes sense. I hope that makes sense.
I tried writing a piece of code to check certain columns and return the value when all of those columns are blank. Hope that helps you
Sub Printing()
Dim CheckCol1 As Integer, CheckCol2 As Integer
Dim rowCount As Integer, rowCount1 As Integer, rowCount2 As Integer, currentRow As Integer
Dim currentRowValue1 As String, currentRowValue2 As String
Dim found As String
found = "No"
CheckCol1 = 1 'column A has a value of 1
CheckCol2 = 2 'column B has a value of 2
rowCount1 = Cells(Rows.Count, CheckCol1).End(xlUp).Row
rowCount2 = Cells(Rows.Count, CheckCol2).End(xlUp).Row
rowCount = Application.Max(rowCount1, rowCount2)
' find the first blank cell on both the columns
For currentRow = 1 To rowCount
currentRowValue1 = Cells(currentRow, CheckCol1).Value
currentRowValue2 = Cells(currentRow, CheckCol2).Value
If (IsEmpty(currentRowValue1) Or currentRowValue1 = "") And (IsEmpty(currentRowValue2) Or currentRowValue2 = "") Then
MsgBox ("No data on Column A and B in row" & currentRow)
found = "Yes"
End If
Next
If found = "No" Then ' This will return rowcount+1 when the columns have values throughout the range
MsgBox ("No data on Column A and B in row" & rowCount + 1)
End If
End Sub
Note:- You can increase the number of columns to be checked by adding few variables. You can try Adding third column by adding Checkcol3, rowcount3, currentrowvalue3 and adding one more condition to the if clause

calculate average of cells which depends upon another column cells

I am looking a way of creating excel vba for calculating average, depends upon another cell
In above picture, I want calculate average of those cell in column C, where A column has the name on it.In this case, average of cells C6,C7,C8 (and skip C9 and C10)because Name column (Column A) has data in only A6,A7,A8. While calculating I need to count 0 as well.
not getting a way to create formula, tried with averageif, but that only check for a specific data
can somebody give a hint to form the this vba function
Try this:
=(SUMPRODUCT(--(ISBLANK(A6:A10)=FALSE),--(C6:C10)))/COUNTA(A6:A10)
Maybe:
=AVERAGEIF(A6:A10,"<>",C6:C10)
In VBA you can try something like this:
Dim lastRowOfColA As Long
lastRowOfColA = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row 'Get last row of column A containing data
Dim rowCount As Long 'Number of rows containing data in column C
Dim sum As Long 'The sum of the values in column C
Dim i As Long
For i = 6 To lastRowOfColA
Dim valOfColA As String
valOfColA = Cells(i, 1).Value
Dim valOfColC As String
If valOfColA <> "" Then
valOfColC = Cells(i, 3).Value
If valOfColC <> "" Then
rowCount = rowCount + 1
sum = sum + valOfColC
End If
End If
Next
If rowCount > 0 Then
MsgBox ("Average: " & (sum / rowCount))
Else
MsgBox ("No rows with data found!")
End If
Of course you have to put that in a function and use parameters instead of the hard coded values above.

Move values of cell to next column if integer

I haven't used formulas in Excel before. Currently, the values of my cells are misaligned. What I would like to do is move the values of column F to column G if they are numerical values. For instance, in the 7th row that is displayed in my image, I'd like to move 48 over to the adjacent cell to the right. Same with 3054, 5770, and 32. However, I DON'T want to move IsCallOnly because it is an alphanumerical value. How would I go about doing this? Thanks!
In cell G2, try:
=IF(ISNUMBER(F2),F2,"")
This will tell is to copy the adjacent cell if it is a number, but leave the cell blank if it is not.
I suggest, in H1 and copied down:
=IF(G1="",F1,G1)
this looks to see if G1 is empty and if it is, take F1, otherwise take G1.
However, the number values in ColumnF are copied rather than moved, though it could be arranged for 'move' rather than 'copy, if required, with a bit of fiddling.
Neither requires VBA but if that is obligatory then it would help if you would post the code you have tried so far.
I think you are asking to move only the numbers in column F to column G?, if so maybe the following will help.
Sub MoveMyNumbers()
MoveNumbers "XXX", "F"
End Sub
.
Function MoveNumbers(ShtName As String, ColLetter As String)
Dim ws As Excel.Worksheet
Dim ColNumber As Integer
Dim lRow As Long
Dim i As Long
Set ws = ThisWorkbook.Sheets(ShtName)
lRow = ws.Range(ColLetter & ws.Rows.Count).End(xlUp).Row
'Get Column Number from column letter
ColNumber = ws.Range(ColLetter & "1").Column
For i = 1 To lRow
If IsNumeric(Cells(i, ColNumber).Value) Then
Cells(i, (ColNumber + 1)).Value = Cells(i, ColNumber).Value
Cells(i, ColNumber).Value = " "
End IF
Next i
End Function

Resources