How to reference cell from another sheet in Module - Excel VBA? - sql

I have a macro in an Excel workbook that updates date from Sheet1 into SQL by clicking a button in Sheet3. Sheet3 also have cells used as parameters during the update process.
Currently, the macro is placed in a module and my SQL statement is as follows:
sSQLUpd = "update [table1].[dbo].[Plan] set [Plan_QTY] = " & Plan & "_
where [MacID] = " & Mac & " and [ModelID] = " & Mdl & " and [Date] = " & dt & "_
and DATEPART(year,[Date])= " & Sheets("Sheet3").Cells(3, 3).Value & "_
and DATEPART(month,[Date])= " & Sheets("Sheet3").Cells(3, 6).Value & ""
conn.Execute sSQLUpd
But when I test the code I keep getting "Subscript out of range" in my error handler.
The SQL structure is fine, since I tested it by replacing the parts:
DATEPART(year,[Date])= " & Sheets("Sheet3").Cells(3, 3).Value & "
and
DATEPART(month,[Date])= " & Sheets("Sheet3").Cells(3, 6).Value & "
with actual numbers and the data can pass.
So it's safe to assume that the codes referencing the cells in Sheet3 have issue. Perhaps it doesn't want to play nice when placed in a module?
I even tried different variations as well:
DATEPART(year,[Date])= " & Sheets("Sheet3").range("C3").Value & "
No dice....
Anything I can do to modify it?

Wait... Never mind. I figured out what went wrong. All I needed to do was change
Sheets("Sheet3") into Sheet3 only:
DATEPART(year,[Date])= " & Sheet3.Cells(3, 3).Value & "
Its always the simple stuff that screws with me. :p

Related

Excel VBA - insert formula in a set of rows with variable reference directly or replacing a string for example "\=" with "="

I have the goal to write a formula in a set of rows. Some references in the formula have to change each row.
I implemented the following script:
Dim i As Integer
Dim formcolM As String
Dim temprng As String
For i = 0 To 100
formcolM = "NUMBERVALUE(IF(Q" & i & "=""Bedarf kum."";A" & i & ";IF(Q" & i & "=""Ist"";OFFSET(A" & i & ";-1;0);IF(Q" & i & "=""Lz."";OFFSET(A" & i & ";-2;0);IF(Q" & i & "=""Ist+Lz.-Bedarf"";OFFSET(A" & i & ";-3;0);)))))"
Let temprng = "M" & i
Range(temprng).Select
ActiveCell.Value = "\=" & formcolM
next i
With this script I am writing a string each row in my excel table at column M.
I noticed that if the formula hasn't the symbol "\" , you can find an error .
In order to avoid the error I thought to leave the symbol "\" and to use a trick deleting it after (because I don't know how to solve with R1C1 formula. I read some answers on Stackoverflow, but unfortunately I did not understand )
The replacing script after the for cycle:
Columns("M:M").Replace What:="\=", Replacement:="=", LookAt:=xlPart
The strange thing is that the macro doesn't delete it.
Infact when the script finishes , it seems that nothing happened, without errors. But if I want substitute "\=" with another symbol, for example "*", the replacing script works.
I did not understand if the problem is :
the replace method did not recognized the symbol "=" to search
I cannot use the replace method because the symbol "=" disturbs in some way , I don't know in what.
OR, is there another simplest way to get this task done?
Someone could help me in order to fix? I should have the formula working in the column M , automatically with vba (not with another formula in the excel sheet) .
Thanks in advance for your time.
We can apply the formula directly. The issue is that vba is very US-EN Centric and all formula when using the .Formula needs to be in that format.
Also since your formula refers to values in a row 3 above the one in which it is put we need to start the loop at 4 not 0. There is no row 0
There are two ways, in US-En format with English functions and , as the deliminator using .Formula:
Dim i As Integer
For i = 4 To 100
Range("M" & i).Formula = "=NUMBERVALUE(IF(Q" & i & "=""Bedarf kum."",A" & i & ",IF(Q" & i & "=""Ist"",OFFSET(A" & i & ",-1,0),IF(Q" & i & "=""Lz."",OFFSET(A" & i & ",-2,0),IF(Q" & i & "=""Ist+Lz.-Bedarf"",OFFSET(A" & i & ",-3,0),)))))"
Next i
Or using .FormulaLocal and the formula as you would write it in your native tongue.
Dim i As Integer
For i = 4 To 100
Range("M" & i).FormulaLocal = "=NUMERO.VALORE(SE(Q" & i & "=""Bedarf kum."";A" & i & ";SE(Q" & i & "=""Ist"";SCARTO(A" & i & ";-1;0);SE(Q" & i & "=""Lz."";SCARTO(A" & i & ";-2;0);SE(Q" & i & "=""Ist+Lz.-Bedarf"";SCARTO(A" & i & ";-3;0);)))))"
Next i
By the time I got this worked out, Scott already had an answer. I just wanted to post your original code modified to work. I would suggest his method.
Sub TestScript()
Dim i As Integer
Dim formcolM As String
Dim temprng As String
For i = 4 To 100
formcolM = "NUMBERVALUE(IF(Q" & i & "=" & "Bedarf kum." & ";A" & i & ";IF(Q" & i & "=" & "Ist" & ";OFFSET(A" & i & ";-1;0);IF(Q" & i & "=" & "Lz." & ";OFFSET(A" & i & ";-2;0);IF(Q" & i & "=" & "Ist+Lz.-Bedarf" & ";OFFSET(A" & i & ";-3;0);)))))"
temprng = "M" & i
Sheets("Sheet1").Range(temprng).Select
ActiveCell.Value = " = " & formcolM
Next i
End Sub

