Due to beginner for VBA, I am in a difficult to find this codes.
I need to create 'Command Button' to insert formula according to
current cell location.
Eg. If current cell location is S7, need to get formula in to it '=K7*L7'.
Current cell location change all the time. Multiplication of Column K and L fixed.
Please help me to write this codes.
You can assign below code to command button
Sub Insert_Formula
n = Selection.row
Selection.Value = "=K" & n & "*L" & n
End Sub
In VBA, Selection will get the selected cell properties.
For example, if you select S7,
n = Selection.Row
Then n will be 7
Selection.Value = "=K" & n & "*L" & n
Above will set selected cell's formulat to =K7*L7
In addition, if you want the button to work on selected range which is more than one cell,
Private Insert_Formula_Multi_Cells
For X = 1 To Selection.Rows.Count
n = Selection.Row + X - 1
Selection.Range(Cells(X, 1), Cells(X, Selection.Columns.Count)) = "=K" & n & "*L" & n
Next X
End Sub
Selection.Rows.Count Gets number of rows selected.
Selection.Columns.Count gets number of columns selected
to get current location in excel you can use ActiveCell.Address command.
Below code first gets current selected cells address and then multiplies with K(11) and L(12) columns to print value in active cell.
Sub acell()
Dim s As String
s = ActiveCell.Address
Range(s).Select
Range(s).Value2 = Cells(2, 11) * Cells(2, 12)
Debug.Print s
End Sub
You can add them in loop as per your requirement.
Related
I have the bellow list, where I should add items in column B in each sheet ; liste_lameM1, liste_lameM2, liste_lameM3 et liste_lameM4:
enter image description here
I need to set a condition on the numbers of the column A, to add new item I need to specify the model from a combobox where i have 4 options( M1, M2, M3, M4) to choose the sheet where the item should be added (this part works well).
The second condition is to select a number from 001 to 300 from a combobox to be able to add my item in the correct place on column B, so if I choose 006, modele M1 my data should be in column B, line 7 in worksheet liste_lameM1, if I choose 007, modele M1 my data should be in column B line8 worksheet liste_lameM1, if I choose 010 , modele M2, my data is added on column B line 11 worksheet liste_lameM2 and so on.
here is my code:
Private Sub CommandButton1_Click()
Dim fin_liste As Range, ligne As Long, ws_lame As Worksheet, ctrl As Boolean
Set ws_lame = ActiveWorkbook.Worksheets("Liste_Lame_" & Me.ComboBox_Modele.Value)
Set fin_liste = ThisWorkbook.Worksheets("Liste_Lame_" & Me.ComboBox_Modele.Value).Cells(Rows.Count, "B").End(xlUp).Offset(1, 0)
For j = 2 To fin_liste
If ws_lame.Range("A" & j) = Me.ComboBox_Num.Value Then
ctrl = True
fin_liste = Me.ComboBox_Num.Value & "-" & Me.TextBox_Mois.Value & "-" & Me.TextBox_Annee.Value & "-" & Me.ComboBox_Modele.Value & "-" & Me.ComboBox_Const.Value
Exit For
End If
Next
If ctrl = False Then
j = fin_liste + 1
ws_lame.Range("A" & j).Value = Me.ComboBox_Num.Value
fin_liste = Me.ComboBox_Num.Value & "-" & Me.TextBox_Mois.Value & "-" & Me.TextBox_Annee.Value & "-" & Me.ComboBox_Modele.Value & "-" & Me.ComboBox_Const.Value
End If
End Sub
The problem with my code is that it is not respecting the numbers I am choosing, it just adds the items one after the other, what editing should I make ? thanks
Variable "j" for looping, I change to "ligne".
Based on your explanation, you can't make the second condition if you use this code as I give you before.
fin_liste = ThisWorkbook.Worksheets(combo.Value).Cells(Rows.Count, "B").End(xlUp).Offset(1, 0)
So even you choose number between 001 & 300, it still add the data exactly on the last row at column "B".
For example, if the last data on cell "B3" (B4 still empty) then you choose number 5 (you hope the data will add on "B6"), the data will add on "B4".
Then maybe you'll find that you can change the .offset(ComboBox_Num.Value, 0), but it will make your data in a mess.
So the code that I give you before ineffective for the 2nd condition.
Based on the 2nd condition, you can use this.
fin_liste = ThisWorkbook.Worksheets(combo.Value).Cells(ComboBox_Num.Value, "B").offset(1, 0)
I still write .offset(1, 0), because I think you want to add the first data on cell "B2", right?
Actually that code have a problem, but based on you question, I think that problem will not affect you. You'll find it out soon. (You should consider Zac's comment)
I've rewrite your code so I can try it on my excel easier. You can change it into your version.
Private Sub CommandButton1_Click()
Dim fin_liste As Range, ligne As Long, ws_lame As Worksheet, ctrl As Boolean
Set ws_lame = ActiveWorkbook.Worksheets(combo.value)
Set fin_liste = ThisWorkbook.Worksheets(combo.Value).Cells(combo2.Value, "B").Offset(1, 0) '.End(xlUp).Offset(combo2.Value, 0)
For ligne = 2 To fin_liste
If ws_lame.Range("A" & ligne) = combo2.Value Then
ctrl = True
fin_liste = text.Value
End If
Next
If ctrl = False Then
ligne = fin_liste + 1
ws_lame.Range("A" & ligne) = combo2.Value
fin_liste = text.Value
End If
End Sub
I´m developing an Excel Makro right now.
Wanted to know, how I can repeat some lines of code using different data, without copy and paste.
Looking forward for your answers : )
This is my current code:
Sub deleteredundant()
Windows("Test1.xlsm").Activate
If Range("A6") = Range("A7") And Range("B6") = Range("B7") Then
Range("A7:B7").Select
Selection.ClearContents
End If
End Sub
It sounds like #BruceWayne has pointed in you in the right direction for what you need - removing duplicates.
As #Apurv Pawar shows you can use a loop, but he's selecting cells (if any code says select or activate a cell just don't.... you can reference a cell without selecting).
Another way is to have a procedure to remove the cells, and another procedure to tell it which workbook, worksheet and cell to look at.
Sub DeleteRedundant(CheckRange As Range)
If CheckRange = CheckRange.Offset(1) And CheckRange.Offset(, 1) = CheckRange.Offset(1, 1) Then
CheckRange.Offset(1).Resize(, 2).ClearContents
End If
End Sub
The code above will accept a range that is passed to it.
It will check if the passed cell is equal to the cell below itself:
CheckRange = CheckRange.Offset(1)
It will then check if the cell to the right of the passed cell is equal to the value below that:
CheckRange.Offset(, 1) = CheckRange.Offset(1, 1)
If the values match it will look at the cell below the passed cell, resize that to two cells wide and clear the contents of those two cells:
CheckRange.Offset(1).Resize(, 2).ClearContents
With this procedure in place we can pass it various range references to operate on:
Sub Test()
DeleteRedundant Workbooks("Excel Worksheet1.xlsx").Worksheets("Sheet1").Range("A6")
DeleteRedundant Workbooks("Excel Worksheet2.xlsx").Worksheets("Sheet2").Range("D5")
'Pass every other cell to the procedure in a loop.
'So will pass A2, A4, A6 - Cells(2,1), Cells(4,1) and Cells(6,1)
Dim x As Long
For x = 2 To 20 Step 2
DeleteRedundant Workbooks("Excel Worksheet1.xlsx").Worksheets("Sheet1").Cells(x, 1)
Next x
End Sub
But, as #BruceWayne says - you probably just need the Delete Duplicates button on the data ribbon.
try the below.
Sub deleteredundant()
Windows("Test1.xlsm").Activate
x = 1
Do While Range("a" & x).Formula <> ""
If Range("A" & x) = Range("A" & (x + 1)) And Range("B6" & x) = Range("B7" & (x + 1)) Then
Rows(x & ":" & x).Select
With Selection
.Delete EntireRow
End With
End If
x = x + 1
Loop
End Sub
Good afternoon all,
I have an issue where I have users who have multiple bank account details. I need to try and create a new row for each employee who has more than one bank account, with the second bank account being allocated a new row.
Employee Number User ID BSB Account number
10000591 WOODSP0 306089,116879 343509,041145273
10000592 THOMSOS0 037125 317166
I need it to look something like this:
Employee Number User ID BSB Account number
10000591 WOODSP0 306089 343509
10000591 WOODSP0 116879 041145273
10000592 THOMSOS0 037125 317166
Any thoughts? Your input is greatly appreciated!
Screenshots are here to demonstrate:
Right click on the tab and choose "View Code"
Paste this code in:
Sub SplitOnAccount()
Dim X As Long, Y As Long, EmpNo As String, UserID As String, BSB As Variant, AccNo As Variant
Range("F1:I1") = Application.Transpose(Application.Transpose(Array(Range("A1:D1"))))
For X = 2 To Range("A" & Rows.Count).End(xlUp).Row
EmpNo = Range("A" & X).Text
UserID = Range("B" & X).Text
BSB = Split(Range("C" & X).Text, ",")
AccNo = Split(Range("D" & X).Text, ",")
For Y = LBound(AccNo) To UBound(AccNo)
Range("F" & Range("F" & Rows.Count).End(xlUp).Row).Offset(1, 0).Formula = EmpNo
Range("G" & Range("G" & Rows.Count).End(xlUp).Row).Offset(1, 0).Formula = UserID
Range("H" & Range("H" & Rows.Count).End(xlUp).Row).Offset(1, 0).Formula = BSB(Y)
Range("I" & Range("I" & Rows.Count).End(xlUp).Row).Offset(1, 0).Formula = AccNo(Y)
Next
Next
End Sub
Close the window to go back to excel
Press ALT-F8
Choose SplitOnAccount and click run.
Note, this is going to populate the split data to rows F to I, make sure there is nothing in there. If there is post back and we can change it.
Also format columns F - I as text before you run it or Excel will strip leading zeros off as it will interpret it as a number.
Here is another sub that appears to perform what you are looking for.
Sub stack_accounts()
Dim rw As Long, b As Long
Dim vVALs As Variant, vBSBs As Variant, vACTs As Variant
With ActiveSheet '<-define this worksheet properly!
For rw = .Cells(Rows.Count, 1).End(xlUp).Row To 2 Step -1
vVALs = .Cells(rw, 1).Resize(1, 4).Value
vBSBs = Split(vVALs(1, 3), Chr(44))
vACTs = Split(vVALs(1, 4), Chr(44))
If UBound(vBSBs) = UBound(vBSBs) Then
For b = UBound(vBSBs) To LBound(vBSBs) Step -1
If b > LBound(vBSBs) Then _
.Rows(rw + 1).Insert
.Cells(rw - (b > LBound(vBSBs)), 1).Resize(1, 4) = vVALs
.Cells(rw - (b > LBound(vBSBs)), 3).Resize(1, 2).NumberFormat = "#"
.Cells(rw - (b > LBound(vBSBs)), 3) = CStr(vBSBs(b))
.Cells(rw - (b > LBound(vBSBs)), 4) = CStr(vACTs(b))
Next b
End If
Next rw
End With
End Sub
I was originally only going to process the rows that had comma delimited values in columns C and D but I thought that processing all of them would allow the macro to set the Text number format and get rid of the Number as text error warnings and keep the leading zero in 041145273.
You Can definitely use Power Query to transform the data to generate new rows using split column option.
Check this article it explains the process in detail.
Load Data in Power Query section of excel.
Create an Index (Not required step)
Use Split column function with advance options and split them into new rows.
Save this result into new table for your use.
I did it myself and it worked like a charm.
A formula solution:
Delimiter: Can be a real delimiter or an absolute reference to a cell containing only the delimiter.
HelperCol: I have to use a helper column to make it work. You need to give the column letter.
StartCol: The column letter of the first column containing data.
SplitCol: The column letter of the column to be splitted.
Formula1: Used to generate the formula for the first column not to be splitted. You can fill this formula down and then fill to right.
Formula2: Used to generate the formula for the column to be splitted(only support split one column).
Formula3: Used to generate the formula for the Helper column.
(If the title of the column to be splitted contains the delimiter, you must change the first value of the helper column to 1 manually.)
Formula1:=SUBSTITUTE(SUBSTITUTE("=LOOKUP(ROW(1:1),$J:$J,A:A)&""""","$J:$J","$"&B2&":$"&B2),"A:A",B3&":"&B3)
Formula2:=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE("=MID($M$1&LOOKUP(ROW(A1),$J:$J,F:F)&$M$1,FIND(""艹"",SUBSTITUTE($M$1&LOOKUP(ROW(A1),$J:$J,F:F)&$M$1,$M$1,"&"""艹"",ROW(A2)-LOOKUP(ROW(A1),$J:$J)))+1,FIND(""艹"",SUBSTITUTE($M$1&LOOKUP(ROW(A1),$J:$J,F:F)&$M$1,$M$1,""艹"",ROW(A2)-LOOKUP(ROW(A1),$J:$J)+1))-FIND(""艹"",SUBSTITUTE($M$1&LOOKUP(ROW(A1),$J:$J,F:F)&$M$1,$M$1,""艹"",ROW(A2)-LOOKUP(ROW(A1),$J:$J)))-1)&""""","$M$1",IF(ISERROR(INDIRECT(B1)),""""&B1&"""",B1)),"$J:$J","$"&B2&":$"&B2),"F:F",B4&":"&B4)
Formula3:=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE("=SUM(E1,LEN(B1)-LEN(SUBSTITUTE(B1,$H$1,"""")))+1","B1",B4&1),"$H$1",IF(ISERROR(INDIRECT(B1)),""""&B1&"""",B1)),"E1",B2&1)
Helper must filled one row more than the data.
How to use:
Copy the formula generated by the above three formula.
Use Paste Special only paste the value.
Make the formula into effect.
Fill the formula.
Bug:
Numbers will be converted to Text. Of course you can remove the &"" at the end of the formula, but blank cells will be filled with 0.
ps. This method may by very hard to comprehend. But once you master it, it can be very useful to solve relative problems.
I will use an example to illustrate my question:
I have many tables which their lines quantity is different.
I want to pull down the function until the end of the table.
For example:
A B
1 =1*2 // <- this is the function that I want to pull
2
3
4
The output should be:
A B
1 =1*2
2 =2*2
3 =3*2
4 =4*2
It is important that the pull length is determined by the last cell at column A (in this case it is 4)
Please also note that the function may be changed either, this should work for any function.
Thank you,
Doron
Here is an example of a macro that will autofill the value from cell B1 to the end of the column to the left of it (in this case column A).
Sub AutoFill()
Dim FillFrom As Range
Set FillFrom = ActiveSheet.Range("B1")
FillFrom.AutoFill Destination:=Range(FillFrom.Address, FillFrom.Offset(0, -1).End(xlDown).Offset(0, 1).Address)
End Sub
Try This:
Public Sub DoWhatIWantYouToDo()
Dim lr As Integer, i As Integer
lr = Sheets("Sheet1").UsedRange.Rows.Count
For i = 2 To lr
Sheets("Sheet1").Range("B" & i).Formula = "=" & " A" & i & "*2"
Next
End Sub
How can I count the number of lines in a wrapped cell through vba code?
With Cells(1, 1)
.WrapText = False
height1 = .height
.WrapText = True
height2 = .height
End With
MsgBox height2 / height1 & " Lines"
This code will not work since I have set row height to a fixed one (only one line is visible).
Also in my text, no line breaks since the data is entered through VBA code.
Thanks in advance.
One way would be to subtract the length of the cell with linebreaks removed from the length of the unadjusted cell
Linebreaks can be replaced with a 0 length string using the worksheet function Substitute
Sub test()
Dim c As Range
Set c = ActiveCell
MsgBox Len(c.Value) - Len(Application.WorksheetFunction.Substitute(c.Value, Chr(10), vbNullString)) & " Linebreak(s)"
End Sub
[Update; Not a linebreak!]
As Sid points out in Get first two lines of text from a wraped cell in excel this is tricky if working with font sizes (which can change).
I think the most foolproof way would be to copy the cell contents elsewhere (to an otherwise blank row), and autofit that row based on that cell to get the height.
If you need an approximation :
Sub approx_number_of_lines()
Set Rng = Selection
a = Len(Rng.Value)
'number of line returns
b = Len(Rng.Value) - Len(Application.WorksheetFunction.Substitute(Rng.Value, Chr(10), vbNullString))
c = Rng.ColumnWidth
d = (a / c) + b
'd = WorksheetFunction.Ceiling(a / c, 1) + b
Debug.Print d
End Sub