Presented calculation values are different when pasted into cells. Why? - vba

I am trying to get a calculated returned value to be pasted into a chosen cell, However, the returned value in the message box is different than the pasted value into the cell. Why is this?
Sub CalcmsgboxAcre()
On Error Resume Next
Dim num As Double
num = Application.InputBox(prompt:="Please Enter The Number Of Hectares You Would Like To Calculate Into Acres ", Type:=1)
MsgBox Format(num * 2.471054, "#,##0.00") & " Is the Number Of Acre's."
num = MsgBox("Do you want to paste the result in a cell?", vbYesNo)
If num = vbYes Then
cell = Application.InputBox("Type In The Cell Reference")
Range(cell).Value = num * 2.471054
End If
End Sub

You are assigning a new value to num:
num = MsgBox (...)
So vbYes gets multiplied by the factor and then enters the cell.

Related

How can I refer to a data in a different row?

I've got an Excel file with N rows and M columns. Usually data are organized one per row, but it can happens that a data occupy more than a row. In this case how can I express that the second (or next) row has to refer to the first row?
In this example, AP.01 has got 5 rows of description, so how can I say that the other 4 rows refer also to the first code?
EDIT once that I did the association I have to export my Excel file into an Access DB. So I want to see the tables with the correct data.
If I have only one row for the description I wrote this code and it works:
If grid(r, 3).Text.Length > 255 Then
code.Description = grid(r, 3).Text.ToString.Substring(0, 252) + "..."
Else
code.Description = grid(r, 3).Text.ToString
End If
Instead if I have more than one row for the description I wrote this code and it doesn't work:
Do While grid(r, 1).ToString = ""
If grid(r, 1).ToString = "" And grid(r, 3).ToString IsNot Nothing Then
Dim s As String
s = grid(r, 3).ToString
code.Description = grid((r - 1), 3).ToString & s
End If
Loop
If it is a one-off, try the below. This will basically put a formula in every cell that refers to the cell immediately above it:
Select column A (from top until bottom of list (row N)
Press ctrl + g to open the GoTo dialogue
Press Special
Select Blanks from the radio buttons
The above will select all the blank cells in column A. Now enter = and press up arrow. Enter the formula by holding down ctrl while pressing enter. That will enter the same formula in every cell.
Try
Sub Demo()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet3") 'change Sheet3 to your data sheet
With .Range("A:A").SpecialCells(xlCellTypeBlanks)
.FormulaR1C1 = "=R[-1]C"
.Value = .Value
End With
End Sub
From your question I Guess that, you must be define a variable for last column Value. and check the value in respective column, if it is empty then use column value if not empty then take current value as last value.
'Dim LastValue as string
LastValue = sheet("SheetName").cells(i,"Column Name").value
for i = 2 to LastRow '>>>> here i am assume you run code in for loop from row to
'to last count row(LastRow as variable)
'Put your sheet name at "SheetName" and column index (like "A","B","C"...) at "Column Name"
if sheet("SheetName").cells(i,"Column Name").value <>"" then
LastValue = sheet("SheetName").cells(i,"Column Name").value
end if
'(Do your stuff using LastValue , you may generate lastvalue 1, lastvalue2 ..etc)
next'for loop end here

Finding next blank row after the user inputs a specific prefix

I have a set amount of tag numbers in column A. The prefix to these tag numbers vary i.e "35C-1243" or "35TC-1234". Each prefix comes with a lot of tag numbers however there are some blank rows in between tag numbers for skipped tags for example it could go from "35C-1234" to "35C-1235" to "35C-1237". This would mean that I have a blank row in between "35C-1235" and "35C-1237". What I have been trying to do is create a code that would prompt the user to enter the prefix for the tag number they want to focus on and based off that prefix the next blank row should be selected however I can't get the excel to activate the blank row. Any suggestions/help will be greatly appreciated.
Private Sub Worksheet_Activate()
Dim msg As String
Dim result As Integer
Dim x As String
msg = "Would you like to find the next available tag number?"
result = MsgBox(msg, vbYesNo)
If result = vbYes Then
x = Application.InputBox("Enter the part reference ")
Select Case x
Case x = "35C"
NextFree = Range("A:A" & Rows.Count).Cells.SpecialCells(xlCellTypeBlanks).Row
Range("A" & NextFree).Select
End Select
Else
Cancel = True
End If
End Sub
The problem is in your Select Case. It should be Case "35C" instead of Case x = "35C". What you do now is compare x to the result of x = "35C", which is True, but x is not equal True, so this case is False :)
Also what #FreeMan said about Range("A:A" & Rows.Count) which should be Range("A:A").

