Variable inside formulaR1C1 for offseting by column using relative referencing - excel

Hey this has been killing me. Look up some stuff here and found some answers that don't make sense. This is the code and it works to find a location and pull a variable from that location.
Range("G7:J7").Select
ActiveCell.FormulaR1C1 = "='Test Macro'!R[-3]C[-5]"
I need to make the R[-3]C[-5] change to R[-3]C[-4] and so forth to select new data in each column. I have created a variable (macroBegin) that is used to do this. I tried many variation, but essentially, I'm trying to do this:
Range("G7:J7").Select
ActiveCell.FormulaR1C1 = "='Test Macro'!R[-3]C[-5+(macroBegin-1)]"
What is the substitute for my poor syntax? Thanks!

Use,
Range("G7:J7").Select ActiveCell.FormulaR1C1 = _
"='Test Macro'!R[-3]C[" & macroBegin - 6 & "]"
I believe the maths are correct there but double check; the string concatenation is right.

Related

VBA Dynamically Building A Formula From An Array

I am trying to dynamically construct a formula based on an array that I have generated from a cell (separated by commas), as there is a varying amount of elements in the array I need to append a new "formula block" with the updated element to use in a if statement that is generated after the for each loop. VBA is throwing a type mismatch error in the InvestigateFormula = line, here is my code:
For Each Type In ToIgnore()
InvestigateFormula = "(ISNUMBER(SEARCH(*" & ToIgnore(Type) & "*," & _
AssetTypesCol & "2)),"
FullFormula = InvestigateFormula & FullFormula
Next Asset
FinalInvestigateFormula = "=IF(OR" & FullFormula & "),""Ignore"", """")"
ActiveCell.Formula = FinalInvestigateFormula
Please let me know if there is an easier way of doing this or how I might be able to correct the above code. Btw I am not declaring a variant I am simply declaring ToIgnore() as String and using the split function from the variable which contains the comma separated values to generate the array/items to loop over.
"Type" is a reserved name? Try strType instead?

Use String text as Code in Visual Basic for Excel

For various reasons, I need to concatenate a text of the form [NAME].Value by changing the value of NAME to an inputbox entry.
Something like this:
Sub example()
data_in = InputBox("Give me something: ")
mystring1 = "[" & data_in & "].Value"
a = Evaluate(mystring1) 'I know this is wrong, but I don't know how to do so.
End Sub
I know it can be done in other ways, and the example in which I want to use this code is not exactly this one, and while it can be done in several ways here, in the original code it can only be done this way.
I want, based on the input in the imputbox, to concatenate the string in whatever way, and subsequently cast that string as code to store the value in another variable, to be used later in the code.
I am not able to get VBA to read the string text as code. I have seen that there is a way that consists of creating a macro from this first macro, execute it, and then delete the recently created macro. The problem with this solution is that doing that I can't save the variable when returning to the initial macro (I don't want to use global variables).
Surely there must be a way?
Thank you very much.
EDIT: The code above returns Error 2015
In order to use a string as if it was code, you can use the evaluate function (exists in most languages)
The official documentation mentions this example:
[a1].Value = 25
Evaluate("A1").Value = 25
trigVariable = [SIN(45)]
trigVariable = Evaluate("SIN(45)")
Set firstCellInSheet = Workbooks("BOOK1.XLS").Sheets(4).[A1]
Set firstCellInSheet = _
Workbooks("BOOK1.XLS").Sheets(4).Evaluate("A1")
I have figured out the easiest way to do it, sorry for posting the question so soon.
Thanks to #Andreas for the solution. I'll write it here in case than could be useful to someone.
Sub example()
data_in = InputBox("Give me something: ")
a = Range(data_in).Value
Debug.Print a
End Sub
In the end the simplest thing is the last thing you try...

Separating a String into two - VBA [duplicate]

This question already has answers here:
How to extract file name from path?
(16 answers)
Extract filename from path [duplicate]
(9 answers)
Closed 1 year ago.
Background:
I have written some VB to search through a directory for a file (the date of the file will be variable, hence the wildcard) the code will then open the file, copy a list of names to another spreadsheet, store the names in an array so I can return their relative position in the other spreadsheet - pos, I need to do this as the next part of the code writes a link to that spreadsheet.
My filename search code is as follows:
Dim lcFound As String
lcFound = Dir("C:\Users\KDelaney\Desktop\*XYZ Select XYZ List.xlsm")
If lcFound <> "" Then
Workbooks.Open Filename:=lcFound
End If
Not going to add all the code as I don't think it's relative to the question. The writing a link formula to each cell in a f loop is as below, the below code was fine before I was using the file search, as I was testing it with the full file name and path:
Cells(f, 4).Formula = "=" & "'" & lcPath & "[" & lcFile & "]" & "Template" & "'!" & "AB" & pos
Question:
Basically the question is what would be the best way to convert C:\Users\KDelaney\Desktop\*XYZ Select XYZ List.xlsm into lcPath and lcFile, or is there a way round separating the strings? (Have briefly tested it unseparated but it seems like the square brackets around the filename is required).
I'm guessing the best course of action would be using InStr function? to return the position of the end of the file path? e.g. I know the filepath will always end with "Desktop\" so if I use InStr to return that position I will then know the filepath is between 1 and the returned value of InStr. However this is where I have stalled, not sure where to go from here, in terms of separating the two strings. I also know the start of the file name will always begin with a number and end with the file extension. I am probably making a meal of this problem and someone will come back with a very simple solution (hopefully)
Any help would be appreciated. Apologies if the question was too in depth just wanted to give you the full picture.
Thanks.
Sorry for:
a) Not researching enough if the question has already been asked/answered
b) answering my own question
Link contains two good answers, a function and using file system object.
How to extract file name from path?
I am going to persevere using the split function for my own knowledge and if things don't go well I will resort to one of the other two methods in the link above.
Further edit: haven't cleaned the code up yet, but I have realised I was massively overcomplicating the problem, all it required was a bit of messy string manipulation. If anyone comes across a similar problem:
Dim WrdArray() As String
Dim lcFound As String
strPath = "C:\Users\KDelaney\Desktop\*XYZ Select XYZ List.xlsm"
newstrL = InStrRev(strPath, "\")
newstrL = newstrL - 1
strlen = Len(strPath)
lnPath = strlen - newstrL
MsgBox Left(strPath, lnPath)
Definitely not the best way of doing it, have realized there are 'multiple ways to skin a cat' in this situation.
Link below for lots of info on string manipulation:
https://www.excel-easy.com/vba/string-manipulation.html

Comparing Textbox value to cell value

I programmed a communication tool for the production floor. This tool will register what they have done, who has done it and on what time.
The following should check whether the textbox value equals the value in the worksheet or if the textbox (textbox is TextTools1) is empty. If this is true, then nothing should happen and the thus the value of the textbox is gonna stay the same.
If the textbox is not empty or is not equal to what has been previously saved in the worksheet (thus the value has changed), then it should be registered which operator has done it and what date and what time.
It works when the textbox is empty, but when the value of the textbox has stayed the same (thus TextTools.value=ActiveCell.Offset(0,23).value (Correct)) it still adds the operators name, date and time.
Something is going wrong when trying to compare the textbox value and the cell value, but cant put my finger on it.
Sheets("Checklist & overdracht").Visible = True
Sheets("Checklist & overdracht").Select
If TextTools1.Value = Range("AZ1").Value Or TextTools1.Value = Empty Then
Sheets("Checklist & overdracht").Select
rowloc1.Value = ActiveCell.Row
ActiveCell.Offset(0, 23).Value = TextTools1.Value
Else
Sheets("Checklist & overdracht").Select
rowloc1.Value = ActiveCell.Row
ActiveCell.Offset(0, 23).Value = TextTools1.Value & " " & "(" & cboOperator.Value & " " & Format(DateValue(CStr(Now)), "short date") & " " & Format(TimeValue(CStr(Now)), "hh:mm") & ")"
End If
Edit; changed it to the code above. I tested this in another userform (and used f8) and it works brilliantly, but when I put in the userform that will actually run this code, than it doesnt have the same result...
Edit2; So apparently something goes wrong with Range(AZ1).Value reference. Because when I enter a random value instead of the range and then run the code, it does work. Is there a different way of referencing?
Ok based on your comments
Stop using active cell when code from a user form is communicating to the compiler what sheet is what. You need to fully qualify what sheet you are using. Im not entirely sure where in the code the active sheet is being set but I am fairly certain the answer is never. Another reason selecting and referencing .ActiveWhatever is bad is a cardinal sin of vba is interacting with the actual application object instead of doing everything in memory. It bogs everything done and performance suffers considerably. When you start writing pretty dense stuff then you will inevitably suffer from issues where the compiler gets confused as to what thing it should be looking at and you'll have a grand ol' time of troubleshooting that nonsense.
Also, it might be a good idea to check for more than just "=Empty". What if there is a null or empty string? I tend to check for:
.value = "" OR ISNULL(.Value)=True OR .Value = vbNullstring
this isnt real feedback though - tons of people have different ways of doing the same thing.
Try:
Thisworkbook.Sheets("YOURSHEETNAME").Range("YOURRANGE").Offset(0,23).Value = Someothervalue.
Let me know if youre still facing issues.

Overwriting a formula in Excel using VBA

Here is the formula in question.
.Range("F5").Formula = "=SUMPRODUCT(--(I23:I29>='Raw Data'!K2),--(I23:I29<='Raw Data'!K3))"
This works fine, but what I want is instead of I23:I29, I want it so that when I did a "lastrow" formula in excel VBA, it will replace the I29, with the I and whatever the response in the last row actually is.
I figured that to make this happen I'd have to break the parentheses, but I wasn't sure if it was the correct thing to do.
What I thought I'd have to do is this:
.Range("F5").Formula = "=SUMPRODUCT(--(I23:I" & lastrow">='Raw Data'!K2),--(I23:I" & lastrow"<='Raw Data'!K3))"
But it doesn't look right. And Excel is giving me a redline for it as well, so I know I'm not doing it correctly. Can someone help me figure out this little nightmare?
Close - watch out, and make sure the & are between every part of the string build:
.Range("F5").Formula = "=SUMPRODUCT(--(I23:I" & lastrow & ">='Raw Data'!K2),--(I23:I" & lastrow & "<='Raw Data'!K3))"

Resources