Updating an excel worksheet from another sheet, depending on a value - vba

I am trying to create an If Statement that lets me send an number and a value to another workbook deepening on a value in a 3rd cell (weather the cell is is True or False"). The code that I want to run if the statement is True is below. I have tested this code, and it works, I just want it to happen if the third cell in the row is True. It then needs to carry the information from the number and value rows where the value is true into the function below.
Dim itemName As String
Dim itemPrice As String
Dim myData As Workbook
Worksheets("Sheet1").Select
InvoiceNumber = Range("A2")
qty = Range("B2")
updated = Range("C2")
Set myData = Workbooks.Open("HD:Users:user:Desktop:Inventory.xlsm")
Worksheets("Orders").Select
Worksheets("Orders").Range("a15").Select
RowCount = Worksheets("Orders").Range("a15").CurrentRegion.Rows.Count
With Worksheets("Orders").Range("a15")
.Offset(RowCount, 0) = InvoiceNumber
.Offset(RowCount, 1) = qty
.Offset(RowCount, 2) = updated
End With

Your code looks like it could use another loop to go through a series of rows but I suppose that it may be a case where only a single operation is required.
Dim itemName As String
Dim itemPrice As String
Dim myData As Workbook
Dim sInvoiceNumber As String, dQty As Double, bUpdated As Boolean, iRowCount As Long
With Worksheets("Sheet1")
sInvoiceNumber = .Range("A2").Value
dQty = .Range("B2").Value
bUpdated = CBool(.Range("C2").Value)
If bUpdated Then
Set myData = Workbooks.Open("HD:Users:user:Desktop:Inventory.xlsm")
With myData.Worksheets("Orders").Range("a15")
iRowCount = .CurrentRegion.Rows.Count
.Offset(iRowCount, 0) = sInvoiceNumber
.Offset(iRowCount, 1) = dQty
.Offset(iRowCount, 2) = bUpdated
End With
myData.Close True '<-save and close the workbook
.Range("C2") = Not bUpdated '<- reset the updated field
End If
End With
Rather than loop through the rows, a bulk transfer operation can be used by filtering the data.
Dim itemName As String
Dim itemPrice As String
Dim myData As Workbook
Dim iRowCount As Long
With Worksheets("Sheet1")
If .AutoFilterMode Then AutoFilterMode = False
With .Cells(1, 1).CurrentRegion
.AutoFilter Field:=3, Criteria1:="TRUE"
With .Offset(1, 0).Resize(.Rows.Count - 1, 3)
If CBool(Application.Subtotal(103, .Columns(1))) Then
Set myData = Workbooks.Open("HD:Users:user:Desktop:Inventory.xlsm")
.Cells.Copy Destination:=myData.Sheets("Orders").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
myData.Close True '<-save and close the workbook
.Columns(3).Cells = False
End If
End With
.AutoFilter Field:=3
End With
If .AutoFilterMode Then AutoFilterMode = False
End With
That filters on a worksheet cell value of TRUE in column C.

You should read up on if statements. I'm guessing you'd be able to figure it out from here:
http://www.techonthenet.com/excel/formulas/if_then.php
Basically, just use updated as the test condition in your if statement.
Dim itemName As String
Dim itemPrice As String
Dim myData As Workbook
Worksheets("Sheet1").Select
InvoiceNumber = Range("A2")
qty = Range("B2")
updated = Range("C2")
If updated Then
Set myData = Workbooks.Open("HD:Users:user:Desktop:Inventory.xlsm")
Worksheets("Orders").Select
Worksheets("Orders").Range("a15").Select
RowCount = Worksheets("Orders").Range("a15").CurrentRegion.Rows.Count
With Worksheets("Orders").Range("a15")
.Offset(RowCount, 0) = InvoiceNumber
.Offset(RowCount, 1) = qty
.Offset(RowCount, 2) = updated
End With
End If

Related

13 type mismatch error

I'm trying to send data between worksheets. When I run the code below, I get a 13 mismatch error on the IncidentReport variable. On the source sheet these ranges are numerical but one cell is a date (so number, date, number). I have tried to declare the IncidentReport as a string, integer, and long but I keep getting this error. What is the correct variable for this?
Private Sub Update_Click()
Dim AgentName As String
Dim IncidentReport As Long
Dim MyData As Workbook
'Names variable
Worksheets("sheet1").Select
AgentName = Range("C2")
IncidentReport = Range("D1:F1")
'Opens master workbook
Set MyData = Workbooks.Open("C:\Users\ashley.graham\Field_AgentFolder\Incident Reports\Test folder\Incident reports 2018.xlsx")
'Calls sheet and selects cell
Worksheets("Incident Reports").Select
Worksheets("Incident Reports").Range("a1").Select
'finds next blank row for data entry
RowCount = Worksheets("Incident Reports").Range ("A1").CurrentRegion.Rows.Count
With Worksheets("Incident Reports").Range("A1")
.Offset(RowCount, 0) = IncidentReport
.Offset(RowCount, 1) = AgentName
End With
MyData.Save
End Sub
I think this is what you're trying to do:
Private Sub Update_Click()
Dim AgentName As String
Dim IncidentReport As Range
Dim MyData As Workbook
Dim LastRow As Long
With ThisWorkbook.Worksheets("Sheet1")
AgentName = .Range("C2")
Set IncidentReport = .Range("D1:F1")
End With
Set MyData = Workbooks.Open("C:\Users\ashley.graham\Field_AgentFolder\Incident Reports\Test folder\Incident reports 2018.xlsx")
With MyData.Worksheets("Incident Reports")
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
.Cells(LastRow, 1) = IncidentReport.Cells(1) 'This will put the first cell value here as don't know what you want.
.Cells(LastRow, 2) = AgentName
End With
MyData.Save
End Sub

Using endxldown function to copy and paste unlimited data

I'm trying to copy and paste data from one workbook into another. This function works when the range is static, but I cannot get it to be dynamic. I know the endxldown function is for this, but how would I work it into my code:
Private Sub CommandButton21_Click()
Dim itemName As String
Dim itemPrice As Single
Dim myData As Workbook
Worksheets("Sheet1").Select
itemName = Range("A2")
Worksheets("Sheet1").Select
itemPrice = Range("B2")
Set myData = Workbooks.Open("C:\Users\Iraj.Masud\Desktop\testing\Master.xlsm")
Worksheets("Sheet1").Select
Worksheets("Sheet1").Range("A1").Select
RowCount = Worksheets("Sheet1").Range("A1").CurrentRegion.Rows.Count
With Worksheets("Sheet1").Range("A1")
.Offset(RowCount, 0) = itemName
.Offset(RowCount, 1) = itemPrice
End With
myData.Save
End Sub
My edits are highlighted in the image below. When I ran the macro, I received an object variable or with block variable not set.
Code with Error
I'd guess:
With Worksheets("Sheet1")
With .Range("A" & .Rows.Count).end(xlUp)
.Offset(1, 0) = itemName
.Offset(1, 1) = itemPrice
End With
End With
try this, (I cleaned up your code), see also the instruction that sets a value to rowcount
Private Sub CommandButton21_Click()
Dim rowcount As Long
Dim myData As Workbook
With Worksheets("Sheet1")
.Range("A2:B" & .Cells(.Rows.Count, 1).End(xlUp).Row).Copy
End With
Set myData = Workbooks.Open("C:\Users\Iraj.Masud\Desktop\testing\Master.xlsm")
With myData.Worksheets("Sheet1")
rowcount = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
.Cells(rowcount, 1).Paste
End With
myData.Save
End Sub
Use End(xlUp) from the bottom to capture the last row, this is better than using xlDown because the latter will capture the first empty row, not the last row.
Removing all the unnecessary Select stuff and using arrays, your code can be reduced to this:
Private Sub CommandButton21_Click()
With Workbooks.Open("C:\Users\Iraj.Masud\Desktop\testing\Master.xlsm").Sheets("Sheet1")
.Cells(.Rows.Count, "A").End(xlUp).Offset(1).Resize(1, 2).Value = _
ThisWorkbook.Sheets("Sheet1").Range("A2:B2").Value2
.Parent.Close True
End With
End Sub
Note that all references are explicit, there is no implicit reference to whichever workbook or worksheet is active. This usually results in safer code.
EDIT
If you want to copy all A:B data from the source, use this:
Private Sub CommandButton21_Click()
Dim src as Range
Set src = ThisWorkbook.Sheets("Sheet1").Range("A2", ThisWorkbook.Sheets("Sheet1").Range("B999999").End(xlUp)
With Workbooks.Open("C:\Users\Iraj.Masud\Desktop\testing\Master.xlsm").Sheets("Sheet1")
.Cells(.Rows.Count, "A").End(xlUp).Offset(1) _
.Resize(src.Rows.Count, src.Columns.Count).Value = src.Value2
.Parent.Close True
End With
End Sub
Private Sub CommandButton21_Click()
Dim itemName As String
Dim itemPrice As Single
Dim wbData As Workbook
Dim wsData As Worksheet
Dim newData As Range
With ThisWorkbook.Worksheets("Sheet1") '<~defines that we are working on sheet1
itemName = .Range("A2") '<~gets the itemname
itemPrice = .Range("B2") '<~gets the itemprice
End With
Set wbData = Workbooks.Open("C:\Users\Iraj.Masud\Desktop\testing\Master.xlsm") '<~opens then workbook
Set wsData = wbData.Worksheets("Sheet1") '<~sets the worksheet
Set newData = wsData.Range("A1048576").End(xlUp).Offset(1, 0) '<~locate last cell and offset 1 row below
With newData '<~defines that we are working with the cell below the last non-blank cell
.Offset(0, 0).Value = itemName '<~passes the item name
.Offset(0, 1).Value = itemPrice '<~passes the item price
End With
Set newData = Nothing '<~post procedure cleaning
Set wsData = Nothing '<~post procedure cleaning
wbData.Save '<~save
wbData.Close
End Sub
This might be a chunky code. But IMO, this is flexible in case you want to change some part/s of the code.

Excel VBA - How to find a value in a column and return the row it is on

I currently use a for loop to look through column A in the HDD database sheet and when it finds the matching search criteria it copies all the information in that row into a designated area.
I am trying to use the same for loop to tell me which row the search criteria is found on so i can delete that row from the HDD database sheet.
Tried a few things but nothing seems to work.
Any help is very welcome on this.
Private Sub EditButton_Click()
Dim Userentry As String
Dim i As Long
Dim ws, ws1, ws2 As Worksheet
'Dim found As Range
Dim RowNumber As String
Set ws = Sheets("HDD database")
Set ws1 = Sheets("HDD log")
Set ws2 = Sheets("Sheet3")
Userentry = editTxtbox.Value
'ws1.Range("A36").Value = Userentry
For i = 1 To ws.Range("A" & Rows.Count).End(xlUp).Row
If (ws.Cells(i, 1).Value) = Userentry Then
ws2.Range("A1").Offset(1, 0).Resize(1, 8).Value = _
ws.Cells(i, 1).Resize(1, 8).Value
End If
Next i
addnewHDDtxtbox.Value = ws2.Range("A2")
MakeModeltxtbox.Value = ws2.Range("B2")
SerialNumbertxtbox.Value = ws2.Range("C2")
Sizetxtbox.Value = ws2.Range("D2")
Locationtxtbox.Value = ws2.Range("E2")
Statetxtbox.Value = ws2.Range("F2")
For i = 1 To ws.Range("A" & Rows.Count).End(xlUp).Row
If (ws.Cells(i, 1).Value) = Userentry Then
RowNumber = ws.Cells.Row
End If
Next i
ws1.Range("I3").Value = RowNumber
End Sub
I think this should help. Using Range.Find() should speed it up a little. I can edit this if you want more, just comment.
'I liked your found :)
Dim found As Range
'Set found equal to the cell containing your string
Set found = ws.Range("A:A").Find(Userentry)
'Show the row of found if you want
'MsgBox found.Row
'Delete found's row
'ws.found.Rows.Delete
'Alternately, set the value of I3 to found's row
ws1.Range("I3").Value = ws.found.row
Change:
RowNumber = ws.Cells.Row
to
RowNumber = i

Find Matching Data and Paste onto Next Empty Cell on the same row

I am new here. I have been trying to solve this problem but to no avail.
My objectives are:
1) Need to find matching cell in the Installment workbook and paste the data into the next empty cell on the same row as the matching cell. The matching cell will come from Column E.
Private Sub CommandButton1_Click()
Dim itemNumber As String
Dim itemAmount As Single
Dim myData As Workbook
Worksheets("sheet1").Select
itemNumber = Range("B6")
Worksheets("sheet1").Select
itemAmount = Range("H16")
Set myData = Workbooks.Open("C:\Mydata\Installment.xlsx")
Worksheets("sheet1").Select
Worksheets("sheet1").Range("E1").Select
For Each cell In Range(“E2:E10000”)
IF cell.Value = itemNumber Then
Cellvalue = ActiveCell.address
Next
End IF
ColumnCount = Worksheets("sheet1").Range("Cellvalue").CurrentRegion.Columns.Count
With Worksheets("sheet1").Range("Cellvalue")
.Offset(0, ColumnCount) = itemNumber
.End With
myData.Save
Workbooks("Installment.xlsx").Close
End Sub
If I'm understanding you correctly, this should work. I've made a few "tweaks" to your code, primarily removing the "select" statements, which are usually undesirable and unnecessary.
Private Sub CommandButton1_Click()
Dim itemNumber As String
Dim itemAmount As Single
Dim myData As Workbook
Dim Wk As Worksheet
Dim Cel As Range
With ThisWorkbook.Worksheets("sheet1")
itemNumber = .Range("B6").Value
itemAmount = .Range("H16").Value
End With
Set myData = Workbooks.Open("C:\Mydata\Installment.xlsx")
Set Wk = myData.Worksheets("sheet1")
For Each Cel In Wk.Range("E2:E10000")
If Cel.Value = itemNumber Then
Cel.Value = Cel.Address
' get next blank cell in row
Wk.Cells(Cel.Row, Wk.Columns.Count).End(xlToLeft).Offset(, 1).Value = itemNumber
End If
Next
myData.Close True 'save & close
End Sub

Find If Value Exists on other Worksheet (Excel)

I have a macro tied to a button click event on my Excel worksheet. When this event fires, I need to see if the value on my worksheet FeedSampleForm Range("A5:B5").Value exists anywhere in column B of my other worksheet FeedSamples.
Can anyone assist me with this? I'm barely a user when it comes to Excel, and this is my first time "Developing" with it.
EDIT:
Current Code below. This is for different save procedures depending on if saving a new record or saving after editing a previously created record.
For Sample Data, say I'm looking for "FeedSampleForm".Range("A5:B5").Value which is "SR0238", I need to see if "SR0238" exists in column B on "FeedSamples" worksheet, currently containing "SR0237" - "SR0252". If it doesn't exist, I can use same code as my Add Record functionality, but if it does, I have to write to that exact row when saving.
Sub SaveInspection()
If modeAdd = True Then
'Labeler Reg. No.
Worksheets("FeedSamples").Range("A1").End(xlDown).Offset(1, 0).value = Range("L3:M3").value
'Feed Report No.
Worksheets("FeedSamples").Range("B1").End(xlDown).Offset(1, 0).value = Range("A5:B5").value
'Product No. / Class No.
Worksheets("FeedSamples").Range("C1").End(xlDown).Offset(1, 0).value = Range("C5").value
Worksheets("FeedSamples").Range("E1").End(xlDown).Offset(1, 0).value = Range("D5").value
Worksheets("FeedSamples").Range("F1").End(xlDown).Offset(1, 0).value = Range("E5").value
'Description No.
Worksheets("FeedSamples").Range("H5").End(xlDown).Offset(1, 0).value = Range("F5").value
Worksheets("FeedSamples").Range("I5").End(xlDown).Offset(1, 0).value = Range("G5").value
Worksheets("FeedSamples").Range("J5").End(xlDown).Offset(1, 0).value = Range("H5").value
Worksheets("FeedSamples").Range("K5").End(xlDown).Offset(1, 0).value = Range("I5").value
'Possessor No.
Worksheets("FeedSamples").Range("L1").End(xlDown).Offset(1, 0).value = Range("J5:K5").value
'Date
Worksheets("FeedSamples").Range("M").End(xlDown).Offset(1, 0).value = Range("L5:M5").value
'Possessor Name
Worksheets("FeedSamples").Range("AB1").End(xlDown).Offset(1, 0).value = Range("A8:F8").value
'Possessor Address
Worksheets("FeedSamples").Range("AC1").End(xlDown).Offset(1, 0).value = Range("A10:F10").value
'Possessor City/St
Worksheets("FeedSamples").Range("AD1").End(xlDown).Offset(1, 0).value = Range("A11:E11").value
'POssessor Zipcode
Worksheets("FeedSamples").Range("AE1").End(xlDown).Offset(1, 0).value = Range("F11").value
'Labeler Name
Worksheets("FeedSamples").Range("AF1").End(xlDown).Offset(1, 0).value = Range("H8:M8").value
'Labeler Address
Worksheets("FeedSamples").Range("AG1").End(xlDown).Offset(1, 0).value = Range("H10:M10").value
'Labeler City/St
Worksheets("FeedSamples").Range("AH1").End(xlDown).Offset(1, 0).value = Range("H11:L11").value
'Labeler Zipcode
Worksheets("FeedSamples").Range("AI1").End(xlDown).Offset(1, 0).value = Range("M11").value
'Product Name
Worksheets("FeedSamples").Range("AJ1").End(xlDown).Offset(1, 0).value = Range("A13:I13").value
'1. Med
Worksheets("FeedSamples").Range("AK1").End(xlDown).Offset(1, 0).value = Range("J13:K13").value
'2. Non-Med
Worksheets("FeedSamples").Range("AL1").End(xlDown).Offset(1, 0).value = Range("L13:M13").value
'No. Bags/Loc. Sampled
'Total No. Guarantees
Worksheets("FeedSamples").Range("P").End(xlDown).Offset(1, 0).value = Range("C15:E15").value
'Flag Sample
Worksheets("FeedSamples").Range("Q").End(xlDown).Offset(1, 0).value = Range("F15:G15").value
'Sample Def.
Worksheets("FeedSamples").Range("R").End(xlDown).Offset(1, 0).value = Range("H15:I15").value
'Compliance
'Duplicate
'Bag Tag Mark or Code
Worksheets("FeedSamples").Range("U").End(xlDown).Offset(1, 0).value = Range("A17:H17").value
'On Hand
Worksheets("FeedSamples").Range("V").End(xlDown).Offset(1, 0).value = Range("I17:K17").value
'Approx. Wt/Lbs
Worksheets("FeedSamples").Range("W").End(xlDown).Offset(1, 0).value = Range("L17:M17").value
'Remarks
Worksheets("FeedSamples").Range("AA").End(xlDown).Offset(1, 0).value = Range("A19:M19").value
'Sample Taken From
'Sample Method
'Form
'Probe Size
'Product No./Class No.
Worksheets("FeedSamples").Range("D").End(xlDown).Offset(1, 0).value = Range("A23:C23").value
modeAdd = False
End If
If modeEdit = True Then
'find the record in "datatable" and save over fields.
Dim result As Variant
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets("FeedSamples")
'Range("O3").Formula = "=IF(ISERROR(MATCH(Range("A5:B5").Value, sheet.Range("B:B"), 0)), "Not Found", "Value found on row " & MATCH(Range("A5:B5").Value, sheet.Range("B:B"), 0))"
'Range("O3").Formula = "=IF(ISERROR(MATCH(12345,A:A,0)),"Not Found","Value found on row " & MATCH(12345,A:A,0)))"
result = Application.WorksheetFunction.VLookup(Range("A5:B5").value, sheet.Range("B2:B25000"), 2, False)
'Throws Object Required Error
MsgBox result
modeEdit = False
allowNav = True
End If
End Sub
A very easy way is to declare the range that you want to search in and the value that you want to find.
Sub findValue()
Dim xlRange As Range
Dim xlCell As Range
Dim xlSheet As Worksheet
Dim valueToFind
valueToFind = "MyValue"
Set xlSheet = ActiveWorkbook.Worksheets("Sheet2")
Set xlRange = xlSheet.Range("B1:B10")
For Each xlCell In xlRange
If xlCell.Value = valueToFind Then
'Do Something
End If
Next xlCell
End Sub
I'm assuming that your range of ("A5:B5") is a merged cell because you indicated that it contained a single value. Merged cells can just be referenced by the "top left" cell within the merge (or at least that's how I think of it). So your merged range of ("A5:B5") can be referred to as just ("A5"). Anyway, here is a modified version of the method above that is more suited for your needs.
Sub findValue(ByVal valueToFind As String)
Dim xlRange As Range
Dim xlCell As Range
Dim xlFormSheet As Worksheet
Dim xlSamplesSheet As Worksheet
Dim iLastRow As Integer
Dim iRow As Integer
Dim bFound As Boolean
bFound = False
Set xlFormSheet = ActiveWorkbook.Worksheets("FeedSampleForm")
Set xlSamplesSheet = ActiveWorkbook.Worksheets("FeedSamples")
iLastRow = xlSamplesSheet.Range("B1").End(xlDown).Row
Set xlRange = xlsamplesheet.Range("B1:B" & iLastRow)
For Each xlCell In xlRange
If xlCell.value = valueToFind Then
bFound = True '<-- The value was found
iRow = xlCell.Row '<-- Here is the row that the value was found on
End If
If bFound Then Exit For '<-- Optional: Exit the for loop once the value is found the first time
Next xlCell
End Sub