For Each Loop Isn't Functioning, VBA - excel

This is a silly question, but I can't seem to find the issue with the code after a lot of hunting. I'm creating a For Each loop that finds all incidences of "Friday," goes over to the cell 6 columns over from "Friday" (under the "Overtime" heading), inserts the number 0 in that cell, and changes the number format. Here is my worksheet so far.
Here is my code:
Sub Calendar_Generator()
Dim WS As Worksheet
Dim MyInput As String
Dim StartDay As Date
Dim Sp() As String
Dim a As Integer
Dim R As Long
Dim Match As Range
Dim b As Variant
Dim DayNames() As String
Dim FirstAddress As String
Dim DeleteDays As Range
Dim c As Variant
Dim Day1 As Range
Dim WorkDays As Range
Dim d As Variant
'Dim Fri As Range
Set WS = ActiveWorkbook.ActiveSheet
WS.Range("A1:R100").Clear
'This loop is crashing excel
'Do
MyInput = InputBox("Enter the start date for the Calendar:")
'If MyInput = "" Then Exit Sub
'Loop While Not IsDate(MyInput)
' repeat if entry isn't recognized as a date
' Set the date value of the beginning of inputted month.
' -- regardless of the day the user entered, even if missing
StartDay = DateSerial(Year(CDate(MyInput)), Month(CDate(MyInput)), 1)
'Set headers
Range("a1").Value = Format(StartDay, "mmmm") & " Time Sheet"
Sp = Split("Day,Date,Time In,Time Out,Hours,Notes,Overtime", ",")
For a = 0 To UBound(Sp)
WS.Cells(2, 1 + a).Value = Sp(a)
Next a
' fill the days for the selected month
' == the last day of a month is always the day before the first of the next
' here deducting 2 to count from 0
For R = 0 To Day(DateAdd("m", 1, StartDay) - 2)
With WS.Cells(3 + R, 2)
.Value = StartDay + R
.NumberFormat = "d-mmm"
.Offset(, -1).Value = StartDay + R
.Offset(, -1).NumberFormat = "dddd"
End With
Next R
ReDim DayNames(1)
'To add more headers, change statement to 3
DayNames(0) = "Saturday"
DayNames(1) = "Sunday"
For b = LBound(DayNames) To UBound(DayNames)
Set Match = WS.Cells.Find(What:=DayNames(b), LookIn:=xlValues, _
lookat:=xlWhole, searchorder:=xlByRows, searchdirection:=xlPrevious, _
MatchCase:=True, SearchFormat:=False)
If Not Match Is Nothing Then
FirstAddress = Match.Address
Do
Match.EntireRow.Clear
'Highlight cell containing table heading in green
Set Match = WS.Cells.FindNext(Match)
Loop While Not Match Is Nothing
End If
Next b
Set DeleteDays = Range("A3:A50")
For Each c In DeleteDays
If c = "" Then
c.EntireRow.Delete
End If
Next c
'Works for some reason if it's executed twice
Set DeleteDays = Range("A3:A50")
For Each c In DeleteDays
If c = "" Then
c.EntireRow.Delete
End If
Next c
'Insert and format template time values with formula for hours worked in E3
Set Day1 = Range("B3")
Range(Day1, Day1.End(xlDown)).Select
With Selection
Selection.Offset(, 1).Value = "8:00 AM"
Selection.Offset(, 1).NumberFormat = "h:mm AM/PM"
Selection.Offset(, 2).Value = "4:00 PM"
Selection.Offset(, 2).NumberFormat = "h:mm AM/PM"
Selection.Offset(, 3).Value = "0"
Selection.Offset(, 3).NumberFormat = "h:mm"
Day1.Offset(, 3).Formula = "=D3-C3"
End With
'Fill in hours worked formula
Day1.Offset(, 3).Select
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown))
'*This is the loop that isn't functioning, but also isn't calling any errors*
'Set Overtime calculation
Set WorkDays = Range("A3:A33")
For Each d In WorkDays
If d = "Friday" Then
d.Offset(, 6).Value = "0"
d.Offset(, 6).NumberFormat = "h:mm"
End If
Next d
End Sub
I've had some trouble with loops crashing Excel since I switched to Excel 365, but this For Each loop isn't crashing it. Any ideas as to why this For Each loop isn't doing its job?

