Excel VBA: fill textbox based on combobox selection - excel

First off all I am not very experienced with excel VBA. After searching on net and youtube I couldn't figure it out, so I hope you can help me out.
In my workbook I run a macro that gives a timestamp via =NOW() and an "unique" generated code via CHAR(RANDBETWEEN). This is then copy & pasted to a separate sheet("Dates")to create the list for my combobox, where the code is in column A and the timestamp in column B. Each time I run my macro a new timestamp and code is generated and put in Row 1 Column A & B again (so the older one is shifted down)
With the combobox I got my list of timestamp based on the code below:
Private Sub UserForm_Initialize()
Dim ws As Worksheet, lirow As Integer
Set ws = ThisWorkbook.Worksheets("Dates")
lirow = 1
While ws.Cells(lirow, 2) <> ""
Me.cboxDates.AddItem ws.Cells(lirow, 2).Value
lirow = lirow + 1
Wend
End Sub
What I want is to show the corresponding code in a textbox next to my combobox, so basically just an offset (0, -1).
Your help is appreciated.
Thanks in advance!
Kr, Marty

Private Sub cboxDates_Change()
Dim Found As Range, LastRow As Long
Set Found = Worksheets("Dates").Columns(2).Find(what:=Me.cboxDates.Text, LookIn:=xlValues, lookat:=xlWhole)
If Found Is Nothing Then Exit Sub
Me.TextBox1.Text = Worksheets("Dates").Cells(Found.Row, Found.Column).Offset(0, -1).Value
End Sub

Related

Excel - How to lock whole row if cell in Column G contains *

I have a rather large excel sheet (4500+ rows) which is an output from a powershell script. when the script couldn't find the answer and we have manually found information have column N (lock Cell) show TRUE .
What I would like to do is lock the entire row if the cell in column N contains text TRUE.
I would assume this is done via VBA but I not versed in VBA so really don't have a clue on it. I am good at following instructions if someone can write some steps.
The end goal is that we would like to be able to run our powershell script in the future and not overwrite manually found information hence the need to lock rows containing a *
Is this possible?
As always thank you for your help
_____________UPDATE _____________
I have adjusted my sheet to have a new column and then created the following VBA script
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("N:N") = "TRUE" Then
Range("2:10000").Locked = True
ElseIf Range("N:N") = "FALSE" Then
Range("2:10000").Locked = False
End If
End Sub
Right click on the tab you wish to protect>>>> View code.
Then I inserted this
Private Sub Worksheet_Calculate()
Dim LR As Long, i As Long
LR = Range("A" & Rows.Count).End(xlUp).Row
Me.Unprotect
For i = 1 To LR
With Range("N" & i)
If .Value = "TRUE" Then .EntireRow.Locked = True
End With
Next i
Me.Protect
End Sub
It appears to be working, now to figure out the next part.

Excel: Copying a row to a new sheet based on a selection from a drop down menu

I am asking what might be a basic question for Excel / VBA, but I am trying to copy rows from one worksheet (StrategicPlanning) to another worksheet (Experiment) based on what is selected in E7 of Worksheet Experiment.
How the Experiment worksheet looks -- please ignore the other cells
My code is not working, and I have a feeling I'm either missing something obvious or I am on the wrong path entirely.
a = Worksheets("StrategicPlanning").Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To a
If Worksheets("StrategicPlanning").Cells(i, 5).Value = Worksheets("Experiment").Cells(7, 5) Then
Worksheets("StrategicPlanning").Rows(i).Copy
Worksheets("Experiment").Activate
b = Worksheets("Experiment").Cells(b + 1, 1).Select
ActiveSheet.Paste
Worksheets("StrategicPlanning").Activate
End If
Next
End Sub
I appreciate any and all help! Many thanks!
This one uses Worksheet_Change Event, but can be done from a button etc.
Remarks:
I have set Experiment E7 as a "named range" Exp_Title.
Given "codenames" to both sheets: Experiment and StrPlan
CurrentRegion is the same as if you select the cell/range and pressing CTRL + *
You will have to modify to your needs, but will give you an idea. Ask away anything confusing. And definitely read what Chris Neilsen has linked.
Private Sub Worksheet_Change(ByVal Target As Range)
If Not (Intersect(Target, Experiment.Range("Exp_Title")) Is Nothing) Then
Dim rngStrPlan As Range
Set rngStrPlan = StrPlan.Range("A1").CurrentRegion
Set rngStrPlan = rngStrPlan.Offset(1, 0).Resize(rngStrPlan.Rows.Count - 1, 1)
Dim i As Long
For i = 2 To 2 + rngStrPlan.Rows.Count
If StrPlan.Cells(i, 1).Value = Experiment.Range("Exp_Title").Value Then
StrPlan.Rows(i).EntireRow.Copy Experiment.Range("A10")
Exit For
End If
Next i
Set rngStrPlan = Nothing
End If
End Sub

