VBA why am i getting error or popup saying "16" - excel

In the code shown below, i am in the first section moving data from sheet "Ark2" to the sheet "Ark1". in the second section, i transpose from vertical to horizontal. Now i am rinning it in module, but i am getting an popup saying "16" and it is deleting data from my sheet "Ark2" and therefor also data on ark2.
it is not adding data from the first sheet to the second or horizonting the colums.
hope you can help!!
Sub MyProcedure()
a = Worksheets("ark1").Cells(Rows.Count, 1).End(xlUp).Row
MsgBox (a)
End Sub
Private Sub CommandButton1_Click()
Dim nøgletal As String, år As Integer
Worksheets("Ark2").Select
nøgletal = Range("B2")
år = Range("C2")
Worksheets("Ark1").Select
Worksheets("Ark1").Range("A4").Select
ThisWorkbook.Worksheets("Ark1").Range("C1:C100").Value = ThisWorkbook.Worksheets("Ark2").Range("C12:C100").Value
ThisWorkbook.Worksheets("Ark1").Range("D1:D100").Value = ThisWorkbook.Worksheets("Ark2").Range("D12:D100").Value
ThisWorkbook.Worksheets("Ark1").Range("E1:E100").Value = ThisWorkbook.Worksheets("Ark2").Range("M12:M100").Value
ThisWorkbook.Worksheets("Ark1").Range("F1:F100").Value = ThisWorkbook.Worksheets("Ark2").Range("N12:N100").Value
ThisWorkbook.Worksheets("Ark1").Range("G1:G100").Value = ThisWorkbook.Worksheets("Ark2").Range("O12:O100").Value
ThisWorkbook.Worksheets("Ark1").Range("A1:A16").Value = ThisWorkbook.Worksheets("Ark2").Range("A12:A16").Value
If Worksheets("Ark1").Range("A4").Offset(1, 0) <> "" Then
Worksheets("Ark1").Range("A4").End(xlDown).Select
End If
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = nøgletal
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = år
Worksheets("Ark2").Select
Worksheets("Ark2").Range("B2", "B16").Select
End Sub
Sub x()
Dim lngDataColumns As Long
Dim lngDataRows As Long
lngDataColumns = 3
lngDataRows = 4
For t = 1 To lngDataRows
Range("l2").Offset(((t - 1) * lngDataColumns) - 1, 0).Resize(lngDataColumns, 1).Value = _
Application.Transpose(Range("e1:g1").Value)
Range("M2").Offset(((t - 1) * lngDataColumns) - 1, 0).Resize(lngDataColumns, 1).Value = _
Application.Transpose(Range("e1:g1").Offset(t).Value)
Next t
End Sub

why am i getting error or popup saying “16”
Should be evident why if you add a value in say ark1!A17 and rerun:
Sub MyProcedure()
a = Worksheets("ark1").Cells(Rows.Count, 1).End(xlUp).Row
MsgBox (a)
End Sub
If not, try adding also into ark1!A18 and rerunning.

Related

How do I code my userform to insert the specified number of rows beneath the selected cell?