Excel custom hyperlink for each cell in range using VBA

I have a module that removes all formulas from an entire sheet and then, it should, create a hyperlink formula on each cell using the cell value.
Sub Test()
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Test")
ws1.Range("B33:F533").Value = ws1.Range("B33:F533").Value
For Each i In ws1.Range("B33:B533")
i.Formula = "=HYPERLINK(""https://somelocation/" & i.Value & """,""" & i.Value & """)"
Next
End Sub
EDIT: It's now working perfectly. Thanks For all the help!
i.Formula = "=HYPERLINK('https://somelocation/"&i.Value&","& i.Value"')"
Has an error in the formula. At the i.Value"') you are missing &, i.Value & "'. The correct one, that 'compiles', is added below:
i.Formula = "=HYPERLINK('https://somelocation/" & i.Value & "," & i.Value & "')"
Also it is worth noting that instead of writing "&i.Value&" and let the VBA IDE add the spaces, it is better to do it yourself, eg: " & i.Value & ".
You're code has 2 flaws, you should add the last & to get a syntax correct formula, and add spaces between the " and &, or else VBA won't see it is right.
Edit; a third flaw:
The line to create the formula is wrong too. Let's break it down:
"=HYPERLINK('https://somelocation/" & i.Value & "," & i.Value & "')"
The parameter in the formula would be:
'https://somelocation/" & i.Value & "," & i.Value & "' so an output example of this line could be 'https://somelocation/1,1'. At first, I thought you are writing an URL with a comma, alright..? But then I looked at the HYPERLINK function in Excel and it requires two parameters. You are only giving one parameter. Excel formulas also expect a double quote instead of a single quote. You can escape a double quote in VBA like this "".
The correct line should be:
i.Cells(1, 1).Formula = "=HYPERLINK(""https://somelocation/" & i.Value & """,""" & i.Value & """)"

VBA: Cell designations not being evaluated

I have the following code in VB:
ActiveCell.Formula = " = COMPANYNAME " & " & " & "R[-12]C[-3]" & " & " & "VLOOKUP(RC[-6],R3C7:R22C18,9)"
I want to get a cell that has in it: = COMPANYNAME & D25 & VLOOKUP(A26,$G$3:$R$22,9)
Instead, I get a cell with = COMPANYNAME & R[-12]C[-3] & VLOOKUP(RC[-6],R3C7:R22C18,9)"
Basically, the cell designations are not being evaluated.
What am I doing wrong?
Change ActiveCell.Formula to ActiveCell.FormulaR1C1
By using ".Formula", it expects cells to be referenced in "A1" fashion, and therefore doesn't know how to compute the R/C references, and appears to see the whole thing as just a string instead of a formula (also you may need to remove the spaces from between the &'s).

Excel vba error name in formula

I'm trying to pass one formula from vba excel to a cell i have this code
atmFecha = "=IF(L" & tmLastRow & "=0," & Chr(34) & " " & Chr(34) & ",'ws2'!$E$3)"
.Cells(tmLastRow, "H").Value = atmFecha
this instruction insert in the cell the correct formula but display #NAME? I have to press "F2" and then "Enter" to Excel recognize the formula and display the correct value.
I use the instructions formula and formulaR1C1 but the result is the same.
what can i do to recognize automaticly the correct value of the formula ?
After your code, add this line:
Application.Calculate
It sounds like you are set to Manual Calculation, so that line will refresh everything. If you're setting a number of formulas, wait until they're all inserted, then execute that line.
I don't know how it fix but now is working, I was testing with the second file I made this is the code"
Sub btnCalculate()
Dim atmFecha As String
Dim tmLastRow As Integer
With Worksheets("ws1")
tmLastRow = 1
atmFecha = "=IF(C1=0," & Chr(34) & " " & Chr(34) & ",'ws2'!$A$1)"
.Cells(tmLastRow, "A").Value = atmFecha
End With
End Sub

MSG Box display workbook

I have an easy question but for whatever reason canĀ“t find it online. I want a msgbox to return me specific cells that apply to a set of conditions. For each cell I want it to say what workbook the cell is in.
MsgBox ("Error: " & cl.Address & " is " & cl.Value & " " & thisworkbook.Name)
is what I have in my code. What its returning is the name of the reporting workbook and not where the actual error is located.
Please help
In your situation you should go this way:
MsgBox ("Error: " & cl.Address & " is " & cl.Value & " " & cl.Parent.Parent.Name)
the final part will use hierarchy of Excel Object model- from Cell >> to Sheet >> to Workbook...