How can I do a Calculation in Microsoft Excel VBA?

I'm 15 and I'm doing a Internship as a Developer and I've got a kinda hard exercise.
I have a Table with 3 columns, A is "Number" B is "percent" and C is "Value". The column "value" is blank and I Need to calculate the value with a macro button. I've tried this, but it was wrong because I didnĀ“t calculate it in VBA:
Public Sub PushButton ()
Range("C2:C11").Formula = "=A2*B2/100"
Range("C2:C11").Value = Range("C1:C6).Value
End Sub
How do I solve this?
You are using a defined range, you could do it with a dynamic range like this:
Option Explicit
Sub PushButton()
Dim i As Long, LastRow As Long
With ThisWorkbook.ActiveSheet
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 'first you need to find the last row on the active sheet
For i = 2 To LastRow 'then iterate through all the rows starting from 2, if row 1 has headers
.Cells(i, 3) = .Cells(i, 1) * .Cells(i, 2) / 100
Next i
End With
End Sub
If you need help understanding this code, let me know.
Edit: Explanation
Well, the first thing you must do is Dimension all your variables, and to help that you can use the Option Explicitright above all your code.
I've dimensioned 1 variable for the loop and another one to find the last row with text.
To find the last row what you are actually doing is going to excel, select the last row (1048576) and the column where it will have text, in this case 1 or column "A" and then pushing ctrl+Up excel and vba will get you to the last cell with text.
To do that you use Cells(Row, column) instead of manually inserting row 1048576 you can just use rows.count and it will be the same.
Once you get the last row you just iterate with a For iloop meaning For a variable called i which equals 2 (For i = 2) To LastRow (to the last row you calculated) VBA will repeat the code in between the ForAnd Next adding 1 number to i everytime the loop restarts.
In this case is just adding a number to the rows on Cells(i, 3) so you can modify that cell depending of its i value.
I think you need to question why Excel needs to calculate on demand rather than automatically like normal. Failing that there are a few options
You could change your calculation method to Manual using the following in the ThisWorkbook object
Option Explicit
Dim xlCalcMethod As XlCalculation
Private Sub Workbook_Open()
With Application
' Store users current method for when closing the workbook
xlCalcMethod = .Calculation
.Calculation = xlCalculationManual
End With
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
' Reset calculation
Application.Calculation = xlCalcMethod
End Sub
and then when the button is pressed use the following code to calculate placed in a Module
Option Explicit
Public Sub Button_Click()
Application.Calculate
End Sub
Another option to do this without looping would be:
Sub CalculateRange()
Dim rng As Range
' Update for your Range
With ActiveSheet
Set rng = .Range("C2:C" & .Cells(.Rows.Count, "A").End(xlUp).Row)
End With
rng.Value2 = Evaluate(rng.Offset(0, -2).Address & "*" & rng.Offset(0, -1).Address & "/100")
End Sub
Finally, the way you've come up with is perfectly acceptable as VBA

Copy Check Box to Every 5th Cell with Command Button

I have an issue which i can't solve.I wrote this code:
Private Sub CommandButton2_Click()
Sheets("sheet2").OLEObjects("CheckBox1").Copy
Sheets("sheet3").Range("V7").PasteSpecial
End Sub
This code copy a checkbox from (sheet 2) to (sheet 3) starting from V7 cell. Now I want the next time I press the command button to paste the data to cell V12,next time to V17 etc. My vba knowledge is not very good as you can see.
This code will see how many checkboxes are already in the sheet you are pasting to and add 5 rows for each check box, then paste five rows under the last one.
Private Sub CommandButton2_Click()
' copy checkbox
Sheets("sheet2").OLEObjects("CheckBox1").Copy
Dim wks As Worksheet
Set wks = Sheets("Sheet3")
Dim cb As OLEObject, i As Integer
'determine how many boxes are already there and get count of cell to paste to
i = 7
For Each cb In wks.OLEObjects
If InStr(1, cb.Name, "CheckBox") Then i = i + 5
Next
'paste new checkbox
Sheets("sheet3").Range("V" & i).PasteSpecial
End Sub
Use a global variable. These must be at the top of your sheet, module, or form code above all subs and functions.
Then use that as the row number in your range. Range("V" & lRow)
Private lRow As Long
Private Sub CommandButton2_Click()
'Let's check if this is the first time the button has been used.
If lRow = 0 then
lRow = 7
Else
'Increment the row from the one we wrote to last time.
lRow = lRow + 5
End If
'Do the copy
Sheets("sheet2").OLEObjects("CheckBox1").Copy
Sheets("sheet3").Range("V" & lRow).PasteSpecial
End Sub
I dont know what data you got between in Sheet(3).Range("V7") and Sheet(3).Range("V12")
but juste before you're PasteSpecial, you shoud keep track where was the last time you paste data in Sheets("sheets3") in a specific cell in Sheet("sheets3"), in exemple : Sheets("Sheet3").Range("A1")
Then you'll be able to pastespecial to this cell 5 row under like this :
Sheets("sheet3").Range(Sheets("Sheets3").Range("A1").Offset(5,0)).PasteSpecial
right after that you update the Sheets("Sheets3").Range("A1") = Sheets("sheet3").Range(Sheets("Sheets3").Range("A1").Offset(5,0)).Address
So this should do the work :
Private Sub CommandButton2_Click()
Dim oWsSource as Worksheet
Dim oWsDestination as Worksheet
Set oWsDestination = ThisWorkbook.Worksheet("Sheets3")
Set oWsSource = ThisWorkbook.Worksheet("Sheets2")
'Do the copy
oWsSource.OLEObjects("CheckBox1").Copy
oWsDestination.Range(oWsDestination.Range("A1").Value).Offset(5,0)).PasteSpecial
oWsDestination.Range("A1").Value = oWsDestination.Range(oWsDestination.Range("A1").Value).Offset(5, 0)).Address
End Sub
All the answers put the first checkbox but the next one put it again to the same cell as before.I don't know if its matter but I use excel 2010.