Related

Excel VBA - Find a value and place in a different sheet

I am an absolute novice trying to make a macro that takes an item from cell A2 in sheet "WHO", assigns the value from cell B2 from the same sheet. Inserts a new column in sheet "BO" with name from cell B1 of sheet "WHO". Finds a match of the item from cell A2/ sheet "WHO" in sheet "BO", checks the quantity corresponding to the item, if it is equal to the value of cell B2 from sheet "WHO" and puts it in the new column if not, puts the found quantity of value from sheet "WHO" and continues to search for the next match of an item until you have distributed all the pieces. Now even I was confused, so I attach the code that I managed to assemble from different places :)
Sub BO_WHO_Format()
Dim I As Integer
Dim rngFound As Range, strFirst, Name As String
Dim pNum, vNum, lr As Long
Name = Worksheets("WHO").Range("B1")
lr = Worksheets("WHO").Cells(Rows.Count, "A").End(xlUp).Row ' Find the last row with data in column A..
With Worksheets("BO").Columns(16)
Application.CutCopyMode = FALSE
Sheets("BO").Select
Columns("AC:AC").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("AC1").Select
ActiveCell.FormulaR1C1 = "На път"
Range("AC2").Value = Name
For I = 2 To lr
strFirst = "" 'Clear the value assigned to strFirst.
Dim Check As Boolean, Counter As Long, Total As Long
Check = False: Counter = 0: Total = 0 ' Initialize variables.
Do ' Outer loop.
pNum = Sheets("WHO").Range("A" & I).Value
vNum = Sheets("WHO").Range("B" & I).Value
If IsNumeric(pNum) Then pNum = Val(pNum)
If IsNumeric(vNum) Then vNum = Val(vNum)
Set rngFound = .Find(what:=pNum, LookAt:=xlWhole, SearchDirection:=xlNext, After:=.Cells(1), MatchCase:=False)
If rngFound Is Nothing Then
MsgBox "Номер " & pNum & " не е намерен! Проверете и започнете отново!"
Sheets("BO").Select
Columns("AB:AB").Select
Selection.Delete Shift:=xlToLeft
Exit Sub
ElseIf rngFound.Offset(, 11).Value = 0 Then GoTo NextIteration 'If value is 0
MsgBox "Виж си кода за грешки"
ElseIf rngFound.Offset(, 11).Value >= vNum Then 'If value is the same
rngFound.Offset(, 13) = vNum
Else
rngFound.Offset(, 13) = rngFound.Offset(, 11).Value
Counter = Counter + rngFound.Offset(, 11).Value ' Increment Counter.
NextIteration:
strFirst = rngFound.Address ' Assign the address of the first item found, so code will know if it has finished looking.
Do While Counter < vNum ' Inner Loop
Total = vNum - Counter
Set rngFound = .FindNext(rngFound)
If Not rngFound Is Nothing And strFirst <> rngFound.Address Then 'strFirst = rngFound.Address ' Assign the address of the first item found, so code will know if it has finished looking.
If rngFound.Offset(, 11).Value = 0 Then GoTo NextError
If rngFound.Offset(, 11).Value <= Total Then
rngFound.Offset(, 13) = rngFound.Offset(, 11).Value
Counter = Counter + rngFound.Offset(, 11).Value ' Increment Counter.
Else
rngFound.Offset(, 13) = Total
Counter = Counter + rngFound.Offset(, 11).Value ' Increment Counter.
End If
Else
NextError:
MsgBox "Номер " & pNum & " не е намерен! Проверете и започнете отново!"
Sheets("BO").Select
Columns("AB:AB").Select
Selection.Delete Shift:=xlToLeft
Exit Sub
End If
Loop ' Inner Loop
End If
Loop Until Check = FALSE ' Exit outer loop immediately.
Next I
End With
End Sub
If the number is not found, the quantity in the sheet "WHO" is greater than the sheet "BO" to delete the newly created column in the sheet "BO" and the macro to terminate with a message. There are no duplicate item in a sheet "WHO", unlike the "BO" sheet.
But I'm totally stuck, please help.
sheet "WHO"
sheet "BO"
I hope I understood all what you need. Have a try of the code:
Option Explicit
Sub BO_WHO_Format()
'worksheets
Dim boSht As Worksheet, whoSht As Worksheet
Set boSht = ThisWorkbook.Sheets("BO")
Set whoSht = ThisWorkbook.Sheets("WHO")
'search ranges
Dim boRange As Range, boCell As Range, whoRange As Range, whoCell As Range
With boSht
'column A, starting from 2-d row
Set boRange = Range(.Cells(2, 1), .Cells(Rows.Count, 1).End(xlUp))
End With
With whoSht
'column P,starting from 2-d row
Set whoRange = Range(.Cells(2, 16), .Cells(Rows.Count, 16).End(xlUp))
End With
'other variables
Dim hasMatch As Boolean
Dim row As Long
'taking each value in column A of the WHO sheet
For Each whoCell In whoRange
'and comparing to each values in column P of the BO sheet
For Each boCell In boRange
If whoCell = boCell Then
row = boCell.row
If Not hasMatch Then
'set the AB column name of the sheet BO as like the name of column B of the WHO sheet
boSht.Cells(1, 28) = whoSht.Cells(1, 2)
hasResult = True
End If
'if value from column B of the sheet WHO equals to value from column AA of the sheet BO
If whoCell.Offset(0, 1).Value = boSht.Cells(row, 27).Value Then
'put this value to column AB
boSht.Cells(row, 28).Value = whoCell.Offset(0, 1).Value
Else
'otherwise if value is not 0
If Not boSht.Cells(row, 27).Value = 0 Then
'put the value from column AA to column AB
boSht.Cells(row, 28).Value = boSht.Cells(row, 27).Value
End If
End If
End If
Next
Next
'check whether there is a match
If Not hasMatch Then
boSht.Cells(1, 28) = ""
MsgBox "No matches!", vbInformation, "Result"
End If
End Sub
See comments in code, in case something is not exactly what you wanted - I pointed an idea, so you can modify it for your needs.