I have a userform that I've created that first asks how many rows I would like to insert. The next part of the userform asks what values I would like in columns 1 and 32 of each newly created row (I've set it up so that a maximum of 6 new rows can be created at one time). My data has 45 columns, and the only data that I want to change in the newly created rows is the data in the two columns i said earlier (1 and 32). I want the data from all the other columns from the original row to be copied down into each new row. My problem is that I can't seem to figure out how to write a code that will do this the way I want it. To provide an example, if I respond to the userform that I want to add 3 rows below the currently active cell, it will then ask me what values i want to enter for columns 1 and 32 for each of these new rows. So I would enter something like this:
First New Row
Column 1: 8/17/2019
Column 32: 400
Second New Row
Column 1: 8/10/2019
Column 32: 500
Third New Row
Column 1: 8/3/2019
Column 32: 600
I've tried many different codes but I've only really figured out how to write it so that it inserts one row below the active cell and its completely blank, I don't know how to program it so that it enters he values I selected for columns 1 and 32 and copies all other data down from the original row. I've figured out the code for the clear and cancel button on my userform already, I am now only concerned with writing this code for the "OK" button.
Private Sub CancelButton_Click()
Unload Me
End Sub
Private Sub ClearButton_Click()
Call UserForm_Initialize
End Sub
Private Sub OKButton_Click()
Dim lRow As Long
Dim lRsp As Long
On Error Resume Next
lRow = Selection.Row()
lRsp = MsgBox("Insert New row above " & lRow & "?", _
vbQuestion + vbYesNo)
If lRsp <> vbYes Then Exit Sub
Rows(lRow).Select
Selection.Copy
Rows(lRow + 1).Select
Selection.Insert Shift:=xlDown
Application.CutCopyMode = False
Rows(lRow).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone
End Sub
Private Sub UserForm_Initialize()
AddRowsTextBox.Value = ""
Date1TextBox.Value = ""
Date2TextBox.Value = ""
Date3TextBox.Value = ""
Date4TextBox.Value = ""
Date5TextBox.Value = ""
Date6TextBox.Value = ""
Qty1TextBox.Value = ""
Qty2TextBox.Value = ""
Qty3TextBox.Value = ""
Qty4TextBox.Value = ""
Qty5TextBox.Value = ""
Qty6TextBox.Value = ""
End Sub
what i understand from your requirement, I would have add one more spin button on the form to make it user friendly. It may look like this.
User form Code may please be modified according to control names in your form
Option Explicit
Public Bal As Double, XQnty As Double, LargeOrder As Double, Sm As Double
Private Sub CommandButton1_Click()
Dim lRow As Long
Dim lRsp As Long
lRow = ActiveCell.Row()
lRsp = MsgBox("Insert New row Below " & lRow & "?", vbQuestion + vbYesNo)
If lRsp <> vbYes Then Exit Sub
Dim Ws As Worksheet
Dim R As Long, i As Integer, RowtoAdd As Integer
Set Ws = ThisWorkbook.ActiveSheet
RowtoAdd = Me.SpinButton1.Value
R = ActiveCell.Row
With Ws
.Cells(R, 32).Value = LargeOrder
For i = 1 To RowtoAdd
.Cells(R + 1, 1).EntireRow.Insert Shift:=xlDown
.Cells(R, 1).EntireRow.Copy Destination:=.Cells(R + 1, 1)
.Cells(R + 1, 1).Value = Me.Controls("TextBox" & i).Value
.Cells(R + 1, 32).Value = Me.Controls("TextBox" & 7 + i).Value
R = R + 1
Next i
End With
Unload Me
End Sub
Private Sub CommandButton2_Click()
Unload Me
End Sub
Private Sub SpinButton1_Change()
Dim x As Integer, i As Integer, Y As Double
Me.TextBox7.Value = Me.SpinButton1.Value
x = Me.SpinButton1.Value
Sm = 0
For i = 1 To 6
Me.Controls("TextBox" & i).BackColor = IIf(i <= x, RGB(255, 100, 100), RGB(255, 2550, 255))
Me.Controls("TextBox" & i + 7).Value = IIf(i <= x, Int(Bal / x), 0)
Sm = Sm + IIf(i <= x, Int(Bal / x), 0)
Next
If Sm <> Bal Then
Me.TextBox8.Value = Int(Bal / x) + Bal - Sm
End If
ManualBal
End Sub
Private Sub TB_LO_Change()
LargeOrder = Val(Me.TB_LO.Value)
Bal = XQnty - LargeOrder
ManualBal
End Sub
Private Sub UserForm_Initialize()
Dim i As Integer, dx As Variant
Me.SpinButton1.Value = 1
Me.TextBox7.Value = 1
Me.TextBox1.BackColor = RGB(255, 100, 100)
dx = ThisWorkbook.ActiveSheet.Cells(ActiveCell.Row, 1).Value
XQnty = ThisWorkbook.ActiveSheet.Cells(ActiveCell.Row, 32).Value
LargeOrder = 575
Bal = XQnty - LargeOrder
Sm = 0
If IsDate(dx) = False Then dx = Now()
For i = 1 To 6
Me.Controls("TextBox" & i).Value = Format(dx - i * 7, "mm-dd-yyyy")
Sm = Sm + Int(Bal / 6)
Me.Controls("TextBox" & i + 7).Value = Int(Bal / 6)
Next
If Sm <> Bal Then
Me.TextBox8.Value = Int(Bal / 6) + Bal - Sm
End If
Me.TB_LO = LargeOrder
Me.TB_Bal = 0
End Sub
Private Sub ManualBal()
Dim x As Integer, i As Integer
x = Me.SpinButton1.Value
Bal = XQnty - LargeOrder
Sm = 0
For i = 1 To 6 ' Or may use 6 insted of X
Sm = Sm + Val(Me.Controls("TextBox" & i + 7).Value)
Next
Me.TB_Bal.Value = Bal - Sm
End Sub
Private Sub TextBox8_Exit(ByVal Cancel As MSForms.ReturnBoolean)
ManualBal
End Sub
Private Sub TextBox9_Exit(ByVal Cancel As MSForms.ReturnBoolean)
ManualBal
End Sub
Private Sub TextBox10_Exit(ByVal Cancel As MSForms.ReturnBoolean)
ManualBal
End Sub
Private Sub TextBox11_Exit(ByVal Cancel As MSForms.ReturnBoolean)
ManualBal
End Sub
Private Sub TextBox12_Exit(ByVal Cancel As MSForms.ReturnBoolean)
ManualBal
End Sub
Private Sub TextBox13_Exit(ByVal Cancel As MSForms.ReturnBoolean)
ManualBal
End Sub
Here Text Box 1 to 6 for dates, 7 for Spin Button values and Text Box 8 to 13 for quantity. May please either modify code according to control names Or modify Control names according to code.
Edit: Two new Text Box added named TB_BAL to show when entering values in manually in Quantity text boxes (balance calculated only at exit event of text boxes) and TB_LO to change LargeOrder during run.

