For 2 to LastRow - not working - excel

It's like it doesn't read LastRow as a Number! Help!! this is my code:
Sub DD()
Dim rNum As Long
Dim LastRow As Long
LastRow = ActiveSheet.Range("A1").End(xlDown).Rows.Count
For rNum = 2 To LastRow
Select Case Range("D" & rNum).Value
Case "FXD"
Range("P" & rNum).FormulaR1C1 = "= RC[-13]"
Case Else
Range("P" & rNum).Value = -4
End Select
Next rNum
End Sub

Change this line:
LastRow = ActiveSheet.Range("A1").End(xlDown).Rows.Count
to this:
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlup).Row
You wanted Row rather than Rows.Count (which would always be 1 since you were referring to one cell) and it's generally better to go up from the bottom of the sheet, rather than down.

Related

Select the first n values of columns in a row without using select

Hey I just found a great code on this site which allows you to dynamically select the n bottom values of columns in a row. with the following code:
Dim LastRow, a As Long
LastRow = Cells(Rows.Count, "K").End(xlUp).Row
Range("K" & LastRow - 2 & ":K" & LastRow).Copy
My code above selects the 2 values at the bottom. Is there any way I can select the two top values of columns in a cell? I tried to do it brainless by modifying my code to
Dim LastRow, a As Long
firstRow = Cells(Rows.Count, "K").End(xlDown).Row
Range("K" & firstRow + 2 & ":K" & firstRow).Copy
However, that doesn't seem to do the job. Furthermore, in my row columns where I want to select the first 10 values there is a string/text above, how do I deal with that?
Dim Firstrow As Long
Dim RowsToCopy As Long
' First row is 2 if there is a header text, else 1.
Firstrow = 2
RowsToCopy = 2
' Copy 2 rows starting at 'Firstrow'
Range("K" & Firstrow & ":K" & Firstrow + (RowsToCopy - 1)).Copy
Please, try the next way:
Sub testFirstTwoRows()
Dim sh As Worksheet, firstR As Long
Set sh = ActiveSheet
firstR = sh.Range("K1").End(xlDown).row
If WorksheetFunction.CountA(sh.Range("K1:K" & firstR - 1)) > 0 Or _
firstR = sh.rows.count Then
firstR = 1
End If
Range("K" & firstR & ":K" & firstR + 1).Copy
End Sub

How to insert a specific value at the beginning of text in a Column using Excel VBA?