Type mismatch error in loop that adds numbers incrementally in column

I'm creating a sub that creates a time sheet for a specific month/year. The code is based on this Microsoft example code. The Microsoft code creates this calendar. I'm amending the code to insert the days of the week in a single column, like this.
My amended code correctly inserts the number 1 in the cell corresponding to the first day of the month, but the loop to add the subsequent day numbers does not work; Cell.Value = Cell.Offset(-1, 0).Value + 1 gives a Type Mismatch Error. Here is my amended code:
Sub Calendar_Genorator1()
Dim WS As Worksheet
Dim MyInput As Variant
Dim StartDay As Variant
Dim DayofWeek As Variant
Dim CurYear As Variant
Dim CurMonth As Variant
Dim FinalDay As Variant
Dim Cell As Range
Dim RowCell As Long
Dim ColCell As Long
Set WS = ActiveWorkbook.ActiveSheet
MyInput = InputBox("Type in Month and year for Calendar ")
If MyInput = "" Then Exit Sub
' Get the date value of the beginning of inputted month.
StartDay = DateValue(MyInput)
' Check if valid date but not the first of the month
' -- if so, reset StartDay to first day of month.
If Day(StartDay) <> 1 Then
StartDay = DateValue(Month(StartDay) & "/1/" & Year(StartDay))
End If
' Prepare cell for Month and Year as fully spelled out.
'Range("B3").NumberFormat = "d-mmmm"
'Set headers
Range("a1").Value = Application.Text(MyInput, "mmmm") & " Time Sheet"
Range("a2") = "Day"
Range("b2") = "Date"
Range("c2") = "Time In"
Range("d2") = "Time Out"
Range("e2") = "Hours"
Range("f2") = "Notes"
Range("g2") = "Overtime"
'Set weekdays
Range("a3") = "Sunday"
Range("a4") = "Monday"
Range("a5") = "Tuesday"
Range("a6") = "Wednesday"
Range("a7") = "Thursday"
Range("a8") = "Friday"
Range("a9") = "Saturday"
DayofWeek = Weekday(StartDay)
' Set variables to identify the year and month as separate variables.
CurYear = Year(StartDay)
CurMonth = Month(StartDay)
' Set variable and calculate the first day of the next month.
FinalDay = DateSerial(CurYear, CurMonth + 1, 1)
' Place a "1" in cell position of the first day of the chosen month based on DayofWeek.
Select Case DayofWeek
Case 1
Range("b3").Value = 1
Case 2
Range("b4").Value = 1
Case 3
Range("b5").Value = 1
Case 4
Range("b6").Value = 1
Case 5
Range("b7").Value = 1
Case 6
Range("b8").Value = 1
Case 7
Range("b9").Value = 1
End Select
'Loop through range b3:b44 incrementing each cell after the "1" cell.
For Each Cell In Range("b3:b44")
RowCell = Cell.Row
ColCell = Cell.Column
' Do if "1" is in column B or 2.
If Cell.Row = 1 And Cell.Column = 2 Then
' Do if current cell is not in 1st column.
ElseIf Cell.Row <> 1 Then
If Cell.Offset(-1, 0).Value >= 1 Then
Cell.Value = Cell.Offset(-1, 0).Value + 1 'Type Mismatch Error here
' Stop when the last day of the month has been entered.
If Cell.Value > (FinalDay - StartDay) Then
Cell.Value = ""
' Exit loop when calendar has correct number of days shown.
Exit For
End If
End If
End If
Next
End Sub
I changed the parameters in the loop to work inserting the days incrementally in column B, and I suspect the error is related to that. Any ideas as to why I'm getting an error for Cell.Value = Cell.Offset(-1, 0).Value + 1?
Monthly Calendar
Option Explicit
Sub Calendar_Genorator1()
Const TitleAddress As String = "A1"
Const HeadersAddress As String = "A2"
Const DaysAddress As String = "A3"
Dim Headers As Variant
Headers = Array("Day", "Date", "Time In", "Time Out", "Hours", _
"Notes", "Overtime")
Dim MyInput As Variant, StartDay As Variant
MyInput = InputBox("Type in setMonth and year for Calendar ")
If MyInput = "" Then Exit Sub
' Get the date value of the beginning of inputted Month.
StartDay = DateValue(MyInput)
' Check if valid date but not the first of the Month
' -- if so, reset StartDay to first day of Month.
If Day(StartDay) <> 1 Then
StartDay = DateValue(Month(StartDay) & "/1/" & Year(StartDay))
End If
Dim ws As Worksheet
Set ws = ActiveWorkbook.ActiveSheet
' Write title.
ws.Range(TitleAddress).Value = Application.Text(StartDay, "mmmm") _
& " Time Sheet"
' Write headers.
ws.Range(HeadersAddress).Resize(, UBound(Headers)) = Headers
' Write days.
Dim Target As Variant
Target = getDDDD_D_US(Month(StartDay), Year(StartDay))
ws.Range(DaysAddress).Resize(UBound(Target), UBound(Target, 2)).Value = Target
End Sub
Function getDDDD_D_US(setMonth As Long, setYear As Long)
Dim DaysData As Variant
DaysData = Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", _
"Friday", "Saturday")
Dim Result As Variant
ReDim Result(1 To 42, 1 To 2)
' Write DDDD column.
Dim i As Long, j As Long, k As Long
For i = 1 To 6
k = (i - 1) * 7 + 1
For j = 0 To 6
Result(k + j, 1) = DaysData(j)
Next j
Next i
' Write D column.
Dim Current As Date
Current = DateSerial(setYear, setMonth, 1)
i = Weekday(Current)
For i = i To i + 27
Result(i, 2) = Day(Current)
Current = Current + 1
Next i
For i = i To i + 2
If Month(Current) = setMonth Then
Result(i, 2) = Day(Current)
Current = Current + 1
End If
Next i
getDDDD_D_US = Result
End Function