how to display first row data's of excel sheet in userform automatically when clicking on a button

I have a set of 4 rows of data, i need to make the first row data's visible automatically in userform excel using vb , when i click on the button in ribbon. Later by clicking on next row it needs to display the complete data's of next row.
for example,
stud_id stud_name age gender
1 a 20 M
2 b 22 M
3 c 25 F
4 d 22 F
Public ncurretnrow As Long
Sub Userform_Initialize()
ncurrentrow = Sheet3("2017").Cells(Rows.Count, 1).End(xlDown).Offset(1, 0).Row
traversedata (ncurrentrow)
End Sub
Public Sub traversedata(nrow As Long)
Me.stud_id.Value = ws.Cells(nrow, 1).Value
Me.stud_name.Value = ws.Cells(nrow, 2).Value
Me.age.Value = ws.Cells(nrow, 2).Value
If Optionyes = True Then
Me.genderm.Value = ws.Cells(nrow, 3).Value
Else
Me.genderf.Value = ws.Cells(nrow, 3).Value
End If
See code below (both Subs inside the User_Form module).
Public ws As Worksheet
Private Sub UserForm_Initialize()
Dim HeaderRng As Range
Dim ncurretnrow As Long
' set the worksheet object
Set ws = ThisWorkbook.Sheets("2017")
Set HeaderRng = ws.Cells.Find(what:="stud_id") ' look for the header (below it you will find the first row with data)
If Not HeaderRng Is Nothing Then
ncurretnrow = HeaderRng.Row + 1
Else
MsgBox "Unable to find stud_id header", vbCritical
Exit Sub
End If
traversedata ncurretnrow
End Sub
Sub traversedata(nrow As Long)
With Me
.stud_id.Value = ws.Cells(nrow, 1).Value
.stud_name.Value = ws.Cells(nrow, 2).Value
.age.Value = ws.Cells(nrow, 3).Value
If Optionyes = True Then
.genderm.Value = ws.Cells(nrow, 4).Value
Else
.genderf.Value = ws.Cells(nrow, 4).Value
End If
End With
End Sub

