Autofil cell with the month number if adjacent cell contains date - excel

I'm looking for a smoother solution for below code. The task is if column O is not empty, then check if AH is empty. If AH is not empty (then it contains a date) I need to get the number of the month from this date to column AI (right next to AH).
I'm new to coding and so far the below is what I've got but this doesn't seem the perfect solution as it is simply adding the formula to and I suppose this could be also done by a loop.
Many thanks in advance.
Sub d_month()
Dim r As Range
Dim LastRow As Long
With Application.ActiveSheet
LastRow = .Cells(.Rows.Count, "O").End(xlUp).Row
For Each r In .Range("O2:O" & LastRow)
If r.Value <> "" Then
r.Offset(0, 20).Value = "=IF(RC[-1]="""","""",MONTH(RC[-1]))"
End If
Next r
End With
End Sub

There are various ways to do this. You can use Excel Formulas, Worksheet_Change or as shown below.
Few suggestions (not a hard and fast rule. Just my personal opinion).
Keep the code simple and easy to understand.
Avoid using Offset unless and until it is really important. This way you will know which cell is being handled just by looking at it. With offset, you will have to count and ensure that it is the right cell.
Use simple For Loops as shown below.
Is this what you are trying?
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long
Dim i As Long
'~~> Change this to relevant sheet
Set ws = Sheet1
With ws
lRow = .Range("O" & .Rows.Count).End(xlUp).Row
For i = 2 To lRow
'~~> Check if O and AH are not empty
If Len(Trim(.Range("O" & i).Value)) <> 0 And _
Len(Trim(.Range("AH" & i).Value)) <> 0 Then
'~~> Write to AI
.Range("AI" & i).Value = Month(.Range("AH" & i).Value)
End If
Next i
End With
End Sub

Related

How can I repeat code through entire data?

I have written a few lines of code that work like I want them too but I don't know how to repeat it through all rows of my data.
This probably seems like a rather simple thing but since I started VBA just a few days ago I struggle with this line of code
If I continue with ActiveCell.Offset(-1,-4) after my code it's a bug and I don't know how to repeat the code through all rows.
Sub SelectRowsWithNoBlanks()
Range("A2").Select
If ActiveCell.Offset(0, 0).Value <> "" And ActiveCell.Offset(0, 1) <> "" And ActiveCell(0, 1) <> "" And ActiveCell(0, 1) <> "" Then
Range(ActiveCell, Cells(ActiveCell.Row, ActiveCell.Column + 4)).Select
End If
End Sub
#SiddharthRout As I don't have Access to the data yet I can't tell. But I thought extending the code for more columns later on wouldn't be a problem. So in the code I have written now I was checking for the columns A-D but I thought I could easily add the "checking" for more columns if needed – Anna von Blohn 43 secs ago
In that case, here is a sample code.
Logic
As #Pᴇʜ mentioned avoid the use of .Select. Work with the objects.
Find the last row and loop through the rows. To find the last you you may want to see This
One way (which I am using) is to count the number of cells which are filled using Application.WorksheetFunction.CountA. So if it is columns A to D then there should be 4 cells to be filled to consider the "row" as filled. Similarly for Cols A to E, there should be 5 cells to be filled to consider the "row" as filled as so on.
Code
I have commented the code. So if you have a problem understanding it, let me know.
Option Explicit
Sub SelectRowsWithNoBlanks()
Dim ws As Worksheet
Dim lRow As Long, i As Long
Dim myRange As Range, rng As Range
'~~> Change this to the relevant sheet
Set ws = Sheet1
With ws
'~~> Find the last row in Col A
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
'~~> Loop through the rows
For i = 2 To lRow
'~~> Change this as applicable
Set rng = .Range("A" & i & ":D" & i)
'~~> Check if the range is completely filled
If Application.WorksheetFunction.CountA(rng) = rng.Columns.Count Then
'~~> Store the range in a range object
If myRange Is Nothing Then
Set myRange = rng
Else
Set myRange = Union(myRange, rng)
End If
End If
Next i
End With
'If Not myRange Is Nothing Then Debug.Print myRange.Address
'~~> Check if any filled rows were found
If Not myRange Is Nothing Then
With myRange
'
'~~> Do what you want with the range
'
End With
Else
MsgBox "No filled rows were found"
End If
End Sub

Excel VBA offset function

I have an Excel file with information in column A and column B. Since these columns could vary in the number of rows I would like to use the function offset so that I could print the formula in one time as an array rather than looping over the formula per cell (the dataset contains almost 1 million datapoints).
My code is actually working the way I want it to be I only can't figure out how to print the code in Range(D1:D5). The outcome is now printed in Range(D1:H1). Anybody familiar how to use this offset within a for statement?
Sub checkOffset()
Dim example As Range
Dim sht As Worksheet
Dim LastRow As Long
Set sht = ThisWorkbook.Worksheets("Sheet1")
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
Set example = Range("A1:A1")
For i = 1 To LastRow
example.Offset(0, i + 2).Formula = "=SUM(A" & i & ":B" & i & ")"
Next i
End Sub
Using the Offset(Row, Column), you want to offset with the increment of row (i -1), and 3 columns to the right (from column "A" to column "D")
Try the modified code below:
Set example = Range("A1")
For i = 1 To LastRow
example.Offset(i - 1, 3).Formula = "=SUM(A" & i & ":B" & i & ")"
Next i
One way of outputting the formula in one step, without looping, to the entire range, is to use the R1C1 notation:
Edit: Code modified to properly qualify worksheet references
Option Explicit
Sub checkOffset()
Dim example As Range
Dim sht As Worksheet
Dim LastRow As Long
Set sht = ThisWorkbook.Worksheets("Sheet1")
With sht
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
Set example = .Range(.Cells(1, 1), .Cells(LastRow, 1))
End With
example.Offset(columnoffset:=3).FormulaR1C1 = "=sum(rc[-3],rc[-2])"
End Sub
You don't need to use VBA for this. Simply type =sum(A1:B1) in cell D1 and then fill it down.
If you're going to use VBA anyway, use this:
Sub checkOffset()
Dim example As Range
Dim sht As Worksheet
Dim LastRow As Long
Set sht = ThisWorkbook.Worksheets("Sheet1")
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
Set example = Range("A1:A1")
For i = 1 To LastRow
example.Offset(i - 1, 3).Formula = "=SUM(A" & i & ":B" & i & ")"
Next i
End Sub
The way offset works is with row offset, column offset. You want the column to always be fixed at 3 to the right.