Merge cells with same year in a row

I need to merge the cells one above the months.
Cells Should be merged from 01 to 12 showing year in cell.
Look for the picture for more clarification.
I have below code, but which show months after run in cell row1.
My idea is to convert above cells to years through vba and apply merge same year at the end.
which is shown in desired output.
Note.
ROW 4 and 5 are just my thinking, which will help year to merge.
Dim a(), i As Long, j As Long, m As Long, x As Range
With Range("b1:qaz1")
.MergeCells = False
.ClearContents
a() = .Offset(1).Value
m = Month(a(1, 1))
j = UBound(a, 2)
Set x = .Cells(1)
For i = 2 To j
If m <> Month(a(1, i)) Or i = j Then
With Range(x, .Cells(i - IIf(i = j, 0, 1)))
.MergeCells = True
.HorizontalAlignment = xlCenter
End With
x.Value = Format(DateSerial(2000, m, 1), "MMMM")
m = Month(a(1, i))
Set x = .Cells(i)
End If
Next
End With
End Sub
After running new program output look like
Since you have true dates in your caption row the month and year can be extracted from there. However, the code below converts dates that might have been created using formulas to hard dates before processing them.
Sub MergeCaptionsByYear()
' 031
Const CapsRow As Long = 1 ' change to suit
Const StartClm As Long = 2 ' change to suit
Dim Rng As Range ' working range
Dim Tmp As Variant ' current cell's value
Dim Cl As Long ' last used column
Dim Cstart As Long ' first column in Rng
Dim C As Long ' working column
Dim Yr As Integer ' year
Cl = Cells(CapsRow, Columns.Count).End(xlToLeft).Column
Range(Cells(CapsRow, StartClm), Cells(CapsRow, Cl)).Copy
Cells(CapsRow, StartClm).PasteSpecial xlValues
Application.CutCopyMode = False
C = StartClm - 1
Application.DisplayAlerts = False
Do
Tmp = Cells(CapsRow, C + 1).Value
If Not IsDate(Tmp) And (C <> Cl) Then
MsgBox "Cell " & Cells(CapsRow, C + 1).Address(0, 0) & _
" doesn't contain a date." & vbCr & _
"This macro will be terminated.", _
vbInformation, "Invalid cell content"
Exit Do
End If
If (Yr <> Year(CDate(Tmp))) Or (C = Cl) Then
If Yr Then
Set Rng = Range(Cells(CapsRow, Cstart), _
Cells(CapsRow, C))
With Rng
.Merge
.HorizontalAlignment = xlCenter
.NumberFormat = "yyyy"
End With
SetBorder Rng, xlEdgeLeft
SetBorder Rng, xlEdgeRight
End If
If C > (Cl - 1) Then Exit Do
Cstart = C + 1
Yr = Year(Tmp)
End If
C = C + 1
Loop
Application.DisplayAlerts = True
End Sub
Private Sub SetBorder(Rng As Range, _
Bord As XlBordersIndex)
' 031
With Rng.Borders(Bord)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlMedium ' xlThin
End With
End Sub
Assuming the months range is "B5:AH5"
Sub test()
Dim monthsRng As Range
Set monthsRng = Range("B5:AH5")
monthsRng.Cells(1, 1).Offset(-1, 0).Select
For j = 1 To Int((monthsRng.Cells.Count / 12) + 2)
If ActiveCell.Offset(1, 0) <> 0 Then
For i = 1 To 12
ActiveCell.Value = Year(ActiveCell.Offset(1, 0))
If Year(ActiveCell.Offset(1, i)) = ActiveCell Then
Selection.Resize(1, i + 1).Select
Else
Exit For
End If
Next
With Selection
.HorizontalAlignment = xlCenter
.MergeCells = True
End With
Selection.Offset(0, 1).Select
Else
Exit For
End If
Next
End Sub
Replacing the inner for loop with below code will work irrespective of whether the dates in the Range("B5:AH5") in above procedure are formatted as dates or not.
For i = 1 To 12
ActiveCell.Value = Right(Format(ActiveCell.Offset(1, 0), "DD.MM.YYYY"), 4)
If Right(Format(ActiveCell.Offset(1, i), "DD.MM.YYYY"), 4) = Format(ActiveCell, Text) Then
Selection.Resize(1, i + 1).Select
Else
Exit For
End If
Next
However, in any case you need to format the output in excel as number (without 1000 separator and decimal places) and not date.