Selecting column range with specific header

I have a macro code but it runs on specific column and on range of 500 only. I wish it should dynamically select column of header 'PRODUCTS' is present. if possible can we increase the limit of 500 to all the data present in column 'PRODUCTS'.
Sub Pats()
myCheck = MsgBox("Do you have Patent Numbers in Column - B ?", vbYesNo)
If myCheck = vbNo Then Exit Sub
endrw = Range("B500").End(xlUp).Row
Application.ScreenUpdating = False
For i = 2 To endrw
PatNum = Cells(i, 2).Value
If Left(Cells(i, 2), 2) = "US" Then
link = "http://www.google.com/patents/" & PatNum
Cells(i, 2).Select
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="http://www.google.com/patents/" & PatNum, ScreenTip:="Click to View", TextToDisplay:=PatNum
With Selection.Font
.Name = "Arial"
.Size = 10
End With
ElseIf Left(Cells(i, 2), 2) = "EP" Then
link = "http://www.google.com/patents/" & PatNum
Cells(i, 2).Select
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="http://www.google.com/patents/" & PatNum, ScreenTip:="Click to View", TextToDisplay:=PatNum
With Selection.Font
.Name = "Arial"
.Size = 10
End With
End If
Next i
End Sub
I would first extract the link building part into a separate subroutine ...
Sub AddLink(c As Range)
Dim link As String
Dim patNum As String
Dim test As String
patNum = c.Value
test = UCase(Left(patNum, 2))
If test = "US" Or test = "EP" Then
link = "http://www.google.com/patents/" & patNum
Else
link = "http://www.www.hyperlink.com/" & patNum
End If
c.Hyperlinks.Add Anchor:=c, Address:=link, ScreenTip:="Click to View", TextToDisplay:=patNum
With c.Font
.Name = "Arial"
.Size = 10
End With
End Sub
Then I would add a function to find the column...
Function FindColumn(searchFor As String) As Integer
Dim i As Integer
'Search row 1 for searchFor
FindColumn = 0
For i = 1 To ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Column
If ActiveSheet.Cells(1, i).Value = searchFor Then
FindColumn = i
Exit For
End If
Next i
End Function
Finally I would put it all together ...
Sub Pats()
Dim col As Integer
Dim i As Integer
col = FindColumn("PRODUCTS")
If col = 0 Then Exit Sub
For i = 2 To ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
AddLink ActiveSheet.Cells(i, col)
Next i
End Sub
I'll admit I have to use SO to remind myself how to get the last used cell on a worksheet (see Find Last cell from Range VBA).
The code below will find which column has the header PRODUCTS and then find the last row in that column and store it in variable lrProdCol.
Sub FindProductLR()
Dim col As Range
Dim endrw As Long
Set col = Rows(1).Find("PRODUCTS")
If Not col Is Nothing Then
endrw = Cells(Rows.count, col.Column).End(xlUp).Row
Else
MsgBox "The 'PRODUCTS' Column was not found in row 1"
End If
End Sub
So replace the following bit of code
myCheck = MsgBox("Do you have Patent Numbers in Column - B ?", vbYesNo)
If myCheck = vbNo Then Exit Sub
endrw = Range("B500").End(xlUp).Row
With the lines above. Hope that helps

Having Trouble passing a Cell object? (i could be wrong)

