I have one problem that I need to solve and is as following. I would like to insert data into cells if conditions are met. Conditions are from cells M1 to M3 and this cells are in dropdown list.
Cell M1 is column B:B
Cell M2 is column C:C
Cell M3 is column D:D
Cell M4 is typed manualy
Cell M5 is a number and is also typed manualy(randoml)
Once I defined from dropdown cells M1 to M3 and type some text in cell M4 and type a number in cell M5, program should insert in column H cell M4, in column I program should automaticaly insert today date and in column J sould automaticaly insert actual time. In how many cells should be this inserted is defined in cell M5. If in some part of the table, row are reserved, macro should skip this already inserted data
If from the table there is no free/empty cells, then the program should inform a user with a notification
Could you please help me to create a macro to automaticaly insert data into cells
Thank you
I try this in attached table, but unfirtunately, results are not this what I expected
Sub code_res()
Dim lr As Long, r As Long
Dim i As Integer
Dim iSheet As Worksheet
Dim ans As Integer
Set iSheet = Worksheets("List1")
lr = Cells(Rows.Count, "A").End(xlUp).Row
i = 0
Cells(4, 14) = 0
For r = 7 To lr
If Cells(r, 2) = Cells(1, 13) And Cells(r, 3) = Cells(2, 13) And Cells(r, 7) = "" Then
Cells(r, 7) = Cells(3, 13)
Cells(r, 9) = Date
With Cells(r, 10)
.Value = Time
.NumberFormat = "hh:mm:ss"
i = i + 1
If i = Cells(4, 13) Then
Exit For
End If
End With
End If
Next r
iSheet.Range("M4") =
iSheet.Application.WorksheetFunction.CountIf(iSheet.Range("H:H"),
iSheet.Range("M3"))
'testing quantity and export
If Cells(4, 13) > Cells(4, 14) Then
ans = MsgBox("Quantity of reservation " & Cells(4, 14), vbQuestion + vbYesNo,"Do you want to do a export?")
If ans = vbYes Then
Call Izvoz1 'data export
Else
MsgBox "Data are not exported"
End If
Else
Call Izvoz1 'data export
MsgBox "Succesesfully exported"
End If
End Sub
Related
I would like populate the blue area with random numbers.
sum of C3 to R3 should be equal to B3 value: 124
also;
sum of C3 to C26 should be equal to C2 value: 705
I tried to achieve it with the following code:
(this code was originally posted here: Code by #Mech
Sub RandomNumbersArray()
' dim your variables. this tells vba what type of variable it is working with
Dim lRow As Long
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Worksheets("SPLIT BY DAYS")
' find the last row in column b (2) in the above defined ws
lRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row
' loop through rows 3 to last row
For i = 3 To lRow
' generate a random number between 0 and the row contents of column B (5)
ws.Cells(i, 3).Value = Int(Rnd() * (ws.Cells(i, 2).Value + 1))
' generate a random number between 0 and the difference between column B and colum C
ws.Cells(i, 4).Value = Int(Rnd() * (ws.Cells(i, 2).Value - ws.Cells(i, 3).Value))
' subtract the difference between column B and the sum of column C and column D
ws.Cells(i, 5).Value = ws.Cells(i, 2).Value - (ws.Cells(i, 3).Value + ws.Cells(i, 4).Value)
' subtract the difference between column B and the sum of column C and column D and column E
ws.Cells(i, 6).Value = ws.Cells(i, 2).Value - (ws.Cells(i, 3).Value + ws.Cells(i, 4).Value + ws.Cells(i, 5).Value)
' subtract the difference between column B and the sum of column C and column D and column E and column F
ws.Cells(i, 7).Value = ws.Cells(i, 2).Value - (ws.Cells(i, 3).Value + ws.Cells(i, 4).Value + ws.Cells(i, 5).Value + ws.Cells(i, 6).Value)
Next i
' sum column C (column 3) and place the value in C2
ws.Cells(2, 3).Value = Application.WorksheetFunction.Sum(Range(Cells(3, 3), Cells(lRow, 3)))
' sum column D (column 4) and place the value in D2
ws.Cells(2, 4).Value = Application.WorksheetFunction.Sum(Range(Cells(3, 4), Cells(lRow, 4)))
' sum column E (column 5) and place the value in E2
ws.Cells(2, 5).Value = Application.WorksheetFunction.Sum(Range(Cells(3, 5), Cells(lRow, 5)))
' sum column F (column 6) and place the value in F2
ws.Cells(2, 6).Value = Application.WorksheetFunction.Sum(Range(Cells(3, 6), Cells(lRow, 6)))
' sum column G (column 7) and place the value in F2
ws.Cells(2, 7).Value = Application.WorksheetFunction.Sum(Range(Cells(3, 7), Cells(lRow, 7)))
End Sub
EDIT: Just to clarify, no negative numbers.
Here is something to try:
Set all cells to 0. Create a list of all cells (some kind of reference to each cell).
Now, randomly choose a cell from your list, and add 1 to that cell. The very first time, all cells will be 0, except for one, which will now be 1.
For this cell that you just incremented, add up the row and column and see if the sums have been reached. If either the row or the column sum has been reached, remove this cell reference from the list.
Repeat (randomly choose a cell from those remaining on the list) until the list is empty.
At each iteration you are randomly choosing one of the remaining cells in the reference list (not choosing from all the cells) and this list is getting smaller and smaller as column or row sums are reached.
It should be the case that random cells will increment, and if the columns and sums can in fact be calculated by values without logical inconsistencies, you should fairly quickly reach that point when the reference list falls empty.
I have a solution.
Answers so far have mostly been about finding values which are random, then fixing them to fit the totals.
I tried finding a calculated (non random) solution that fits the totals, then made a separate sub to randomize it. This way you can prevent the randomization from introducing negative values.
There are two procedures, This sub will call them both on the same Range.
Sub Call_Random_Array
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Worksheets("SPLIT BY DAYS")
Dim RangeToFill as Range: Set RangeToFill = ws.Range("C3:R26") 'Edit this line to select whatever range you need to fill randomly
'Proportionately fill the array to fit totals:
Call ProportionateFillArray(RangeToFill)
'Randomize it x times
For x = 1 to 10 'increase this number for more randomisation
Call RandomizeValues(RangeToFill)
Next
End Sub
Proportionately fill the array to fit totals:
Sub ProportionateFillArray(rngAddress As Range)
Dim ws As Worksheet: Set ws = rngAddress.Worksheet
'Horizontal and Vertical target values as ranges:
Dim hTarg As Range, vTarg As Range
Set hTarg = rngAddress.Rows(1).Offset(-1, 0)
Set vTarg = rngAddress.Columns(1).Offset(0, -1)
'Check the totals match
If Not WorksheetFunction.Sum(hTarg) = WorksheetFunction.Sum(vTarg) Then
'totals don't match
MsgBox "Change the targets so both the horizontal and vertical targets add up to the same number."
Exit Sub
End If
With rngAddress
'Now fill rows and columns with integers
Dim Row As Long, Col As Long
For Row = 1 To .Rows.Count
For Col = 1 To .Columns.Count
.Cells(Row, Col) = Int( _
hTarg.Cells(Col) * vTarg.Cells(Row) / WorksheetFunction.Sum(hTarg) _
)
Next
Next
'Correct rounding errors
For Row = 1 To .Rows.Count
For Col = 1 To .Columns.Count
If Row = .Rows.Count Then
'Last row, so this column must be corrected come what may
.Cells(Row, Col) = .Cells(Row, Col) - WorksheetFunction.Sum(.Columns(Col)) + hTarg.Cells(Col)
ElseIf Col = .Columns.Count Then
'Last column, so must be corrected come what may
.Cells(Row, Col) = .Cells(Row, Col) - WorksheetFunction.Sum(.Rows(Row)) + vTarg.Cells(Row)
ElseIf _
(WorksheetFunction.Sum(.Rows(Row)) - vTarg.Cells(Row)) * _
(WorksheetFunction.Sum(.Columns(Col)) - hTarg.Cells(Col)) > 0 Then
'both row and column are incorrect in the same direction
.Cells(Row, Col) = .Cells(Row, Col) - WorksheetFunction.Max( _
WorksheetFunction.Sum(.Rows(Row)) - vTarg.Cells(Row), _
WorksheetFunction.Sum(.Columns(Col)) - hTarg.Cells(Col))
End If
Next
Next
End With
End Sub
Randomize an array without changing row or column totals:
Sub RandomizeValues(rngAddress As Range)
Dim ws As Worksheet: Set ws = rngAddress.Worksheet
Dim rngIncrease(1 To 2) As Range, rngDecrease(1 To 2) As Range, lDiff As Long
With rngAddress
'Select two cells to increase at random
For a = 1 To 2
Set rngIncrease(a) = .Cells(RndIntegerBetween(1, .Rows.Count), RndIntegerBetween(1, .Columns.Count))
rngIncrease(a).Select
Next
'Corresponding cells to decrease to make totals the same:
Set rngDecrease(1) = ws.Cells(rngIncrease(1).Row, rngIncrease(2).Column)
Set rngDecrease(2) = ws.Cells(rngIncrease(2).Row, rngIncrease(1).Column)
'Set the value to increase/decrease by - can't be more than the smallest rngDecrease Value, to prevent negative values
If Not WorksheetFunction.Min(rngDecrease) > 1 Then
'Don't decrease a value below 1
Exit Sub
Else
lDiff = RndIntegerBetween(1, WorksheetFunction.Min(rngDecrease)-1)
End If
'Now apply the edits
For a = 1 To 2
rngIncrease(a) = rngIncrease(a) + lDiff
rngDecrease(a) = rngDecrease(a) - lDiff
Next
End With
End Sub
'The below is the Random Integer function, I also used it in my other answer
Function RndIntegerBetween(Min As Long, Max As Long) As Long
RndIntegerBetween = Int((Max - Min + 1) * Rnd + Min)
End Function
This code is for what you were trying to do, not exactly how you explained it though (see comments). If this is what you were looking for, then your explanation was a bit off, otherwise let me know what you did mean.
Sub RandomNumbersArray()
Dim lRow As Long, lColumn As Long, remainingValue As Long
Dim wb As Workbook: Set wb = ActiveWorkbook
Dim ws As Worksheet: Set ws = wb.Worksheets("SPLIT BY DAYS")
lRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row
lColumn = ws.Cells(2, ws.Columns.Count).End(xlToLeft).Column
For i = 3 To lRow 'loop through the rows
remainingValue = ws.Cells(i, 2).Value2
For j = 3 To lColumn 'loop through all the columns per row
' generate a random number between 0 and the row contents of column B - previous column
If j = lColumn Then 'last cell can't be random unless you want to extend the columns until the sum in B-column is met
ws.Cells(i, j).Value2 = remainingValue
Else
ws.Cells(i, j).Value2 = Int((remainingValue + 1) * Rnd)
End If
remainingValue = remainingValue - ws.Cells(i, j).Value2
Next j
Next i
For j = 3 To lColumn 'loop through the columns to set the sum
ws.Cells(2, j).Value2 = Application.WorksheetFunction.Sum(Range(Cells(3, j), Cells(lRow, j)))
Next j
End Sub
I'm yet to get past the O-column with any value above 0 however
I am trying to delete row based upon their values (i.e. if a cell contains the word DELETE) then the entire row should be deleted and shifted up.
I currently have code that loops through data and applies the cell value "IN-SCOPE" or "DELETE" to column 11 depending on the date present in Column 4. This works fine - however, the code I've written to delete any items labeled with "DELETE" doesn't do anything. Below is the code I currently have - any help would be great.
'Loop that lables items as in-scope IF they fall within the user defined range
y = 2
StartDate = Controls.Cells(15, 10).Value
EndDate = Controls.Cells(15, 11).Value
Bracknell.Activate
Cells(1, 11).Value2 = "Scope Check"
Do While Cells(y, 4).Value <> ""
If Cells(y, 9).Value >= StartDate And Cells(y, 9).Value < EndDate Then
Cells(y, 11).Value = "IN-SCOPE"
Else: Cells(y, 11).Value = "DELETE"
End If
y = y + 1
Loop
'Loop to delete out of scope items
Bracknell.Activate
z = 1
Do While Cells(z, 4).Value <> ""
If Cells(z, 11).Value = "DELETE" Then
Range("A" & z).EntireRow.Delete shift:=xlUp
End If
z = z + 1
Loop
Try this, the code is self explained:
Option Explicit
'use option explicit to force yourself
'to declare all your variables
Sub Test()
'Loop that lables items as in-scope IF they fall within the user defined range
Dim StartDate As Date
StartDate = Controls.Cells(15, 10).Value
Dim EndDate As Date
EndDate = Controls.Cells(15, 11).Value
With Bracknell
'Instead deleting every row, store them into a range variable
Dim RangeToDelete As Range
'Calculate your last row with data
Dim LastRow As Long
'Assuming your column 4 has data on all the rows
'If not, change that 4 for a column index that has data.
LastRow = .Cells(.Rows.Count, 4).End(xlUp).Row
'The most efficient way to loop through cells
'is using For Each loop
Dim cell As Range
.Cells(1, 11) = "Scope Check"
'loop through every row in column 4
For Each cell In .Range(.Cells(2, 4), .Cells(LastRow, 4))
'if the cell of that row in column 9 is between
If .Cells(cell.Row, 9) >= StartDate And .Cells(cell.Row, 9) < EndDate Then
.Cells(cell.Row, 11) = "IN-SCOPE"
Else
'if not, check if rangetodelete is empty
If RangeToDelete Is Nothing Then
'if it is empty, set it as the cell
Set RangeToDelete = cell
Else
'if not, set it as what it already is and the new cell
Set RangeToDelete = Union(RangeToDelete, cell)
End If
End If
Next cell
'Once you ended the loop you'll get the variable
'with every cell that didn't meet your criteria
'Check if is nothing, which means there are no cell to delete
If Not RangeToDelete Is Nothing Then RangeToDelete.EntireRow.Delete
End With
End Sub
Trying to loop two columns and put result into one column.
1) looping is incorrect (no hits = wrong)
2) printing puts result into two different columns ("O" +7 from H and "R" +7 from K).
Private Sub FindValueKH_JN()
'New column O (no 15)
'Find if value starting in column H (no8) is between 207100-208100
'AND if value starting in column K (no11) is between 12700-12729,
' then T2J in column O, else T2N in O
Range("O1").Select
Selection.EntireColumn.Insert , CopyOrigin:=xlFormatFromLeftOrAbove
ActiveCell.FormulaR1C1 = "T2 er Ja eller Nei"
Dim loopRange As Range
'From H to new column O is +7 columns
lastrow1 = ActiveSheet.Cells(Rows.Count, "H").End(xlUp).Row
'From K to new column O is +4 columns
lastrow2 = ActiveSheet.Cells(Rows.Count, "K").End(xlUp).Row
'loop columns H and K
Set loopRange = Union(Range("H2:H" & lastrow1), Range("K2:K" & lastrow2))
For Each cell In loopRange
If Left(cell.Value, 6) >= 207100 And Left(cell.Value, 6) <= 208100 And _
Left(cell.Value, 5) >= 12700 And Left(cell.Value, 5) <= 12729 Then
cell.Offset(0, 7).Value = "T2J"
Else: cell.Offset(0, 7).Value = "T2N"
End If
Next cell
End Sub
Your references are incorrect, and this is why you are not getting any hits. You want to check two separate columns for specific values, but instead are just looking in one single cell for both conditions:
For Each cell In loopRange will loop through every cell in your defined loopRange range, which contains both columns.
You'd have to change your code so it loops through just a single column instead, like the following
Dim loopRange As Range
lastrow = ActiveSheet.Cells(Rows.Count, "H").End(xlUp).Row 'From H to new column O is +7 columns
Set loopRange = Range("H2:H" & lastrow1) 'loop columns H
For Each cell In loopRange
If Left(cell.Value, 6) >= 207100 And Left(cell.Value, 6) <= 208100 And Left(cell.Offset(, 3).Value, 5) >= 12700 And Left(cell.Offset(, 3).Value, 5) <= 12729 Then
cell.Offset(0, 7).Value = "T2J"
Else: cell.Offset(0, 7).Value = "T2N"
End If
Next cell
In your If-statement, you are checking the content of a single cell and your If-statement can never be true. With your Union-statement, you will get a Range with all cells of Col H and all cells of Col K, and in the loop you are checking all cells that are either in H or in K.
So your If hits, for example, Cell H2 and you are checking if the content is > 207100 and in the same moment < 12729.
What you probably want is to loop over all cells if column H, check it's value together with the value of the cell in column K of the same row.
I assume your cells contain a string starting with a number but holds also some characters. I would advice that you write the values into intermediate variables, makes it much easier to debug. You are using the left-function which will give you the first 6 (resp. 5) characters. The result is still a string (even if it contains only digits), and you compare it to a number, and that's not a good idea because now VBA has to do some implicit conversions, and that may lead to unexpected results. You should use the Val-function to convert a string into a numeric value.
As already mentioned in the comments, never work implicit on the so called Active Worksheet. Specify explicitly the worksheet you want to work with.
One question: Why do you use the strange syntax for the Else-statement. The : means that you put a second statement into a line. It is much more readable to omit the : and put the next statement(s) into separate lines.
Dim loopRange As Range, cell As Range, lastrow As Long
With ThisWorkbook.Sheets(1)
lastrow = .Cells(Rows.Count, "H").End(xlUp).row
Set loopRange = .Range("H2:H" & lastrow)
End With
For Each cell In loopRange
Dim valH As Long, valK As Long
valH = Val(Left(cell.Value, 6))
valK = Val(Left(cell.Offset(0, 3).Value, 6))
If valH >= 207100 And valH <= 208100 And valK >= 12700 And valK <= 12729 Then
cell.Offset(0, 7).Value = "T2J"
Else
cell.Offset(0, 7).Value = "T2N"
End If
Next cell
I am trying to create a pricing sheet which will import a CSV BOM from Creo into a new worksheet, I have that part sorted. The problem is the next part i want...
We have different values in column 'G' which are for the different materials e.g: 'MS', 'SS', 'ANGLE', 'PURCHASED'
The issue I have is creating a 'total cost' in column 'J' which is based on the material in 'G'. If the value is "MS" then the value in Column 'J' should be quantity x unit mass x material cost.
'Quantity' is the value in column C, 'unit mass' is the value in column E and 'material cost' is always cell H5 in worksheet named 'MASTER' (this is where the total cost column J should be driven from)
Sub subMultiply()
For Each Cel In Range("G2:D" & Cells(Rows.Count, "G").End(xlUp).Row)
If Cel.Value = "MS" Then
Cel.Offset(0, 3).Value = Cel.Offset(0, -2).Value * ThisWorkbook.Sheets(MASTER).Range(H5).Value * Cel.Offset(0, -4).Value
ElseIf Cel.Value = "PURCHASED" Then
Cel.Offset(0, 3).Value = Cel.Offset(0, -3).Value * ThisWorkbook.Sheets(MASTER).Range(H6).Value * Cel.Offset(0, -4).Value
End If
Next
End Sub
You should try with the select case function
SOmething like :
Select Case Cells(i, 7)
Case Is = "MS"
Cells(i, 10) = 3
Case Is = "SS"
Cells(i, 10) = 5
Case Is = "ANGLE"
Cells(i, 10) = 8
Case Is = "PURCHASED"
Cells(i, 10) = 11
End Select
Instead of the numbers (3,5,8 and11) I used for my test, you can use whatever you want.
You can use the sheets function to select sheets :
Sheets("MASTER").Cells(5,8) is H5 on the Master Sheets.
Ex : Sheets("Sheet2").Cells(1, 1).Select
'''
Firstrow = .UsedRange.Cells(1).Row
lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row
For lRow = lastrow To Firstrow Step -1
Set ws2 = ThisWorkbook.Sheets("MASTER")
With .Cells(lRow, "G")
If Not IsError(.Value) Then
If .Value Like ("*MS*") Then Cells(lRow, "D").Value = Cells(lRow, "E").Value * ws2.Range("H5").Value
'''
I was able to add another If statement for each type of material
I have two sheets in my workbook. The first is supposed to display data from the second sheet that has a lot of data.
I have put a macro button on the display sheet where if I enter a specific value in the referenced cell and then click the button it displays all the rows in my data sheet that has it's value.
The problem is I can only search for a single value to display but I want to use another two cells to put other values like using conditions, to be specific is date duration.
cell 1... Name,
cell 2... Start Date,
cell 3... End Date
Upon clicking the button it should display all the rows in the data sheet that has the values of specific name, a date in the second cell and a date in the third cell.
Here's the code I'm currently using,
Sub SearchMultipleValues()
Dim eRow As Long
Dim ws As Worksheet
Dim lastrow As Long
Dim count As Integer
lastrow = Sheets("DATA").Cells(Rows.count, 1).End(xlUp).Row
Sheet2.Range("A5:L1048569").ClearContents
count = 0
Dim p As Long
p = 2
For X = 2 To lastrow
If Sheets("DATA").Cells(X, 1) = Sheet2.Range("A1") Then
Sheet1.Cells(p, 1) = Sheets("Sheet2").Cells(X, 1)
Sheet1.Cells(p, 2) = Sheets("Sheet2").Cells(X, 2)
Sheet1.Cells(p, 3) = Sheets("Sheet2").Cells(X, 3)
Sheet1.Cells(p, 4) = Sheets("Sheet2").Cells(X, 4)
Sheet1Cells(p, 5) = Sheets("Sheet2").Cells(X, 5)
Sheet1.Cells(p, 6) = Sheets("Sheet2").Cells(X, 6)
Sheet1.Cells(p, 7) = Sheets("Sheet2").Cells(X, 7)
Sheet1.Cells(p, 8) = Sheets("Sheet2").Cells(X, 8)
Sheet1.Cells(p, 9) = Sheets("Sheet2").Cells(X, 9)
Sheet1.Cells(p, 10) = Sheets("Sheet2").Cells(X, 10)
Sheet1.Cells(p, 11) = Sheets("Sheet2").Cells(X, 11)
Sheet1.Cells(p, 12) = Sheets("Sheet2").Cells(X, 12)
p = p + 1
count = count + 1
End If
Next X
MsgBox " The number of item found is " & " " & count
End Sub
The cell A1 is where I type the value I want to display in the "Sheet1" that is from the data sheet "Sheet2". Now I want to include cell A2 and A3 as additional values that sticks with the value in cell A1 in the data sheet.
You can abandon the loop altogether. Try using Filter method of the Range Object.
Dim sh As Worksheet, lastrow As Long, datarange As Range
Set sh = Sheets("DATA") '// set the source sheet //
'// clear destination sheet focusing on columns that will be used //
Sheet2.Range("A5:L" & Sheet2.Rows.Count).ClearContents
With sh
lastrow = .Range("A" & .Rows.Count).End(xlUp).Row
Set datarange = .Range("A1:L" & lastrow) '// set the source row //
End With
'// filter based on sheet2 A1 value //
datarange.AutoFilter 1, Sheet2.Range("A1").Value2, xlFilterValues
'// copy filtered values
datarange.SpecialCells(xlCellTypeVisible).Copy
'// paste to destination
Sheet2.Range("A2").PasteSpecial xlPasteValuesAndNumberFormats
You can have a go at this and if it works, adjust to suit your needs. This is not tested as I have no way of doing it now. Hope this helps though.