I'm trying to insert this character "-" at the beginning of each text in column F.
My F column looks like this:
BP850
BP851
BT100
GP160
GP161
I tried this code:
Option Explicit
Sub test()
Dim LastRow As Long, i As Long
Dim str As String
'Change sheet if needed
With ThisWorkbook.Worksheets("Sheet1")
'Find the last row of column F
LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row
'Loop column F
For i = 1 To LastRow
'Replace the first occurance
str = Replace(.Range("F" & i).Value, "", "-", 1, 1)
.Range("F" & i).Value = str
Next i
End With
End Sub
I expect:
-BP850
-BP851
-BT100
-GP160
-GP161
As an alternative, you could try to utilize .Evaluate. This prevents the need for any loop:
Option Explicit
Sub test()
Dim LastRow As Long
Dim rng As Range
'Change sheet if needed
With ThisWorkbook.Worksheets("Sheet1")
'Find the last row of column F
LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row
Set rng = .Range("F1:F" & LastRow)
rng.Value = .Evaluate("""'-""&" & rng.Address)
End With
End Sub
Instead of using replace, just concatenate "-" before str
Sub test()
Dim LastRow As Long, i As Long
Dim str As String
'Change sheet if needed
With ThisWorkbook.Worksheets("Sheet1")
'Find the last row of column F
LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row
'Loop column F
For i = 1 To LastRow
'Replace the first occurance
str = "-" & .Range("F" & i).Value '<== EDIT
.Range("F" & i).Value = str
Next i
End With
End Sub
Your str = Replace(.Range("F" & i).Value, "", "-", 1, 1) has problem. Change it to following:
For i = 1 To LastRow
.Range("F" & i).Value = "-" & .Range("F" & i).Value
Next i
No need to use str variable here.
See if following approach helps.
It will also check
Cell is not blank
Cell doesn't begin with "-"
which should help in case of accidental rerun of the macro!
Option Explicit
Sub test2()
Dim LastRow As Long, i As Long
'Change sheet if needed
Application.ScreenUpdating = False
With ThisWorkbook.Worksheets("Sheet1")
'Find the last row of column F
LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row
'Loop column F
For i = 1 To LastRow
If Len(.Range("F" & i).Value) > 0 And Left(.Range("F" & i).Value, 1) <> "-" Then _
.Range("F" & i).Value = "-" & .Range("F" & i).Value
Next i
End With
Application.ScreenUpdating = True
End Sub
try this, ie. add "'-" in front of the value. Note the single quote before the -
For i = 1 To lastRow
If .Range("F" & i).Value <> "" Then
If Left(.Range("F" & i).Value, 1) <> "-" Then
.Range("F" & i).Value = "'-" & .Range("F" & i).Value
End If
End If
Next i
Option Explicit
Sub test()
Dim LastRow As Long, i As Long
Dim AdditionString As String, CellString As String, CompleteString As String
AdditionString = "'-"
With ThisWorkbook.Worksheets("Sheet1")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
For i = 1 To LastRow
CellString = .Range("A" & i).Value
CompleteString = AdditionString & CellString
.Range("A" & i).Value = CompleteString
Next i
End With
End Sub

identify the last used cell and paste below

I'm a total novice with VBA. I have the following code which does a matching exercise and then pastes the relevant values into col. B. my issue is each time the code is used the col will change how can I add this to the module so that it looks for the last cell used in row 1 and pastes the values below.
Sub TransferData()
Dim i As Long, j As Long, lastrow1 As Long, lastrow2 As Long
Dim myname As String
Application.ScreenUpdating = False
lastrow1 = Sheets("Input Sheet").Range("B" & Rows.Count).End(xlUp).Row
For i = 2 To lastrow1
myname = Sheets("Input Sheet").Cells(i, "B").Value
Sheets("Data").Activate
lastrow2 = Sheets("Data").Range("A" & Rows.Count).End(xlUp).Row
For j = 2 To lastrow2
If Sheets("Data").Cells(j, "A").Value = myname Then
Sheets("Input Sheet").Activate
Sheets("Input Sheet").Cells(i, "c").Copy
Sheets("Data").Activate
Sheets("Data").Cells(j, "B").Select
ActiveSheet.PasteSpecial
End If
Next j
Application.CutCopyMode = False
Next i
Application.ScreenUpdating = True
End Sub
any assistance with this would be appreciated.
You can replace your second For j = 2 To lastrow2 with the Match function.
Also, there is no need to Activate the sheets back and fourth all the time, just use fully qualified Ranges instead.
Code
Option Explicit
Sub TransferData()
Dim i As Long, j As Long, lastrow1 As Long, lastrow2 As Long
Dim myname As String
Dim MatchRng As Range
Application.ScreenUpdating = False
j = 2
With Sheets("Input Sheet")
lastrow1 = .Range("B" & .Rows.Count).End(xlUp).Row
' the 2 lines bellow should be outisde the loop
lastrow2 = Sheets("Data").Range("A" & Sheets("Data").Rows.Count).End(xlUp).Row
Set MatchRng = Sheets("Data").Range("A2:A" & lastrow2)
For i = 2 To lastrow1
myname = .Range("B" & i).Value
If Not IsError(Application.Match(myname, MatchRng, 0)) Then '<-- if successful Match
Sheets("Data").Range("B" & j).Value = .Range("C" & i).Value
j = j + 1
End If
Application.CutCopyMode = False
Next i
End With
Application.ScreenUpdating = True
End Sub

Search and extract between workbooks

I'm trying to use the following code to search one cell in each row. If the search value matches a portion of the cell in that row, the entire row is copied and added to the end of another range in another workbook.
Sub GetRowsWithMatchingDates ()
Dim toThisWorkSheet As Worksheet, fromSourceWorkbook As Workbook
Dim NextFreeRow As Long
Dim LastRow As Long
Dim currentRowDate As String
Dim currentRow As Long
Dim TodaysDateAsString As String
Dim currentRowDate As String
TodaysDateAsString = 20150320
Set toThisWorkSheet = ThisWorkbook.Sheets("ImportedData")
NextFreeRow = toThisWorksheet.Range("A" & Rows.Count).End(xlUp).Row + 1
Set fromSourceWorkbook = Workbooks.Open(ThisWorkbook.Path & "JUIDTesting.xlsb")
With fromSourceWorkBook.Sheets("DataToBeSearched")
For i = 1 to To LastRow
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
currentRowDate = Mid(toThisWorkbook.Range("B" & i + 1).Value, 3, 8)
currentRow = .Range("A" & i + 1).Row
If TodaysDateAsString = currentRowDate Then
currentRow.Copy
toThisWorkbook.Range("A" & LastRow + 1).PasteSpecial xlPasteValues
Endif
Next i
End With
fromSourceWorkBook.Close False
End Sub
`
I'm just beginning to use for and with and copy paste code so this could be totally jacked up.
lastrow needs to be before your loop, right now it is undefined and defaults to 0. So you are doing a for i = 1 to 0 esentially.
it should be
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 1 to To LastRow
currentRowDate = Mid(toThisWorkbook.Range("B" & i + 1).Value, 3, 8)
currentRow = .Range("A" & i + 1).Row
If TodaysDateAsString = currentRowDate Then
currentRow.Copy
toThisWorkbook.Range("A" & LastRow + 1).PasteSpecial xlPasteValues
Endif
Next i
That would correct your first problem.
Your second problem is that toThisWorkbook is not defined anywhere + it is in a with from source workbook, and you do not have a worksheet defined.
Would need to be something like
ThisWorkbook.toThisWorkSheet.Range("A" & LastRow + 1).PasteSpecial xlPasteValues
but also keep in mind that will just keep overwriting the same row because that is what you told it to do. lastrow + 1 = will always be the same constant.

macro to create multiple sub totals in one column

Can anyone help me with this macro to create multiple sub totals in one column? Any help would be great. I have a group of numbers in column Y. which begins at row 16.
The data is listed on every three lines until the end of that section then there is a gap of around thirty lines then it beings again. I want to create a macro to count how many numbers >45 in each section. Put the total 2 rows below the last data point of each section. In column X on the same row place Number>45
Sub Sample()
Dim result As Long, firstrow As Long, lastrow As Long
Dim ws As Worksheet
Dim rng As Range
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> Find Lastrow in Col Y
lastrow = .Range("Y" & .Rows.Count).End(xlUp).Row
'~~> Set First row
firstrow = 16
'~~> Set your range
Set rng = .Range("Y" & firstrow & ":Y" & lastrow)
'~~> Put relevant values
.Range("x" & lastrow + 2).Value = "Total>45"
.Range("y" & lastrow + 2).Value = _
Application.WorksheetFunction.CountIf(rng, ">45")
End With
End Sub
try the below procedure
and loop backwards to ROW=1 like this:
Sub setTotals()
Dim iRow As Integer
Dim iLastRow As Integer
Dim sFormulaTargetAddress As String
iLastRow = ActiveSheet.Range("Y" & ActiveSheet.Rows.Count).End(xlUp).Row
iRow = iLastRow
Do Until iRow = 1
If Range("Y" & iRow).Value <> "" Then
'
' define the section
sFormulaTargetAddress = "Y" & Range("Y" & iRow).End(xlUp).Row & ":Y" & iRow & ""
'
' Put in the COUNTIF > 45 of the current section...
'
Range("Y" & iRow + 2).Formula = "=COUNTIF(" & sFormulaTargetAddress & ","">45"")"
' '
'Range("X" & iRow + 2).Formula = "=COUNTIF(" & sFormulaTargetAddress & ","">45"")"
Range("X" & iRow + 2).value="Numbers > 45"
'
' find the next section
iRow = Range("Y" & iRow).End(xlUp).Row
If Range("Y" & iRow) <> "" Then iRow = Range("Y" & iRow).End(xlUp).Row
Else
iRow = Range("Y" & iRow).End(xlUp).Row
End If
Loop
End Sub
HTH
Philip

Resources