First off thank you very much. Over the last few months (i believe) my coding has progressed drastically. Any and all criticize is always welcome (rip me apart).
Recently I started to try to use different Subs (I dont quite understand when to use functions etc, but i figure it is good structure practice for when i figure it out.
I am hitting a Run-time 424 Error with the following bit of code in Sub ownerCHECK
Sub OccupationNORMALIZATION()
Dim infoBX As String
' initialize variables
LRow = ActiveSheet.UsedRange.Rows.Count
LCol = ActiveSheet.UsedRange.Columns.Count
STATUScounter = LRow
Do While infoBX = ""
infoBX = InputBox("Enter Occupation Column", "Occupation Column")
Loop
restaurCHECK (infoBX)
Application.ScreenUpdating = True
Application.StatusBar = ""
End Sub
-
Sub restaurCHECK(infoBX As String)
Dim RestaurantS(), RestaurantDQs() As Variant
Dim i, LRow, LCol, STATUScounter As Long
Dim rRng As Range
LRow = ActiveSheet.UsedRange.Rows.Count
LCol = ActiveSheet.UsedRange.Columns.Count
STATUScounter = LRow
RestaurantS = Array("estaur", "food", "cafe", "beverage", "waiter", "waitr", _
"waitstaff", "wait staff", "grill") 'array list of target occupations
RestaurantDQs = Array("fast", "pub", "import", "packing", "processing", "packag", _
"retired", "anufact", "distrib") ' disqualifying words for Restaurante category
Set rRng = Range(infoBX & "2:" & infoBX & LRow)
Application.ScreenUpdating = False
For Each cell In rRng
ownerCHECK (cell)
For i = LBound(RestaurantS) To UBound(RestaurantS)
If InStrRev(cell.Value, UCase(RestaurantS(i))) > 0 Then
cell.Offset(, 1) = "Restaurants"
cell.Interior.Color = 52479
End If
Debug.Print cell.Value
Next
For i = LBound(RestaurantDQs) To UBound(RestaurantDQs)
If InStrRev(cell.Value, UCase(RestaurantDQs(i))) And cell.Interior.Color = 52479 Then
cell.Interior.Color = 255
cell.Offset(, 1) = ""
End If
Next
STATUScounter = STATUScounter - 1
Application.StatusBar = "REMAINING ROWS " & STATUScounter & " tristram "
Next cell
End Sub
-
Sub ownerCHECK(str_owner As Range)
Dim owner() As Variant
owner() = Array("owner", "shareholder", "owns ")
For i = LBound(owner) To UBound(owner)
If InStrRev(str_owner, UCase(owner(i))) > 0 Then
cell.Offset(, 2) = "Owner"
End If
Next
End Sub
I can see a couple of issues in ownerCHECK():
"cell" is not defined (unless it's global)
you shouldn't use "cell" as a variable name (internal VBA property)
check validity of incoming range
.
Option Explicit
Sub ownerCHECK(ByRef rngOwner As Range)
If Not rngOwner Is Nothing Then
Dim owner() As Variant
owner() = Array("OWNER", "SHAREHOLDER", "OWNS ")
For i = LBound(owner) To UBound(owner)
If InStrRev(UCase(rngOwner), owner(i)) > 0 Then
rngOwner.Offset(, 2) = "Owner"
End If
Next
End If
End Sub

Excel VBA: writing formula in current selection

I want to write the current month based on a referenced cell into the current selection. This is my code but I get the error message: object variable or with block variable not set. I don't know what the problem is - anyone have a clue?
Sub SelectionMonthNames()
Dim Currentrange As Range
For i = 1 To 3
Currentrange = Selection.Address
If i = 1 Then
Currentrange.Formula = "=DATE(YEAR($B$5);MONTH($B$5);DAY($B$5))"
Else
Currentrange.Formula = "=DATE(YEAR($B$5);MONTH($B$5)+" & CStr(i - 1) & ";DAY($B$5))"
End If
Selection.Offset(0, 1).Select
Next i
End Sub
Try
Set Currentrange = Selection.Address
Instead of
Currentrange = Selection.Address
EDIT:
So, final version of your macro should look like this:
Sub SelectionMonthNames()
Dim Currentrange As Range
For i = 1 To 3
Set Currentrange = Selection
If i = 1 Then
Currentrange.Formula = "=DATE(YEAR($B$5),MONTH($B$5),DAY($B$5))"
Else
Currentrange.Formula = "=DATE(YEAR($B$5),MONTH($B$5)+" & CStr(i - 1) &",DAY($B$5))"
End If
Selection.Offset(0, 1).Select
Next i
End Sub

Resources