Infinite Loop in Userform Initialization

I'm initializing a userform in an Excel VBA macro. When I go to populate the items in a combobox, I get stuck in an infinite loop, but I don't know why. Here is my code:
Private Sub UserForm_Initialize()
'Populate the combobox with the months
Me.cboCurrMth.SetFocus
Dim cMth As Range
Dim ws As Worksheet
Set ws = Sheet1
For Each cMth In ws.Range("months")
With Me.cboCurrMth
.AddItem cMth.Value
.List(.LineCount - 1, 1) = cMth.Offset(0, 1).Value
End With
Next cMth
End Sub
The named range "months" includes all 12 rows and 2 columns where the first column is an integer (from 1 to 12) and the second column is the string name of each month.
Anyone see why this loop won't terminate? Thanks.
You should rarely select cells or ranges in your production VBA code. However, it can be extremely helpful for debugging purposes.
Add a .select in your For Each loop and then step through your code. You should be able to figure out what's wrong.
Private Sub WhyAmIInfinite()
'Loop through and select the months
Dim cMth As Range
Dim ws As Worksheet
Set ws = Sheet1
For Each cMth In ws.Range("months")
cMth.Select
Next cMth
End Sub
I set up a worksheet with a range exactly as you describe and the loop exited as I expected it to. I removed the combobox from my example because I wanted to isolate the loop itself.
I have wrote the following code and it is worked for me. I am using Excel 2003.
ActiveSheet.Shapes("cmbMonths").Select
Dim currMonth As Range
With Selection
For Each currMonth In Range("Months")
.AddItem currMonth.Value
Next
End With
This line ".List(.LineCount - 1, 1) = cMth.Offset(0, 1).Value" is giving error for me 'Saying member not found"
Please select your month cells once again and give the name for the selected range and try again.
Hope it works.

Resources