Use math equation input value to do math calculation in VBA Exccel

I'm doing numerical integration in Excel VBA and I want to get the equation from the user instead of inserting it in the Cell.
Example
The user gives me x^3+x^2+2 which is F(X)
In A1, I have number 2 and I evaluate F(X) in B1.
How to tell excel that the equation input from user is =A1^3+A2^2+2. I just need that conversion to one cell.
I'm using Val(InputBox())
Thanks for the help
If the user enters x or X and you only need to replace X with A1.cell.value then use this:
Sub test()
formula_user = InputBox("Please type formula")
Range("B1").Formula = "=" & Replace(LCase(formula_user), "x", "A1")
End Sub
x is replace with A1 in the formula from the user inputbox. It can be upper or lower case in the user input
The Application Evaluate function can resolve the formula received from the user but you will have to find someway to convert x to a cell reference that can be correctly understood. This may require the worksheet name.
Your x^3+x^2+2 example replaces two x values with A1 and A2. It may be better as x^3+y^2+2 so that there is no ambiguity between what is A1 and what is A2.
Sub f_of_x_and_y()
Dim fmla As String, str As String
fmla = InputBox("enter formula")
With Worksheets("Sheet2")
str = Replace(Replace(fmla, "x", .Range("A1").Address(external:=True)), _
"y", .Range("A2").Address(external:=True))
.Range("A3") = Application.Evaluate(str)
End With
End Sub
Sub variable_input()
Dim userFormula$
Dim myVar&
myVar = 2
userFormula = InputBox("What is the formula?")
Debug.Print userFormula
userFormula = Replace(userFormula, "x", myVar)
Debug.Print userFormula
Dim theAnswer$
theAnswer = Val(userFormula)
Debug.Print theAnswer
End Sub
You can replace all "x" with the string "A1". Don't forget to add "=" in front...
Sub TestUserEquation()
Dim strUserEquation As String
strUserEquation = LCase(InputBox("Please enter your equation:", "Equation InputBox"))
If strUserEquation <> "" Then
Cells(1, 2) = "=" & Replace(strUserEquation, "x", "A1")
Else
Cells(1, 2) = "No equation entered."
End If
End Sub

MS Excel 2010 - VBA to lookup in one column a customer number and Tag the corresponding column with Yes or No

I have an extremely large dataset with customer numbers and we cannot just use a =IF(E3=160248, "YES", "NO") to tag a particular customer number of 160248 with YES or NO. Instead, I would like to use VBA code to lookup Customer_Number in column E and return a YES or NO in the corresponding row in Column AG, called Incorporated_160248. I have not done an If then clause in VBA, so I have no idea where to start. Please note, each month the data set can change. One month it could be 4,000 entries and the next 3,500, so that has to be dynamic. Any thoughts?
Sub TagTryco()
Dim CN As Integer, result As String
CN = Range("E:E").Value
If CN = 160248 Then
result = "YES"
Else
result = "NO"
End If
Range("AG:AG").Value = result
End Sub
I get a Compile error: Wrong number of arguments or invalid property assignment.
This CODE Works now:
Sub TagTryco()
Dim listLength
listLength = Worksheets("ILS_Import").Cells(Rows.Count, "E").End(xlUp).Row - 1
Dim i As Integer
For i = 2 To listLength + 2
If Worksheets("ILS_Import").Range("E" & i) = 160248 Then
Worksheets("ILS_Import").Range("AG" & i) = "Yes"
Else
Worksheets("ILS_Import").Range("AG" & i) = "No"
End If
Next
End Sub
To know how many entries you have:
dim listLength
listlength = Sheet1.Cells(Rows.Count, "E").End(xlUp).Row - 1 'I assumed column E, starting at row 2
You need to loop from row 2 to the row 2 + listLength, check the cell in column E, and check if it is equal to your number:
dim i as integer
for i = 2 to listLength + 2
If Range("E" & i) = 160248 Then
Range("AG" & i) = "Yes"
Else
Range("AG" & i) = "No"
End If
Next
If you wish to scan for different numbers you can adapt the code to use a value from a cell in which you enter that number, OR use an inputbox to enter the number you want to look for, or something else. This code was not tested.
If you want to use the column name you assigned instead of AG (which is safer) you can use something along the lines of:
= Range("Incorporated_160248")(i+1)
Instead, which gives the column with an offset of i. Should bring you to the right cell.