Find a string within a range and set cell address as new range

I am trying to search for a string within a sheet and return the cell address so that I can use that address to populate adjacent cells with info. My problem is with setting "Daycell" as the cell reference, can anyone see where I am going wrong?
Private Sub Enter_Click()
Dim FindWor As Range
Dim Findrng As String
Dim FindRowNumber As Long
Dim i As Integer
Dim frq As String
Dim wkday As String
Dim nwday As String
Dim Mnth As String
Dim Daycell As Range
Dim entryno As String
Dim Dayno As String
frq = Me.No1
'Date from userform
Findrng = Me.Date1
'Reoccuring interval from userform
If Not Me.Freq1 = "No" Then
Do While i < Me.No1
'This part adds the title and the detail to a data sheet with 3 possible entries per day
With Worksheets("Data").Range("$A:$A")
Set FindWor = .Find(What:=CDate(Findrng))
FindRowNumber = FindWor.Row
'Checks for the 1st empty row and populates
If .Cells(FindRowNumber, 2) = "" Then
.Cells(FindRowNumber, 2).Value = Me.Event1
.Cells(FindRowNumber, 3).Value = Me.Details1
entryno = 1
ElseIf .Cells(FindRowNumber, 4) = "" Then
.Cells(FindRowNumber, 4).Value = Me.Event1
.Cells(FindRowNumber, 5).Value = Me.Details1
entryno = 2
ElseIf .Cells(FindRowNumber, 6) = "" Then
.Cells(FindRowNumber, 6).Value = Me.Event1
.Cells(FindRowNumber, 7).Value = Me.Details1
entryno = 3
End If
'This part is to enter the detail part into the cell within the correct monthly tab as a comment
Mnth = (Month((CDate(Findrng))))
Mnth = MonthName(Mnth, True)
With Worksheets(Mnth).Range("$A:$Z")
Dayno = Day(CDate(Findrng))
Set Daycell = .Find(What:=Dayno, LookIn:=xlValues, Lookat:=xlWhole, _
MatchCase:=False, SearchFormat:=False)
'This is where I think my issue is as I want the comment to be in the cell below the day number (the days are displayed as day number only
.Cell(Daycell).Offset (1)
'I am not sure if this will work, I want the comment to go into the corresponding cell as stated by the entryno that is created above
If .Cells(Daycell) = "" Then
Range(Daycell).NoteText Text:=Me.Details1.Value
Else: .Cell(Daycell).Offset (entryno)
End If
End With
'this part then loops based upon the frq and the no1 from the userform
If Me.Freq1 = "Daily" Then
Findrng = Findrng + 1
ElseIf Me.Freq1 = "Weekly" Then
Findrng = Findrng + 7
ElseIf Me.Freq1 = "Bi-Weekly" Then
Findrng = Findrng + 14
'the parts below check for the correct working day
ElseIf Me.Freq1 = "Monthly" Then
wkday = Format(CDate(DateAdd("M", 1, (CDate(Findrng)) + 1)), "MM/DD/YYYY")
bday = DateAdd("D", -1, ((Format(wkday, "DD/MM/YYYY"))))
nwday = CDate(Application.WorksheetFunction.WorkDay(wkday, -1))
Findrng = bday
ElseIf Me.Freq1 = "Quaterly" Then
wkday = CDate(Format(DateAdd("M", 3, (CDate(Findrng))) + 1, "MM/DD/YYYY"))
bday = DateAdd("D", -1, ((Format(wkday, "DD/MM/YYYY"))))
nwday = CDate(Application.WorksheetFunction.WorkDay(wkday, -1))
Findrng = bday
ElseIf Me.Freq1 = "6 Monthly" Then
wkday = CDate(Format(DateAdd("M", 6, (CDate(Findrng))) + 1, "MM/DD/YYYY"))
bday = DateAdd("D", -1, ((Format(wkday, "DD/MM/YYYY"))))
nwday = CDate(Application.WorksheetFunction.WorkDay(wkday, -1))
Findrng = bday
' Findrng = FindRowNumber + ((CDate(bday) - CDate(Findrng)))
ElseIf Me.Freq1 = "Yearly" Then
wkday = CDate(Format(DateAdd("M", 12, (CDate(Findrng))) + 1, "MM/DD/YYYY"))
bday = DateAdd("D", -1, ((Format(wkday, "DD/MM/YYYY"))))
nwday = CDate(Application.WorksheetFunction.WorkDay(wkday, -1))
Findrng = bday
' Findrng = FindRowNumber + ((CDate(bday) - CDate(Findrng)))
End If
i = i + 1
End With
Loop
End If
Unload Me
End Sub
#SiddharthRout Sorry, i am not looking to get a message box, I want to use the cell address to populate that cell with a comment. How can I find the cell address/range using the Set Daycell line? – Steven Craig 1 min ago
You said you wanted the value and hence I gave that example. If you want to insert a comment in that cell then you will have to do it like this (Untested)
Dim Daycell As Range
With Range("A1:A100")
Set Daycell = .Find(What:=Dayno, LookIn:=xlValues, Lookat:=xlWhole, _
MatchCase:=False, SearchFormat:=False)
If Not Daycell Is Nothing Then '<~~ Check if a match was found
With Daycell
.AddComment
.Comment.Visible = False
.Comment.Text Text:="This is a sample comment"
End With
End If
End With
Try this way
Dim Daycell As Range
With Range("A1:A100")
Set Daycell = .Find(What:=Dayno, LookIn:=xlValues, MatchCase:=False, SearchFormat:=False)
If Not Daycell Is Nothing Then
MsgBox Daycell.Column
MsgBox Daycell.Row
End If
End With
Refer https://msdn.microsoft.com/en-us/library/office/ff839746.aspx

