I cant able to pull the information from the main source - excel

I created a userform that will autofill in all the information using the ID# but I cant pull the source from the specific folder, workbook and range.
Here is my code:
Private Sub TextBox4_Change()
Dim rSource As Range
If Not r Is Nothing Then
'// Get value in cell r.row, column 2 into textbox2
TextBox2.Text = Sheet1.Cells(r.Row, 4).Value
ComboBox3.Value = Sheet1.Cells(r.Row, 6).Value
ComboBox4.Value = Sheet1.Cells(r.Row, 8).Value
ComboBox5.Value = Sheet1.Cells(r.Row, 9).Value
End If
End sub
Thank you!

See my answer in the code below (explanation inside the code as comments):
Option Explicit
Private Sub TextBox4_Change()
Dim wb As Workbook
Dim rSource As Range
' === first set the Workbook object ===
' if the workbook (Excel file) is already open >> use the line below
Set wb = Workbooks("Request ID.xlsm")
' if its close, then use the alternative line below
Set wb = Workbooks.Open("\\Path\")
' now use the Find function
Set rSource = wb.Worksheets("Sheet1").Range("A:A").Find(What:=TextBox4.Text, LookAt:=xlWhole, MatchCase:=False)
If Not rSource Is Nothing Then '<-- you need to use the same Range variable you used for the Find
'// Get value in cell r.row, column 2 into textbox2
TextBox2.Text = Sheet1.Cells(rSource.Row, 4).Value
ComboBox3.Value = Sheet1.Cells(rSource.Row, 6).Value
ComboBox4.Value = Sheet1.Cells(rSource.Row, 8).Value
ComboBox5.Value = Sheet1.Cells(rSource.Row, 9).Value
End If
End Sub

Related

Macro Confusion [duplicate]

This question already has answers here:
Excel VBA, getting range from an inactive sheet
(3 answers)
Closed 1 year ago.
In Excel VBA we have a spreadsheet which stores information and have one of each of our sites. The workbooks are identical but each contains info for a specific sites. These are in constant use and we have too many users to use a single book.
Since an update to office 365, if a user has more than one sheet open then the scripts are writing the data to the wrong sheet. The scripts are contained in a module and it appears that excel, on rare occasions runs the script (of the same name) from the wrong workbook.
Is there a simple way to make the code only run in the workbook it is contained in?
One thought was if we put it in the "this workbook" container rather than in a module might have this effect.
The spreadsheet is very long but in essence this is what it does:
Private Sub cmdSave_Click()
Set ws = Sheets("Repairs Log")
lr = ws.Cells(Rows.Count, 1).End(xlUp).Row + 1
ws.Cells(lr, 3).Value = txtsite
ws.Cells(lr, 4).Value = lbxblock
ws.Cells(lr, 5).Value = txtflat
ws.Cells(lr, 6).Value = txtroom
ws.Cells(lr, 7).Value = txtdescription
ws.Cells(lr, 9).Value = lbxtype
ws.Cells(lr, 8).Value = lbxassigned.Text
End Sub
Any ideas
ThisWorkbook
ThisWorkbook on Microsoft Docs
Option Explicit
' Being Careless
Sub AWB()
Dim wb As Workbook: Set wb = ActiveWorkbook ' workbook you are looking at
' Several possibilities: could be the wrong one!
' continue...
End Sub
' Memorize this.
Sub TWB()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' One possibility: can't be the wrong one!
Dim ws As Worksheet: Set ws = wb.Worksheets("Repairs Log")
' continue...
End Sub
' Since it is simple enough, you can use the 'With' statemnt:
Private Sub cmdSave_Click()
With ThisWorkbook.Worksheets("Repairs Log")
Dim lr As Long: lr = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
.Cells(lr, 3).Value = txtsite
.Cells(lr, 4).Value = lbxblock
.Cells(lr, 5).Value = txtflat
.Cells(lr, 6).Value = txtroom
.Cells(lr, 7).Value = txtdescription
.Cells(lr, 9).Value = lbxtype
.Cells(lr, 8).Value = lbxassigned.Text
End With
End Sub

VBA Userform posting data twice....sometimes

I have a userform with a combobox on a sheet "PostHistory" that draws it's data from the "Staff" sheet. When you press Add on the userform it's suppose to locate the name on the Staff Sheet and replace the date next to the name. Occasionally, it will replace the date and the date next to the name below it. Using Excel 2016
Private Sub CommandButton7_Click()
Application.ScreenUpdating = False
Sheets("Staff").Visible = True
Sheets("Engine").Visible = True
Dim TargetRow As Integer
Dim nameRange As Range
Set nameRange = Sheets("Staff").Range("C3:C200")
TargetRow = Sheets("Engine").Range("D3").Value
Sheets("PostHistory").Range("B3").EntireRow.Insert Shift:=xlDown
Sheets("PostHistory").Range("B3").Value = txt_date
Sheets("PostHistory").Range("C3").Value = cb_staff
Sheets("PostHistory").Range("D3").Value = txt_post
Sheets("PostHistory").Range("E3").Value = txt_notes
If (Augment.txt_date.Text) = "" Then
GoTo Skip1
ElseIf IsNull(Augment.txt_date.Value) = False Then
End If
For Each cell In nameRange.Cells
If cell.Text = [cb_staff] Then
cell.Offset(0, -1).Value = txt_date
End If
Next
Skip1:
Unload Augment
Sheets("Staff").Visible = False
Sheets("Engine").Visible = False
Sheets("List").Visible = False
Application.ScreenUpdating = True
Augment.Show
End Sub
To start: I didn't find the reason why your code should write more than once. But I believe the code below will not write anything twice.
Private Sub CommandButton7_Click()
' 209
Dim nameRange As Range
Dim Fnd As Range
Dim Ctls() As String
Dim i As Integer
Ctls = Split("txt_Date,cb_Staff,txt_Post,txt_Notes", ",")
If Len(txt_Date) Then
With Worksheets("Staff")
Set nameRange = .Range(.Cells(3, 3), .Cells(.Rows.Count, 3).End(xlUp))
End With
Set Fnd = nameRange.Find(cb_Staff.Value, , xlValues, xlWhole)
If Not Fnd Is Nothing Then Fnd.Offset(0, -1).Value = txt_Date.Value
End If
With Worksheets("PostHistory")
.Rows(3).EntireRow.Insert Shift:=xlDown
With .Rows(3)
For i = 0 To UBound(Ctls)
.Cells(3 + i).Value = Me.Controls(Ctls(i)).Value
Me.Controls(Ctls(i)).Value = ""
Next i
End With
End With
End Sub
In principle, you don't need to unhide a sheet in order to read from or write to it. Also, if the sheet to which you write is hidden, there is no point in stopping ScreenUpdating. Finally, I did like the way you found to clear all controls but believe that it will interfere with your management of the list in the combo box. Therefore I showed you another method above.
Oh, yes. I created a userform called Augment with one combo box, 3 text boxes and one CommandButton7. I hope that is what you also have.

How to reference specific cell number for LOOKUP in VBA?

I have the following code:
Private Sub submitFormBtn_Click()
If timeOfArrival.Value = "" Then
MsgBox "Please enter time of arrival", vbCritical
ElseIf poNumber.Value = "" Then
MsgBox "Please enter a valid PO Number", vbCritical
Else
Dim lRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Data")
lRow = ws.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
With ws
.Cells(lRow, 1).Value = Me.DTPicker1.Value
.Cells(lRow, 2).Value = Me.timeOfArrival.Value
.Cells(lRow, 4).Value = Me.poNumber.Value
.Cells(lRow, 5).Value = "=LookupCSVResults(D3,Table_PurchaseOrderLine[POR],Table_PurchaseOrderLine[Product])"
End With
End If
End Sub
What it does
The code above, takes in the User Form Text Box values, and then inserts it into excel sheet for each available row.
Problem
This function "=LookupCSVResults(D3,Table_PurchaseOrderLine[POR],Table_PurchaseOrderLine[Product])" is the complication.
For every record inserted into Excel sheet, it is currently referencing to cell D3 - how can I reference it to the cell to the left of it?
Current problem:
Should be:
If I understand correctly, you want to use lrow:
"=LookupCSVResults(D" & lrow & ",Table_PurchaseOrderLine[POR],Table_PurchaseOrderLine[Product])"

Import checked checkbox captions into a table

I have a userform from which I want to import values into a predefined table (called "Overzicht").
I have 12 checkboxes (one for each month) and I want one row for each month if that checkbox is checked. I want to put the Caption of the checkbox in one of the columns in the table.
For example, if I check January, February and March, I want to import all values into a table into three rows where the first row the 'Month' columns says "January", the second one "February" etc.
I have code that checks the number of checked checkboxes and creates the same number of rows. I don´t know how to get correct captions in the rows. This is what I have so far:
Private Sub CommandButton1_Click()
Dim rng As Range
Dim newrow As ListRow
Set rng = ThisWorkbook.Worksheets("Kostenoverzicht").Range("Overzicht")
Dim answer As Integer
'check number of rows to insert based on # of checked months
Dim ctl As MSForms.Control
Dim rows As Long
For Each ctl In Kostenoverzicht.Frame2.Controls
If TypeOf ctl Is MSForms.CheckBox Then
If Kostenoverzicht.Frame2.Controls(ctl.Name).Value = True Then
rows = rows + 1
End If
End If
Next
answer = MsgBox("Are you sure you want to continue?", vbQuestion + vbYesNo + vbDefaultButton1, "Zet in overzicht?")
If answer = vbYes Then
rng.Select
Set newrow = Selection.ListObject.ListRows.Add(alwaysinsert:=True)
With ws
For rows = 1 To rows
newrow.Range.Cells(rows, 1).Value = Me.TextBox1.Value
newrow.Range.Cells(rows, 2).Value = Me.CategorieBox.Value
newrow.Range.Cells(rows, 3).Value = Me.SubCategorieBox.Value
newrow.Range.Cells(rows, 4).Value = Me.BankrekeningBox.Value
If OptionButton1.Value = True Then newrow.Range.Cells(rows, 5).Value = "Af" Else newrow.Range.Cells(1, 5).Value = "Bij"
newrow.Range.Cells(rows, 6).Value = Me.TextBox2.Value
newrow.Range.Cells(rows, 7).Value = Me.CheckBox1.Caption
If OptionButton3.Value = True Then newrow.Range.Cells(rows, 8).Value = "Ja" Else newrow.Range.Cells(1, 8).Value = "Nee"
Next
End With
End If
End Sub
It will give the value "January" to all rows.
I need code to replace the newrow.Range.Cells(rows, 7).Value = Me.CheckBox1.Caption to take the caption of the checked checkbox.
I´ve tried to find my answer on several sites.
Nevermind my first answer, I misunderstood and thought it would always go from jan to some other month. But now It seems it could also be just be sept and nov for example. Find old/wrong answer at the bottom.
Your code is increadibly hard for me to understand for some reason. You check how many rows to insert at the top, then all the rows seem to get the same information put into it since cells 1-6 are values from other non variable/dynamic sources? Im unsure if I understand whats happening.What even is ws? It also kind of calls a userform right? I can"t really rebuilt what you have cuz I don`t quite know.
Best shot:
Private Sub CommandButton1_Click()
Dim rng As Range
Dim newrow As ListRow
Set rng = ThisWorkbook.Worksheets("Kostenoverzicht").Range("Overzicht")
Dim answer As Integer
Dim ctl As MSForms.Control
Dim rows As Long
answer = MsgBox("Are you sure you want to continue?", vbQuestion + vbYesNo + vbDefaultButton1, "Zet in overzicht?")
If Not answer = vbYes Then Exit Sub
For Each ctl In Kostenoverzicht.Frame2.Controls
If TypeOf ctl Is MSForms.CheckBox Then
If Kostenoverzicht.Frame2.Controls(ctl.Name).Value = True Then
Set newrow = rng.ListObject.ListRows.Add(alwaysinsert:=True)
newrow.Range.Cells(rows, 1).Value = Me.TextBox1.Value
newrow.Range.Cells(rows, 2).Value = Me.CategorieBox.Value
newrow.Range.Cells(rows, 3).Value = Me.SubCategorieBox.Value
newrow.Range.Cells(rows, 4).Value = Me.BankrekeningBox.Value
If OptionButton1.Value = True Then newrow.Range.Cells(rows, 5).Value = "Af" Else newrow.Range.Cells(1, 5).Value = "Bij"
newrow.Range.Cells(rows, 6).Value = Me.TextBox2.Value
newrow.Range.Cells(rows, 7).Value = ctl.Name 'Or maybe ctl.Caption ?
If OptionButton3.Value = True Then newrow.Range.Cells(rows, 8).Value = "Ja" Else newrow.Range.Cells(1, 8).Value = "Nee"
End If
End If
Next
End Sub
I hope you see what I'm trying to do here and can fix it to your needs /bug fix it. Like I said, I didnt rebuilt a sheet to test it. Maybe it helps you regardless.
Old:
newrow.Range.Cells(rows, 7).Value = Format(3 + 31 * (rows - 1), "MMMM")
This code should go behind your UserForm
Here are some suggestions for when you're coding:
Use option explicit so you don't have unexpected behavior with undefined variables
Always indent your code (see www.rubberduckvba.com a free tool that help you with that)
Try to separate your logic defining variables and the reusing them
Review and customize the code so it fits your needs.
You can see what's happening in the code by adding a stop and pressing F8 and executing it line by line.
Code:
Option Explicit
Private Sub CommandButton1_Click()
ProcessForm
End Sub
Private Sub ProcessForm()
Dim targetControl As MSForms.control
Dim continue As Boolean
continue = MsgBox("Are you sure you want to continue?", vbQuestion + vbYesNo + vbDefaultButton1, "Zet in overzicht?") = vbYes
' If it's not yes
If Not continue Then Exit Sub
For Each targetControl In Me.Controls
If TypeOf targetControl Is MSForms.CheckBox Then
Select Case targetControl.Value
Case True
' Call the RecordData procedure (remember to add the controls in the parameters)
RecordData targetControl.Caption, Me.TextBox1.Value, Me.TextBox2.Value
Case False
' Do something?
End Select
End If
Next targetControl
End Sub
Private Sub RecordData(ByVal recordMonth As String, ByVal textbox01Value As String, ByVal textbox02Value As String)
Dim targetTable As ListObject
Dim newRow As ListRow
' Refer to the table (no need for the worksheet reference)
Set targetTable = Range("Overzicht").ListObject
' Add a new row an set a reference
Set newRow = targetTable.ListRows.Add
' Refer to the columns by their header (replace with yours)
newRow.Range.Cells(1, targetTable.ListColumns("Month").Index).Value = recordMonth
newRow.Range.Cells(1, targetTable.ListColumns("Textbox1").Index).Value = textbox01Value
newRow.Range.Cells(1, targetTable.ListColumns("Textbox2").Index).Value = textbox02Value
End Sub
Let me know if it works or you need more help

VBA codes for Excel- Find a cells value in another workbook and copy adjacent cell to the first workbook

I have a quick question; I have two workbooks, let's say wbk1 and wbk2; What I am trying to do is finding each cell value of a column in wbk1 in a specific column of wbk2 and return offset cell value from wbk2 to adjacent cell of the searched value in wbk1.
Is there any one who can help?
By the way, I could find following code if it helps;
'=================
Sub find1()
Dim Key
Dim Target
Dim Hnum
Dim Success
Dim wbk As Workbook
Dim Lastrow As Long
Dim one As Long
Success = False
Application.ScreenUpdating = False
strSecondFile = "C:\Soroush\08- Technical\03- Stock\Test\PL_Test_01\PL_Test_01.xlsm"
strFrthFile = "C:\Soroush\08- Technical\03- Stock\CNC_Test.xlsx"
'==
Sheets("sheet2").Select
Lastrow = ActiveSheet.UsedRange.Rows.Count
If Not IsEmpty(Cells(5, 9).Value) Then
Key = Cells(5, 9).Value
For i = 5 To Lastrow
' If Not IsEmpty(Cells(i, 9).Value) Then
' Key = Cells(i, 9).Value
Set wbk = Workbooks.Open(strFrthFile)
With wbk.Sheets("Sheet1")
Set Target = Columns(1).find(Key, LookIn:=xlValues)
If Not Target Is Nothing Then
ActiveCell.Select
Selection.Copy
Set wbk = Workbooks.Open(strSecondFile)
With wbk.Sheets("Sheet2")
Sheets("Sheet2").Select
Cells(i, 10).Select
ActiveCell.Paste
If Not IsEmpty(Cells(i + 1, 9).Value) Then
Key = Cells(i + 1, 9).Value
End If
End With
End If
End With
'End If
Next
End If
End Sub
'=========================================================================
But It does not work and I can't figure it out. I appreciate any comments on this macro.
Cheers
You can use INDEX and MATCH.
In this case, the value in cell E2 is matched against values in B2 to B6. This is then indexed against column C and the value in column C is returned.
*ignore the typo for "mammal"!

Resources