Can I insert a variable into a string?

I'm trying to make a program in the Excel VBA that inserts a formula into a column of cells. This formula changes based on the contents of the cell directly to the left.
This is the code I have written so far:
Sub Formula()
Dim colvar As Integer
colvar = 1
Dim Name As String
Name = "Sample, J."
Do While colvar <= 26
colvar = colvar + 1
Name = Range("B" & colvar).Value
Range("C" & colvar).Value = "='" & Name & "'!N18"
Loop
End Sub
As you can see, I want to insert the variable Name between the formula strings, but Excel refuses to run the code, giving me a "application-defined or object-defined error."
Is there a way to fix this?
You will need some error checking in case the sheets don't actually exist in the workbook.
it looks like you are looping through column B that has a list of sheet names and want range N18 to display next to it.
Something like
Sub Button1_Click()
Dim Lstrw As Long, rng As Range, c As Range
Dim Name As String
Lstrw = Cells(Rows.Count, "B").End(xlUp).Row
Set rng = Range("B1:B" & Lstrw)
For Each c In rng.Cells
Name = c
c.Offset(, 1) = "='" & Name & "'!N18"
Next c
End Sub
Or you can just list the sheets and show N18 next to it, run this code in a Sheet named "Sheet1"
Sub GetTheSh()
Dim sh As Worksheet, ws As Worksheet
Set ws = Sheets("Sheet1")
For Each sh In Sheets
If sh.Name <> ws.Name Then
ws.Cells(ws.Rows.Count, "A").End(xlUp).Offset(1) = sh.Name
ws.Cells(ws.Rows.Count, "A").End(xlUp).Offset(0, 1) = sh.Range("N18")
End If
Next sh
End Sub
Thank you to everyone for your help! I actually found that I had just made a silly error: the line Do While colvar<=26 should have been Do While colvar<26. The cells were being filled, but the error manifested because one cell was being filled by a nonexistent object.
I did decide to use the .Formula modifier rather than .Value. Thank you to Jeeped for suggesting that.

I want to concatenate the range of cells ad include commas

In one cell, I want to concatenate range of cells till the cell value become blank and also i should include commas. Please check the below code
Private Sub CommandButton1_Click()
Dim lastRow As Long
Sheets("Sheet2").Range("A2").Select
lastRow = Range(Selection, Selection.End(xlDown)).count
Range("E2").Value = Range("E2:E" & lastRow & "", "").Value
End Sub
But this code is not working. Please help on this. Many Thanks.
I think you should be using Join Function.
Something like:
With Sheets("Sheet2")
Dim lrow As Long
lrow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("E2").Value = Join(Application.Transpose(.Range("E2:E" & lrow)), ",")
End With
This will concatenate the value of E2:Ex and place it in E2. HTH.

Method range of object _global failed

I simply want to use the value in C2 to populate the rest of column C with the same value all the way to the bottom of the data in the sheet.
Sub Testfill1()
'
' Testfill1 Macro
'
'
Sheets(1).Select
lngEndRow = lastCellBlock
Range("C2:C" & lngEndRow).FormulaR1C1 = "1"
End Sub
I simply want to use the value in C2 to populate the rest of column C with the same value all the way to the bottom of the data in the sheet.
This should do what you want:
Sub FillDown()
Range("C2", "C" & rows.Count).FillDown
End Sub
If that doesnt work or doesnt answer your question let me know
This will find the last row in column C with a value and copy whatever is in C2 down to that cell.
Sub CopyDown()
Dim ws As Worksheet
Dim lastRow As Long
Set ws = ThisWorkbook.Sheets("Sheet1")
lastRow = ws.Range("C" & ws.Rows.Count).End(xlUp).Row
ws.Range("C2").Copy ws.Range("C2:C" & lastRow)
End Sub
Try below code
Sub Testfill1()
Dim lastRow As Long
With Sheets("sheet1")
lastRow = .Range("C" & .Rows.Count).End(xlUp).Row
.Range("C2:C" & lastRow).FormulaR1C1 = "1"
End With
End Sub
I simply want to use the value in C2 to populate the rest of column C with the same value all the way to the bottom of the data in the sheet.
I am interpreting "bottom of the data" to mean the extents of your data and not the absolute bottom of the worksheet (the latter being C1048576 in Excel 2007/2010/2013). It isn't clear on whether C2 contains a formula or not so that should likely be left alone and its value stuffed into the remaining cells from C3 down to the extents of the data.
Range("C3:C" & cells(rows.count, 3).end(xlUp).row) = Range("C2").value

Resources