Unexpected String Results

I have the following code to check values entered into two input boxes, if both values are zero then the MsgBox should display "Stop!" (I will change this later to exiting the sub but I am using a MsgBox for testing)
From testing I've seen these results:
A zero in both strings produces the expected message box.
A non zero in the first string followed by any non zero value in the second string does nothing (as expected).
A zero in the first string followed by a second string value equal to or greater than 10 produces the message box (unexpected).
I've also noticed that if the second string is 6-9 it is displayed as x.00000000000001%. I think this is a floating point issue and could be related? This behaviour occurs without the IF... InStr function too.
Option Explicit
Sub Models()
Dim MinPer As String, MaxPer As String, Frmula As String
Dim Data As Worksheet, Results As Worksheet
Set Data = Sheets("Data")
Set Results = Sheets("Results")
Application.ScreenUpdating = False
MinPer = 1 - InputBox("Enter Minimum Threshold Percentage, do not include the % symbol", _
"Minimum?") / 100
MaxPer = 1 + InputBox("Enter Maximum Threshold Percentage, do not include the % symbol", _
"Maximum?") / 100
If (InStr(MinPer, "0") = 0) And (InStr(MaxPer, "0") = 0) Then
MsgBox "STOP!"
End If
' Remainder of code...
This is the most interesting problem I've come across so far in VBA and welcome any discussion about it.
Edit: I use this code to display on screen the paramaters for the end-user to see. Hence how I noticed the .00000000001% issue:
.Range("D2").Value = "Min is " & 100 - MinPer * 100 & "%"
.Range("D3").Value = "Max is " & MaxPer * 100 - 100 & "%"
Two things
1) Declare MinPer, MaxPer as Long or a Double and not a String as you are storing outputs from a calculation
2) Don't directly use the InputBox in the calculations. Store them in a variable and then if the input is valid then use them in the calculation
Dim MinPer As Double, MaxPer As Double, Frmula As String
Dim Data As Worksheet, Results As Worksheet
Dim n1 As Long, n2 As Long
Set Data = Sheets("Data")
Set Results = Sheets("Results")
Application.ScreenUpdating = False
On Error Resume Next
n1 = Application.InputBox(Prompt:="Enter Minimum Threshold Percentage, do not include the % symbol", _
Title:="Minimum?", Type:=1)
On Error GoTo 0
If n1 = False Then
MsgBox "User cancelled"
Exit Sub
End If
On Error Resume Next
n2 = Application.InputBox(Prompt:="Enter Maximum Threshold Percentage, do not include the % symbol", _
Title:="Maximum?", Type:=1)
On Error GoTo 0
If n2 = False Then
MsgBox "User cancelled"
Exit Sub
End If
If n1 = 0 And n2 = 0 Then
MsgBox "STOP!"
End If
MinPer = 1 - (Val(n1) / 100)
MaxPer = 1 + (Val(n2) / 100)
This is because the number "10" has a "0" in the string (second character) so both evaluate to true.
Try this instead:
If (MinPer = "0") And (MaxPer = "0") Then
MsgBox "STOP!"
End If
For additional control save the user input (MinPer , MaxPer) and THEN text them for validity before performing nay mathematical operations on them.
InStr(MinPer, "0") is just checking to see whether the string contains a zero
character.
You need to convert the string value to an integer. Use the IsNumeric and CInt functions
to do that. See this URL:
vba convert string to int if string is a number
Dim minPerINT as Integer
Dim maxPerINT as Integer
If IsNumeric(minPer) Then
minPerINT = CInt(minPer)
Else
minPerINT = 0
End If
If IsNumeric(maxPer) Then
maxPerINT = CInt(maxPer)
Else
maxPerINT = 0
End If
If minPerINT = 0 and maxPerINT=0 Then
MsgBox "STOP!"
End If
Depending on what data can be entered It may also be a good idea to check if the length
of the data is zero using the len() function.