For each cell in worksheets("xyz") query

Idea behind the code is that it is supposed to find customer names, then find the level of sales to them throughout the year then paste all this data into another sheet.
Getting a Run-Time error '1004' Application-defined or object-defined error from the following line. I have asterisked the line where I am getting the error.
Sub Import_CustomerData()
Dim strMonth As String
Dim rngMonth As Range
Dim DataImportColum As Integer
Dim DataImportRow As Integer
Dim strFirstCustomer As String
Dim strSecondCustomer As String
Dim strThirdCustomer As String
Dim strFourthCustomer As String
Dim strFifthCustomer As String
Dim lngFirstCustomerSales As Long
Dim lngSecondCustomerSales As Long
Dim lngThirdCustomerSales As Long
Dim lngFourthCustomerSales As Long
Dim lngFifthCustomerSales As Long
Dim lngTotalSales As Long
Dim cell As Range
Dim x As Integer
'Finding Data for clients
For Each cell In Worksheets("Data entry").Range("A1:A99")
If cell.Value = "Customer Sales" Then
strFirstCustomer = cell.Offset(1, 0).Value
strSecondCustomer = cell.Offset(2, 0).Value
strThirdCustomer = cell.Offset(3, 0).Value
strFourthCustomer = cell.Offset(4, 0).Value
strFifthCustomer = cell.Offset(5, 0).Value
End If
Next
'Extracting Data from Customer sheet
***For Each cell In Worksheets("Client_Customer").Range("B83:86")***
'First Customer
If cell.Value = strFirstCustomer Then
lngFirstCustomerSales = Val(cell.Offset(0, 1))
End If
'Second Customer
If cell.Value = strSecondCustomer Then
lngSecondCustomerSales = Val(cell.Offset(0, 1))
End If
'Third Customer
If cell.Value = strThirdCustomer Then
lngThirdCustomerSales = Val(cell.Offset(0, 1))
End If
'Fourth Customer
If cell.Value = strFourthCustomer Then
lngFourthCustomerSales = Val(cell.Offset(0, 1))
End If
'Fifth Customer
If cell.Value = gxdfg Then
lngFifthCustomerSales = Val(cell.Offset(0, 1))
End If
'Total Customers Sales
If cell.Value = "Total:" Then
lngTotalSales = Val(cell.Offset(0, 1))
End If
Next
'Importing it into Data Customer Monthly 2013 sheet.
'Determing month of client system reports
strMonth = Sheets("Client_Customer").Range("B8").Value
If strMonth = "" Then
frmEnter_month.Show
Else
iLenMonth = Len(strMonth)
x = iLenMonth - 5
strLeftMonth = Left(strMonth, x)
End If
'To find Column of Customer imput
For Each cell In Range("B4:M4")
If cell.Value = strLeftMonth Then
DataImportColumn = cell.Column
End If
Next
For Each cell In Worksheets("data customer monthly 2013").Range("A3:A9999")
'First Customer
If cell.Value = strFirstCustomer Then
DataImportRow = cell.Row
** 2 ** lngFirstCustomerSales = Cells(DataImportRow, DataImportColumn).Offset(0, 2).Value ** 2 **
End If
'Second Customer
If cell.Value = strSecondCustomer Then
DataImportRow = cell.Row
lngSecondCustomerSales = Cells(DataImportRow, DataImportColumn).Offset(0, 2).Value
End If
'Third Customer
If cell.Value = strThirdCustomer Then
DataImportRow = cell.Row
lngThirdCustomerSales = Cells(DataImportRow, DataImportColumn).Offset(0, 2).Value
End If
'Fourth customer
If cell.Value = strFourthCustomer Then
DataImportRow = cell.Row
lngFourthCustomerSales = Cells(DataImportRow, DataImportColumn).Offset(0, 2).Value
End If
'Fifth Customer
If cell.Value = strFifthCustomer Then
DataImportRow = cell.Row
lngFifthCustomerSales = Cells(DataImportRow, DataImportColumn).Offset(0, 2).Value
End If
'Total Sales
If cell.Value = "Total Sales" Then
DataImportRow = cell.Row
lngTotalSales = Cells(48, DataImportColumn).Value
End If
Next
DeleteClientSheets
End Sub
Sorry for the large amount of code but does anyone have any suggestions? Couldn't find anything else that help explain the question as cell has been defined as a range.
EDIT1:
Second question: After Silenxor's brilliant solution, I am getting code on the line with the following indicator: ** 2 **
The error I am getting is the same as the first error.
With regards to your asterix line
For Each cell In Worksheets("Client_Customer").Range("B83:86")
Try
For Each cell In Worksheets("Client_Customer").Range("B83:B86")

Resources