I am trying to move the first instances of each value of the column "firstname" from one sheet to another. I am able to move the first instance of the first cell value from the firstname column, but I am not able to move the next and so on till the end. Below is the code I am working with at the moment.
Is there any problem with the for loops?
Option Explicit
Private Const RAW_DATA_SHEET = "UserDetails"
Private Const REPORT_SHEET = "Report"
Private Const USER_NAME_COL = "User Name"
Private Const FIRST_NAME_COL = "First Name"
Private Const LAST_NAME_COL = "Last Name"
Private Sub CommandButton1_Click()
Dim firstname As String
Dim firstnameActive As Range
Dim sheet As Worksheet
Dim sheetre As Worksheet
Dim userNameHeader As Range
Dim firstnameHeader As Range
Dim userToFindRow As Range
Dim user As String
Dim curcell As Range
Application.ScreenUpdating = False
Set sheetre = Sheets("Report")
Set sheet = Sheets("UserDetails")
For Each firstnameHeader In sheet.Range("B2" & sheet.Range("B" & sheet.Cells.Rows.Count).End(xlUp).row)
Set curcell = sheetre.Range("A3")
' Find the columns of "User Name"
Set userNameHeader = sheet.Rows(1).Find(What:=USER_NAME_COL, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False) 'note: SearchOrder:=xlByColumns
Set firstnameHeader = sheet.Rows(1).Find(What:=FIRST_NAME_COL, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False) 'note: SearchOrder:=xlByColumns
' Use to find the row number of the provided user
Set userToFindRow = sheet.Columns(userNameHeader.Column).Find(What:=user, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False) 'note: SearchOrder:=xlByRows
For Each userToFindRow In sheet.Range("E2" & sheet.Range("E" & sheet.Cells.Rows.Count).End(xlUp).row)
' Get the value of "firstname" cell for provided user
Set firstnameActive = sheet.Cells(userToFindRow.Column, firstnameHeader.Column)
If Not IsEmpty(firstnameActive) Then
curcell.Value = firstnameActive
Set curcell = curcell.Offset(1)
End If
Next userToFindRow
Next firstnameHeader
Application.ScreenUpdating = True
End Sub
why the loop is not working?
Sathak, I think you need to change your For Each Loop. Syntax of For each is we tend to search in defined range. You need to add :B & :E in both for each range to make loop work.
Check the modified code and try to use this For Each loop in your code:
First For each loop:
For Each firstnameHeader In sheet.Range("B2:B" & sheet.Range("B" & sheet.Cells.Rows.Count).End(xlUp).Row)
Second For each loop:
For Each userToFindRow In sheet.Range("E2:E" & sheet.Range("E" & sheet.Cells.Rows.Count).End(xlUp).Row)
Related
I have a working code to find a specific string in a column of a specific sheet, offset and clear the contents of a specific cell. However it only clears the first occurrence of this search and I would like to have the code work on all occurrences. Can someone help me to wrap a Loop or a FindNext around this code because I wasn't able to. Please see here below the code I already have. Thnx
Dim SearchValue6 As String 'located B9
Dim Action6 As Range 'clear
SearchValue6 = Workbooks.Open("C:\Users\.......xlsm").Worksheets("Sheet1").Range("B9").Value
On Error Resume Next
Worksheets(2).Columns("A:A").Select
Set Action6 = Selection.Find(What:=SearchValue6, After:=ActiveCell, LookIn:=xlFormulas2, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Action6 Is Nothing Then
'MsgBox "No clearings made in " & ActiveWorkbook.Name
Else
Action6.Activate
ActiveCell.Offset(0, 1).Select
ActiveCell.ClearContents
End If
Please, try using the next updated code and send some feedback:
Sub FindMultipleTimes()
Dim SearchValue6 As String 'located B9
Dim Action6 As Range 'clear
SearchValue6 = Workbooks.Open("C:\Users\.......xlsm").Worksheets("Sheet1").Range("B9").Value
Dim ws As Worksheet: Set ws = Worksheets(2)
Dim firstAddress As String
Set Action6 = ws.Columns("A:A").Find(What:=SearchValue6, After:=ws.Range("A1"), LookIn:=xlFormulas2, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not Action6 Is Nothing Then
firstAddress = Action6.address
Do
Action6.Offset(0, 1).ClearContents
Set Action6 = ws.Columns("A:A").FindNext(Action6) 'find the next occurrence
Loop While Action6.address <> firstAddress
Else
MsgBox SearchValue6 & " could not be found in column ""A:A"" of sheet " & ws.name
End If
End Sub
I only adapted your code, but do you want letting the workbook necessary to extract SearchValue6 value, open?
i am new to VBA. Task here is to find the address of a cell with respect to a variable.
i am using the find option and receiving error
Object Variable or With block variable not set
Using Find option in VBA. searching data is already available in the sheet. when I do it manually its working.
Sub updateddata()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim currentdate As Date
Dim empid As String
Dim attendance As String
Dim namerange As Range
Dim columnadd As String
Dim rowadd As Range
Dim pasterange As Range
Worksheets("MARK ATTENDANCE").Select
Range("b6").Select
Set namerange = Range(Selection, ActiveCell.End(xlDown))
Range("G5").Select
currentdate = Left(Range("g5").Value, 10)
attendance = ActiveCell.Offset(1, 0).Value
For Each cell In namerange
empid = cell.Value
If attendance = "" Then
ActiveCell.Offset(1, 0).Select
attendance = ActiveCell.Value
Else
Worksheets("Daily Attendance Tracker").Select
Range("1:1").Select
columnadd = Selection.Find(What:=currentdate, After:=ActiveCell, LookIn:=xlFormulas _
, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Address
Range("B2:B37").Select
rowadd = Selection.Find(What:=Trim(empid), After:=ActiveCell, LookIn:=xlFormulas _
, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Address
End If
Next
End Sub
I know selection is not good to use. However, I need to find a string in another sheet and need it to be selected (it can even select and change the color) so the user will able to see it.
My code is only taking me to the sheet but not to the cell where the string I need to find is.
Sub Risk1()
Dim SearchString As String
Dim SearchRange As Range, cl As Range
Dim FirstFound As String
Dim sh As Worksheet
' Set Search value
SearchString = "1."
Application.FindFormat.Clear
Sheet2.Activate
' loop through all sheets
For Each sh In ActiveWorkbook.Worksheets
' Find first instance on sheet
Set cl = sh.Cells.Find(What:=SearchString, _
After:=sh.Cells(1, 1), _
LookIn:=xlValues, _
lookat:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not cl Is Nothing Then
FirstFound = cl.Activate.cell
End If
Next
End Sub
The string that I am looking for can be in any cell of column A.
Try this. If it's in one sheet no need to loop through all of them. It's still not clear to me what happens if the value is found more than once?
Btw you don't need VBA for this, the worksheet Find will do exactly this.
Sub Risk1()
Dim SearchString As String
Dim SearchRange As Range, cl As Range
Dim FirstFound As String
Dim sh As Worksheet
' Set Search value
SearchString = "1."
Application.FindFormat.Clear
With Sheets("Over").Columns(1)
Set cl = .Find(What:=SearchString, After:=.Cells(1, 1), LookIn:=xlValues, _
lookat:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not cl Is Nothing Then Application.Goto cl 'better than select or activate and sheet does not need to be active first
End With
End Sub
1
2
3
4
.
.
So I have a sequence of numbers running from 1-20. I have the number "1" on top selected and I would like to search the entire column and find the number "9". The code works when I don't name the range "rng"; it finds the number and selects. But the code stops working when I name the range of number. What's wrong with the range function? could it be that if I define Dim rng as Range that when I later define the "Set rng=" I cannot have the ".Select" or ".Copy" extension on the end?
Sub macro2()
Dim rng As Range
Set rng = Range(ActiveCell, ActiveCell.End(xlDown)).Select
rng.Find(10).Select
End Sub
Also, If I want to sum the entire column from 1-20, on the last cell below the number "20" should I use the following code? because the application object doesn't seem to do it. Thank you!
rng.End(xlDown).Offset(1, 0).Select
Application.WorksheetFunction.Sum (rng.Value)
To look for 10 in the active column you could try this (which ends up selecting the first 10 - although Select in vba isn't normally needed other than taken the user to location at code end)
test that the found range exists (ie you can find 10 before proceeding)
you should also use xlWhole to avoid matching 100 if the current default for [lookAt] is xlPart
using search [After] as Cells(1, ActiveCell.Column , and [Search Direction] as xlNext finds the first value looking down.
code
Sub QuickFind()
Dim rng1 As Range
Set rng1 = ActiveCell.EntireColumn.Find(10, Cells(1, ActiveCell.Column), xlFormulas, xlWhole, , xlNext)
If Not rng1 Is Nothing Then
Application.Goto rng1
Else
MsgBox "10 not found"
End If
End Sub
Part 2
Sub Other()
Dim rng1 As Range
Set rng1 = Range(Cells(1, ActiveCell.Column), Cells(Rows.Count, ActiveCell.Column).End(xlUp))
rng1.Cells(rng1.Cells.Count).Offset(1, 0) = Application.WorksheetFunction.Sum(rng1.Value)
End Sub
Try this, I hope this will help u to find the specific row no as well as column name too. In code you can use
strRw = FindColumn(Sheet name, "Value which need to be found", True, "Cell Name",Row number)
sourceCOL = colname(FindColumn(Shee Name, "Value which need to be found", False, , 4))
Below is main function of find
Public Function FindColumn(colnocountWS As Worksheet, srcstr As String, Optional rowflag As Boolean, Optional bycol As String, Optional strw As Integer, Optional stcol As Integer) As Integer
Dim srcrng As Range 'range of search text
Dim srcAddr As String 'address of search text
Dim stcolnm As String
colnocountWS.Activate
If stcol <> 0 Then stcolnm = colname(stcol)
If stcol = 0 Then stcolnm = "A"
If strw = 0 Then strw = 1
colnocountWS.Range(stcolnm & strw).Select
If ActiveSheet.Range(stcolnm & strw) = srcstr Then
ActiveSheet.Range(stcolnm & strw).Select
FindColumn = 1
Else
If bycol = "" Then
Set srcrng = colnocountWS.Cells.Find(Trim(srcstr), after:=ActiveCell, LookIn:=xlValues _
, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
Else
Set srcrng = colnocountWS.Cells.Find(Trim(srcstr), after:=ActiveCell, LookIn:=xlValues _
, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
End If
'ByPart
If srcrng Is Nothing Then
If bycol = "" Then
Set srcrng = colnocountWS.Cells.Find(Trim(srcstr), after:=ActiveCell, LookIn:=xlValues _
, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
Else
Set srcrng = colnocountWS.Cells.Find(Trim(srcstr), after:=ActiveCell, LookIn:=xlValues _
, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
End If
End If
If srcrng Is Nothing Then
FindColumn = 0
Exit Function
Else
srcAddr = srcrng.Address
colnocountWS.Range(srcAddr).Select
FindColumn = ActiveCell.Column
If rowflag = True Then FindColumn = ActiveCell.Row
End If
End If
End Function
'this function find column name
Public Function colname(iFinalCol1 As Integer) As String
Dim colnm As String
On Error GoTo gg
If Mid(Cells(1, iFinalCol1).Address, 3, 1) = "$" Then
colnm = Mid(Cells(1, iFinalCol1).Address, 2, 1)
Else
colnm = Mid(Cells(1, iFinalCol1).Address, 2, 2)
End If
gg: colname = colnm
End Function
This macro runs on the click of a button. I receive an error.
Run-time error '91':
Object variable or With block variable not set
I click Debug and it leads me to this highlighted area.
Selection.Find(What:=DateString, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False).Activate
Here is the entire function
Function GetBalance(Month As Integer) As Currency
'This function is called by the Calculate_Balance subroutine. It
'finds the appropriate month's balance on an employee sheet and sends
'it back to the calling routine.
Dim DateString As String
Dim RangeString As String
Dim Balance
Dim BalDate As Date
Dim strCurrMonth As String
Dim strCurrYear As String
Dim strFirstDayCurrMonth As String
strCurrMonth = CStr(DatePart("m", Date))
strCurrYear = CStr(DatePart("yyyy", Date))
strFirstDayCurrMonth = strCurrMonth & "/1/" & strCurrYear
dtmFirstDayCurrMonth = CDate(strFirstDayCurrMonth)
DateString = Month & "/1/"
Columns("A:A").Select
Range("A6").Activate
Selection.Find(What:=DateString, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False).Activate
CurrRow = ActiveCell.Row
BalanceRow = CurrRow - 1 'Move up 1 row to get last balance for this month
RangeStr = "E" & BalanceRow
DateRangeStr = "A" & BalanceRow
BalDate = Range(DateRangeStr).Value
If BalDate <= dtmFirstDayCurrMonth Then
Balance = Range(RangeStr).Value
Else
Balance = 0
End If
GetBalance = Balance
End Function
The Find() function returns a Range object so with your code if nothing is found, you will get a error as it can not 'activate' nothing. Change the code to something like:
Dim rng As Range
Set rng = Selection.Find(What:=DateString, After:=ActiveCell, LookIn:=xlFormulas, SearchDirection:=xlNext, MatchCase:=False)
If Not (rng Is Nothing) Then
rng.Activate
End If