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.
Related
I found a code that I use to insert rows based on the cell value:
Sub Add_Rows()
Dim r As Long
Application.ScreenUpdating = False
For r = Range("F" & Rows.count).End(xlUp).Row To 1 Step -1
If Cells(r, "F").Value > 0 Then Rows(r + 1).Resize(Cells(r, "F").Value).Insert
Next r
Application.ScreenUpdating = True
End Sub
But I also need to copy the value of the cell with the same index as "F" into the inserted rows:
How can I modify the code so that rows are inserted based on the value of the range F and a value from the range H is inserted into these rows in parallel?
That is, the script should have logic: if the value of "F" is 2, two rows are inserted - and the value from the index "H" is inserted into these two new rows
In the code that I sent, I manage to insert rows based on the value from the index "F", but I can't supplement the code so that the value from the index H is inserted for each new row
Please tell me how to modify the code?
Thanks
I added a line after the .Insert that assigns the value to the "H" column of those new rows. I used the same dynamic range ideas that .Insert used to find the correct range for those new rows.
Sub Add_Rows()
Dim r As Long
Application.ScreenUpdating = False
For r = Range("F" & Rows.Count).End(xlUp).Row To 1 Step -1
If Cells(r, "F").Value > 0 Then
Rows(r + 1).Resize(Cells(r, "F").Value).Insert
Cells(r + 1, "H").Resize(Cells(r, "F").Value).Value = Cells(r, "H").Value
End If
Next r
Application.ScreenUpdating = True
End Sub
Try something like this:
Sub Add_Rows()
Dim r As Long
Application.ScreenUpdating = False
For r = Range("F" & Rows.Count).End(xlUp).Row To 1 Step -1
If Cells(r, 5).Value > 0 Then
Rows(r + 1).Resize(Cells(r, 5).Value).Insert
' insert h value
Cells(r + 1, 7).Value = Cells(r, 7).Value
End If
Next r
Application.ScreenUpdating = True
End Sub
I am desperate now. :(
I have a list of activities in a column in a sheet. In another sheet I have another list of activities, some of which match entries in the list in the first sheet. The code goes through the first list and finds a match in the second list. Then it checks how many outputs this match has, and if there are more than one outputs, it adds another row in the first list of data, right below the last checked cell of that list. On that new row an entry based on the second output should get written. If there is a further output, another new row gets added etc. until there are no more outputs of the same activity. Then it shall continue with the next activity from the first list. That next activity cell shall be therefore moved with the number of rows added additionally during the check.
The problem is, sometimes that moving with the number of additional rows seems to not be enough, so it happens that the next cell is actually a previous one from the list, i.e. an already checked one, and not a new one. And thus an indefinite cycle occurs. To bypass this, I even try to save the last populated row to a value, so that an additional check gets performed if an earlier row gets calculated, but this does not seem to work either :(
What I have is:
…
For Each a In activity_list
previousAddress = 0
If flagOffset > 0 Then
If rows_to_offset <> 0 Or flagsame > 0 Then
Set canda = a.Offset(rows_to_offset, 0) 'check if the offset is enough
If canda.Row <= lastR Then
Set a = Sheets("Sheet1").Cells(lastR + 1, 3) 'if not enough, go to the last result populated row
Else
Set a = canda
End If
rows_to_offset = 0
End If
End If
activityRow = a.Row
activityValue = a.Value
If activityValue <> 0 And Not activity_to_match_list.Find(activityValue, lookin:=xlValues) Is Nothing Then
Set found_act_match = activity_to_match_list.Find(activityValue, lookin:=xlValues)
Sheets("Sheet2").Activate
Set range_to_search_for_outputs = Sheets("Sheet2").Range(Cells(found_act_match.Row, 2), Cells(found_act_match.Row, 500))
If Not range_to_search_for_outputs.Find("o", lookat:=xlPart, lookin:=xlValues, SearchDirection:=xlNext) Is Nothing Then
Set found_output = range_to_search_for_outputs.Find("o", lookin:=xlValues, SearchDirection:=xlNext)
If found_output.Column <> 1
firstAddress = found_output.Address
Do
… do something with the output value…
' Then take the found output from the match and take its status from the Sheet1:
previousAddress = found_output.Address
If op <> "" Then
If Not op_list.Find(op, lookin:=xlValues) Is Nothing Then
Set found_output_match = op_list.Find(op, lookin:=xlValues)
Sheets("Sheet1").Activate
op_result = Cells(found_output_match.Row, "Y").Value
If Worksheets("Sheet1").Cells(activityRow + rows_to_offset, "Y").Value = "" Then
Worksheets("Sheet1").Cells(activityRow + rows_to_offset, "Y").Value = "? " & Format(op_result, "Percent")
lastR = Cells(activityRow + rows_to_offset, "Y").Row
End If
Else:
If Worksheets("Sheet1").Cells(activityRow + rows_to_offset, "Y").Value = "" Then
Worksheets("Sheet1").Cells(activityRow + rows_to_offset, "Y").Value = "Nothing in Sheet1"
lastR = Cells(activityRow + rows_to_offset, "Y").Row
End If
End If
Sheets("Sheet2").Activate
Set another = range_to_search_for_outputs.Find("o", after:=found_output, SearchDirection:=xlNext)
If Not another Is Nothing And another.Address <> found_output.Address Then 'if there is another output for the same activity, go to its output and continue as above
If another.Address <> firstAddress Then
Set found_output = another
Sheets("Sheet1").Activate
If Sheets("Sheet1").Cells(activityRow + rows_to_offset + 1, "C").Value <> activityValue Then 'if there isn't another row for the same activity yet
Sheets("Sheet1").Rows(activityRow + 1).Insert
Sheets("Sheet1").Cells(activityRow + 1, "C").Value = activityValue
rows_to_offset = rows_to_offset + 1
flagOffset = flagOffset + 1
Else:
flagsame = flagsame + 1 'if there is already another row for the same activity
rows_to_offset = rows_to_offset + 1
End If
End If
End If
Sheets("Sheet1").Activate
End If
Loop While (found_output.Address <> previousAddress) And (found_output.Address <> firstAddress)
End If
Else:
Worksheets("Sheet1").Cells(activityRow, "Y").Value = "no Output"
lastR = Cells(activityRow, "Y").Row
End If
ElseIf activity_to_match_list.Find(activityValue, lookin:=xlValues) Is Nothing Then
Worksheets("Sheet1").Cells(activityRow, "Y").Value = "Nothing in Sheet1"
lastR = Cells(activityRow, "Y").Row
ElseIf a.Offset(1, 0).Value <> 0 Then
Set a = a.Offset(1, 0)
Else:
Sheets("Sheet1").Activate
…
End If
Set … to Nothing
Next a
In principle use a dictionary with the key as the sheet2 activity and the value as a collection of row numbers for that activity. Scan down sheet1 and use the dictionary to find matching rows. Search along the matched row for cells with "o" and copy values back to sheet1 Column Y (inserting rows as required).
Sub FindOutputs()
Const COL_OUT = "Y"
Dim wb As Workbook, ws1 As Worksheet, ws2 As Worksheet
Dim rng As Range, fnd As Range, sFirst As String
Dim dict As Object, key, count As Integer
Dim iLastRow As Long, i As Long, n As Long
Set dict = CreateObject("Scripting.Dictionary")
Set wb = ThisWorkbook
' sheet 2 - Activities to Search in Column A
Set ws2 = wb.Sheets("Sheet2")
iLastRow = ws2.Cells(Rows.count, "A").End(xlUp).Row
For i = 1 To iLastRow
key = Trim(ws2.Cells(i, "A"))
If Len(key) > 0 Then
If Not dict.exists(key) Then
' collection holds row numbers for each activity
dict.Add key, New Collection
End If
dict(key).Add CStr(i) ' add row
End If
Next
' sheet 1 - Activities in column A
Set ws1 = wb.Sheets("Sheet1")
Set cell = ws1.Range("A1")
Do While Len(cell.value) > 0
key = Trim(cell.Value)
count = 0
' does activity exist on sheet2?
If dict.exists(key) Then
n = dict(key).count
' loop through matching rows
For i = 1 To n
r = dict(key).Item(i)
' search along the row for "o"
Set rng = ws2.Cells(r, "B").Resize(1, 500)
Set fnd = rng.Find("o", lookat:=xlPart, LookIn:=xlValues, SearchDirection:=xlNext)
If Not fnd Is Nothing Then
sFirst = fnd.Address
' do something with output value
Do
count = count + 1
If count > 1 Then
' insert row
cell.Offset(1).EntireRow.Insert _
CopyOrigin:=xlFormatFromLeftOrAbove
Set cell = cell.Offset(1)
cell.Value = key
End If
ws1.Range(COL_OUT & cell.Row).Value = fnd.Value
Set fnd = rng.FindNext(fnd)
Loop While fnd.Address <> sFirst
End If
Next
If count = 0 Then
ws1.Range(COL_OUT & cell.Row).Value = "No Output"
End If
Else
ws1.Range(COL_OUT & cell.Row).Value = "Nothing in Sheet1"
End If
Set cell = cell.Offset(1)
Loop
MsgBox "Done"
End Sub
I have created a method for defining range between two words and iterate through it to copy paste values from one worksheet to another. There is some strange reason it does not work.
I specify row, it is 18, my code starts from row 20? So it copies everything starting from row 20. O_o
It does not detect range correctly as it copies values below my words as well? I have checked that I don't have same words elsewhere.
Any suggestions?
Here is code for calling method:
Sub dsfdsfdsfds()
copyOptionsToTable 18, CalculationItemOM1
End Sub
Here is method:
Private Sub copyOptionsToTable(RowToPaste As Integer, OperatingWorksheet As Worksheet)
'Dim FirstWord, SecondWord
Dim OptionsRange As Range
Dim cell, x
'Set FirstWord = OperatingWorksheet.Range("W:W").Find("OPTIOONS START", LookIn:=xlValues, lookat:=xlWhole)
'Set SecondWord = OperatingWorksheet.Range("W:W").Find("OPTIOONS END", LookIn:=xlValues, lookat:=xlWhole)
Set OptionsRange = OperatingWorksheet.Range(OperatingWorksheet.Cells.Find("[OPTIOONS START]"), OperatingWorksheet.Cells.Find("[OPTIOONS END]"))
x = 0
' Copy - Paste process
For Each cell In OptionsRange
If Not IsEmpty(cell.Value) Or cell.Value <> "OPT" Then
ThisWorkbook.Worksheets("TableForOL").Range("B" & RowToPaste).Offset(0 + x, 0).Value = cell.Offset(0 + x, -20).Value
ThisWorkbook.Worksheets("TableForOL").Range("B" & RowToPaste).Offset(0 + x, 3).Value = cell.Offset(0 + x, 2).Value
End If
x = x + 1
Next cell
End Sub
Source sheet:
Output sheet:
EDIT:
Output still looks like this?
You're already incrementing cell by one row inside the loop - you don't need to further offset that using x
Set OptionsRange = OperatingWorksheet.Range( _
OperatingWorksheet.Cells.Find("[OPTIOONS START]").Offset(1,0), _
OperatingWorksheet.Cells.Find("[OPTIOONS END]").Offset(-1, 0))
x = 0
' Copy - Paste process
For Each cell In OptionsRange.Cells
If Not IsEmpty(cell.Value) Or cell.Value <> "OPT" Then
With ThisWorkbook.Worksheets("TableForOL").Range("B" & RowToPaste)
.Offset(x, 0).Value = cell.Offset(0, -20).Value
.Offset(x, 3).Value = cell.Offset(0, 2).Value
End With
x = x + 1 '<< only increment if you copied values...
End If
Next cell
Also I'm not sure this line does what you intend?
If Not IsEmpty(cell.Value) Or cell.Value <> "OPT" Then
maybe
If Not IsEmpty(cell.Value) And cell.Value <> "OPT" Then
I have a userform with 2 textboxes and 1 ComboBox. I want the user to input a serial number in "SN_Textbox1" and the 2nd textbox "RMA_Textbox2" automatically fills in with the matching value (coded and works!)
After they select the disposition from ComboBox1 and clicks submit... I want to update column 7 in the same row of that matching serial number...
However, it is just adding a new row at the moment...
'this assigns data to Data Sheet matching serial numbers or adds new values
Private Sub SubmitButton_Click()
Dim serial_ID As String
serial_ID = UCase(Trim(SN_TextBox1.Text))
Worksheets("RMA Tracker").Activate
lastrow = ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
For i = 2 To lastrow
'this assigns data to disposition column to matching entries in serial number column
If UCase(Worksheets("Sheet1").Cells(i, 4).Text) = serial_ID Then
Worksheets("Sheet1").Cells(i, 7).Value = ComboBox1.Text
'Searches for matching RMA & SN 'this assigns data to Log Sheet, if the data is brand new
ElseIf Worksheets("Sheet1").Cells(i, 4).Text <> serial_ID Then
Sheet1.Cells(lastrow + 1, 4) = SN_TextBox1.Text
Sheet1.Cells(lastrow + 1, 1) = RMA_TextBox1.Text
Sheet1.Cells(lastrow + 1, 7) = ComboBox1.Text
End If
Next i
'this clears the fields of userform when button is clicked and saves it automatically
ActiveWorkbook.Save
Call resetform
End Sub
Try This.
Private Sub SubmitButton_Click()
Dim serial_ID As String
Dim cell As Range
Dim r As Range
serial_ID = UCase(Trim(SN_TextBox1.Value))
Worksheets("RMA Tracker").Activate
lastrow = ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
Set r = ActiveSheet.Cells(2, 4).Resize(lastrow, 1)
For Each cell In r:
If UCase(Trim(cell.Value)) = serial_ID Then
cell.Offset(0, 3).Value = ComboBox1.Value
GoTo aaaaa
End If
cell.Offset(1, 0).Value = serial_ID
cell.Offset(1, -3).Value = RMA_TextBox1.Text
cell.Offset(1, 3).Value = ComboBox1.Value
Next cell
aaaaa:
'this clears the fields of userform when button is clicked and saves it automatically
ActiveWorkbook.Save
Call resetform
End Sub
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?