VBA Excel R1C1Formulas using cells method - vba

I've run accross this problem many times and still haven't found the solution or why this won't work. I want to use cells method to enter a formula through a column and so I write this:(just an example)
With ws
iEndCol = .cells(4650,1).End(Xlup).Column
For i = 2 To iEndCol
.Cells(i, 2) = "=VLOOKUP([RC-1],Somesheet!someTable,10,FALSE)"
Next
End With
when this dosen't work (Method error) I try something like this:
Cells(i,2).Select
Do While IsEmpty(ActiveCell.Offset(0, -1)) = False
ActiveCell.Formula = "=VLOOKUP([RC-1],Somesheet!someTable,10,FALSE))"
ActiveCell.Offset(1, 0).Select
Loop
or instead of .Formula, I try .FormulaR1C1, .Formulalocal etc. and this doesn't work either. Then this is what works:
Range("B2").Select
Do Until IsEmpty(ActiveCell.Offset(0, 5)) And IsEmpty(ActiveCell.Offset(0, 6))
If IsEmpty(ActiveCell) = False Then
ActiveCell.Offset(0, 1).Formula = "=VLOOKUP(B2,Somesheet!someTable,10,FALSE)"
End If
ActiveCell.Offset(1, 0).Select
Loop
What am I not understanding on using Cells to enter formulas?

Enter a formula using Excel interface (not your code).
Now go to the code editor, press Ctrl+G and type: ? activecell.FormulaR1C1
The result, =VLOOKUP(RC[-1],Somesheet!sometable,10,FALSE), will tell you what you are doing wrong. You are not providing correct RC syntax.
Having that said, you should always ensure your formula syntax matches the property you have picked to set that formula. Use A1 notation for .Formula, and RC notation for FormulaR1C1. And don't use .Value to set a formula.

First, the following worked for me:
Set oCell = ActiveCell
Do
Set oCell = oCell.Offset(0, 1)
oCell.FormulaR1C1 = "=VLOOKUP(RC[-1],SomeTable,10,FALSE)"
Set oCell = oCell.Offset(1, -1)
Loop Until IsEmpty(oCell)
Notice that in my syntax, I assumed that SomeTable was a defined name with Workbook scope and thus I need no prefix. If SomeTable is a defined name scoped to a specific Worksheet, only then do you need to prefix the sheet name (e.g. Somesheet!SomeTable).
Second, you should verify in which cell it is trying to put the formula using Debug.Print oCell.Address. It may be the case that it is trying to stuff the formula in literally the first column which would cause an error in the formula.

Related

Populating an excel file from word vba

I'm writing a macro that will populate an excel file with user inputs from active x controls in word. I've got almost everything working except that I keep getting an error message when I try and select cell A1 in the sheet that I want to use in the workbook. Here is the code:
Workbooks.Open ("mypath\myfile.xlsm")
Workbooks("myfile.xlsm").Activate
Worksheets("sheet1").Select
Range("A1").Select
Do Until (IsEmpty(ActiveCell.Value))
ActiveCell.Offset(1, 0).Select
Loop
ActiveCell.Value = n
ActiveCell.Offset(0, 1).Value = a
ActiveCell.Offset(0, 2).Value = b
ActiveCell.Offset(0, 3).Value = c
Columns("D:D").EntireColumn.AutoFit
Columns("A:A").EntireColumn.AutoFit
Columns("B:B").EntireColumn.AutoFit
Columns("C:C").EntireColumn.AutoFit
Workbooks("myfile.xlsm").Save
Workbooks("myfile.xlsm").Close
The variables in this block of code are the values of the active x controls and are located much further up in the sub. This block of code is a small part of an if statement within the sub. Anyhow, when I take Range("A2").Select out of the code, it works just fine except for the fact that the information that I want to input does not go to the right spot (since it didn't select range A1 to begin with).
The error I get is type mismatch 4218.
Referencing the Excel object model gives you access to some global objects defined in that object model.
VBA resolves identifiers in this order:
Current procedure
Current module
Current project
VBA standard library
Host application object model
Any other referenced library, in the order they appear in the references dialog
So when you invoke Range meaning to be a call to the Excel object model, you actually invoke the same-name Range global member that's defined in the Word object model.
Note I say member and mean it: these are unqualified member calls to Global.Range. This is important, because a member implies an object, and since everything in the Excel object model (Word's too) has an Application property, then if you're not explicit about exactly what you're referring to, you might be implicitly creating an Excel.Application object, that you can't quite clean up properly. This usually translates into a "ghost" EXCEL.EXE process lingering in Task Manager well after your macro finishes running.
The trick is to make that reference explicit, and explicitly constrain its lifetime - a With block is perfect for this:
With New Excel.Application
With .Workbooks.Open(path)
With .Worksheets("Sheet1")
lRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
.Cells(lRow, 1) = n
.Cells(lRow, 2) = a
.Cells(lRow, 3) = b
.Cells(lRow, 4) = c
.Columns("A:D").EntireColumn.AutoFit
End With
.Save
.Close
End With
.Close
End With
I'm guessing as I don't usually run Excel from Word, but I think the problem might be related to everything being unqualified from Word.
If Workbooks.Open is working, then we can just hang everything related to that workbook on that..
Try the following code instead:
Dim myWkBk As Workbook, lRow As Long
Set myWkBk = Excel.Application.Workbooks.Open("mypath\myfile.xlsm")
With myWkBk.Sheets("sheet1")
lRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
.Cells(lRow, 1) = n
.Cells(lRow, 2) = a
.Cells(lRow, 3) = b
.Cells(lRow, 4) = c
.Columns("A:D").EntireColumn.AutoFit
End With
myWkBk.Save
myWkBk.Close
I've got it figured out. #Cindy Meister I just needed to add an ActiveSheet. qualifier on the troubled line:
Workbooks.Open ("H:\Second Rotation\OBI project\answersUsers.xlsm")
Workbooks("answersUsers.xlsm").Activate
Sheets("Answers Users").Select
ActiveSheet.Range("A1").Select
Do Until (IsEmpty(ActiveCell.Value))
ActiveCell.Offset(1, 0).Select
Loop
ActiveCell.Value = n
ActiveCell.Offset(0, 1).Value = cwid
ActiveCell.Offset(0, 2).Value = mann
ActiveCell.Offset(0, 3).Value = dept
Columns("A:D").EntireColumn.AutoFit
Workbooks("answersUsers.xlsm").Save
Workbooks("answersUsers.xlsm").Close
Dim myWkBk As Workbook, lRow As Long

Copying to a Macro if there is a "-" in a certain cell (VBA)

I am trying to copy some cells in the same sheet if there's a "-" or a "/" in a certain cell.
According to the number of "-" or "/" is the number of times it is going to copy.
This is my code but it's not working, can anyone help?
Sub TWB_Copy_columns()
'TWB_Copy_columns Macro
Dim celltxt As String
Range("B14").Select
Selection.End(xlToRight).Select
celltxt = Selection.Text
If InStr(1, celltxt, "-") Or InStr(1, celltxt, "/") Then
Range("BA5:BB36").Select
Selection.Copy
Range("BD5").Select
ActiveSheet.Paste
Range("BG5").Select
End If
End Sub
It seems that you are looking at the displayed format of a cell's contents to determine if it is a date or not. There is a native VBA function, IsDate that does this determination quite well on true dates. If your data does noot contain dates as true dates, well.. they should be true dates so that is another problem to be fixed.
with worksheets("sheet1")
if isdate(.cells(14, "B").end(xltoright)) then
.range("BA5:BB36").copy destination:=.range("BD5")
end if
end with
It seems to me that this code is only reusable if BA5:BB36 is not static but you've provided no indication on what determines the location. It's probably the last two columns of data in your data block but that is only a guess.
Here's the refactored and fixed version:
Sub TWB_Copy_columns()
'TWB_Copy_columns Macro
'Range("B14").Select
'Selection.End(xlToRight).Select
'celltxt = Selection.Text
' Use explicit references and avoid select. In this case, you will need to
' qualify the workbook and sheetname of the range you are using. We can then
' directly access the value of that range.
' Also, no need to declare a string just to hold onto the value. Directly use the value instead
With ThisWorkbook.Sheets("Sheetname")
If InStr(1, .Range("B14").End(xlToRight).value, "-") > 0 Or InStr(1, .Range("B14").End(xlToRight).value, "/") > 0 Then
.Range("BD5:BB36").value = .Range("BA5:BB36").value
End If
End With
End Sub
First, always avoid Select and Activate. In this case, I directly assign the values instead of trying to copy, paste, or select. Any time you see Range("A5").Select; Selection.Value you really need Range("A5").Value. Likewise, never have an unqualified range. Range("A5") is the same as saying ActiveSheet.Range("A5") which can complicate things if the wrong sheet is active.
Finally, if you are literally using a variable for one comparison, use the direct value. There's no need to create a variable for just one task (at least in my opinion).
Edit:
As Ralph suggests, consider reading this thread: How to avoid using Select in Excel VBA macros. Once you learn to avoid Select your abilities will skyrocket.
This does what I think you're looking for (for every "-" or "/", copy Range("BA5:BB36") and paste it to Range("BD5"), Range("BG5") - leaving a space in your columns):
Sub TWB_Copy_columns()
'TWB_Copy_columns Macro
Dim celltxt As String
Dim vWords As Variant
Dim rFind As Range
Dim i As Long
celltxt = Range("B14").Value
celltxt = Replace(celltxt, "-", "/")
vWords = Split(celltxt, "/")
Range("BA5:BB36").Copy
Range("BD5").Activate
For i = 1 To UBound(vWords)
ActiveCell.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
ActiveCell.Offset(0, 2).Activate
Next
End Sub

How to add a Formula To Cell using VBA [duplicate]

This question already has answers here:
How do I put double quotes in a string in vba?
(5 answers)
Closed 1 year ago.
I am attempting to write some VBA which will add header text to 3 cells then fill a formula all the way down to the last row. I have written the below, which writes the headers no problems, but when it get's to my first .Formula it throws a
Application Defined or Object Defined error
What needs to be altered so that this macro will execute successfully? (The formulas were pulled directly from the formula in the cell, so I know they are valid formulas at least on the "front-end")
Function Gre()
Range("E2").Select
ActiveCell.FormulaR1C1 = "Under"
Range("F2").Select
ActiveCell.FormulaR1C1 = "Over"
Range("G2").Select
ActiveCell.FormulaR1C1 = "Result"
With Range("E2:E" & Cells(Rows.Count, "C").End(xlUp).Row)
.Formula = "=IF(C2<B2,B2-C2,"")"
End With
With Range("F2:F" & Cells(Rows.Count, "C").End(xlUp).Row)
.Formula = "=IF(C2>B2,C2-B2,0)"
End With
With Range("G2:G" & Cells(Rows.Count, "C").End(xlUp).Row)
.Formula = "=IF(F2>0,'Issue',"")"
End With
End Function
The problem is likely that you are escaping the quotes with the formula.
What you need is:
.Formula = "=IF(C2>B2,B2-C2,"""")"
for the first one, for example. The other quotes need to be doubled as well.
As a side-note, it would also be best to specify the sheet you are working on with something like:
Dim ws as worksheet
Set ws = Sheets("mySheet")
ws.Range("E2").FormulaR1C1 = "Under"
etc.
If you don't do this, you can sometimes have errors happen while running the code.
As suggested by OpiesDad, to minimize ambiguity, avoid ActiveCell and the like.
Using Select will also slow down performance a lot compared to assigning to cells directly.
I'm pretty sure you need to escape quotes in Excel formulas inside of VBA by doubling the quotes, so a normal empty string becomes """". You also have Issue in single quotes in a formula, which I'm pretty sure will error in Excel; that should be in escaped double quotes as well.
I'm having a hard time figuring out what Range("E2:E" & Cells(Rows.Count, "C").End(xlUp).Row) actually does, but it sounds like you want to select E2 to the last used row of the sheet. Avoid Rows.Count or just generally referring to the rows of a sheet, as that will go to row 10^31. Use Worksheet.UsedRange to get the range from the first row and column with content to the last row and column with content. This also includes empty strings and can be a bit tricky sometimes, but is usually better than dealing with thousands of extra rows.
Also,
You don't need to use With if your only enclosing one statement, although it won't cause any problems.
I would not mix use of Range.Formula and Range.FormulaR1C1 unless you have a reason to.
Function Gre()
Dim ws as Worksheet
Set ws = ActiveSheet
Dim used as Range
Set used = ws.UsedRange
Dim lastRow as Integer
lastRow = used.Row + used.Rows.Count - 1
ws.Range("E2").Formula = "Under"
ws.Range("F2").Formula = "Over"
ws.Range("G2").Formula = "Result"
ws.Range("E2:E" & lastRow).Formula = "IF(C2<B2, C2-B2, """")"
ws.Range("F2:F" & lastRow).Formula = "IF(C2<B2, C2-B2, 0)"
ws.Range("G2:G" & lastRow).Formula = "IF(F2>0, ""Issue"", """")"
End Function
The first issue is the selecting of cells. This requires the macro to select the cell, then determine the cell address. If you need to actually select a cell, use Application.ScreenUpdating = False. Then the macro doesn't have to show the cursor selection of a cell. Dropping the select and incorporating the range into the formula assignment code line like below will gain some speed/efficiency.
Range("E2").FormulaR1C1 = "Under"
Range("E2:E" & Cells(Rows.Count, "C").End(xlUp).Row) is the code version of selecting the last cell in a blank column (row 1048576), then using the keystroke of ctrl and the up key to determine the lowest/last used cell. This gets you a row count of 1 every time since the column is blank. Since you're looking for the last row. It may be faster to count down from the top. My favorite method for this is a loop. Increment a variable within a loop, while looking for the last row. Then, the variable can be used instead of your bottom up strategy.
t = 0
Do Until Range("C2").Offset(t, 0).Value = ""
t = t + 1
Loop
With Range("E2:E" & t)
.Formula = "=IF(C2<B2,B2-C2,"""")"
End With`
Just like TSQL, quote characters need their own quote characters.
.Formula = "=IF(C2<B2,B2-C2,"""")"
The Range Fillup VBA function can be utilized in this case to fill all cells from the bottom with a common formula, accounting for Excel Formula Reference Relativity. The code below starts with the range that we got from the loop counter. Next, we set a variable equal to the total rows in Excel minus the row corresponding to the counter row. Then, we resize the original region by the necessary rows and use the FillDown function to copy the first formula down.
Here's the resulting code. This will fill the range starting from the last row in Excel.
Sub Gre()
Range("E2").FormulaR1C1 = "Under"
Range("F2").FormulaR1C1 = "Over"
Range("G2").FormulaR1C1 = "Result"
Do While Range("e2").Offset(t, 0).Value <> ""
t = t + 1
Loop
Range("E2").Offset(t, 0).Formula = "=IF(C2<B2,B2-C2,"""")"
r1 = Range("e2").EntireColumn.Rows.Count
r2 = Range("E2").Offset(t, 0).Row
Range("E2").Offset(t, 0).Resize(r1 - r2, 1).FillDown
Range("F2").Offset(t, 0).Formula = "=IF(C2>B2,C2-B2,0)"
Range("F2").Offset(t, 0).Resize(r1 - r2, 1).FillDown
Range("G2").Offset(t, 0).Formula = "=IF(F2>0,""Issue"","""")"
Range("G2").Offset(t, 0).Resize(r1 - r2, 1).FillDown
End Sub
As well as using double quotes you may need to use 0 in the first two formula otherwise they may evaluate to empty strings. This may give unexpected results for the last formula i.e. incorrectly return "Issue".
If you do not have blank columns between your data and the 3 new columns you can use CurrentRegion to determine the number of rows:
Range("E2:E" & Cells.CurrentRegion.Rows.Count).Formula = "=if(C2'<'B2,B2-C2,0)"
Range("F2:F" & Cells.CurrentRegion.Rows.Count).Formula = "=if(C2>B2,C2-B2,0)"
Range("G2:G" & Cells.CurrentRegion.Rows.Count).Formula = if(F2>0,""Issue"","""")"
Please try the following sample hope it will help you to wright formula in VBA
Sub NewEntry()
Dim last_row As Integer
Dim sht1 As Worksheet
Dim StockName As String
Set sht1 = Worksheets("FNO MW")
last_row = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
'MsgBox last_row
StockName = sht1.Cells(last_row, 1).Value
sht1.Cells(last_row, 1).Formula = "=RTD(""pi.rtdserver"", ,"" " & StockName & " "", ""TradingSymbol"")"
End Sub

VBA Right-Function returning wrong data type

I have written a very simple code which returns the last 6 characters of every active cell within a range.
The code works pretty good until it finds a particular cell in which the characters to be returned should be: "MARC01". Unfortunately it returns a date type character (01.Mrz).
By using the normal excel formula it works fine, that is why I would expect it to work with a Macro as well.
Here you can see my code which takes the strings from column "A" and enters it in column "B":
Range("B12").Activate
Do
ActiveCell.Value = Right((ActiveCell.Offset(0, -1).Value), 6)
ActiveCell.Offset(1, 0).Activate
Loop Until ActiveCell.Offset(0, -1).Value = 0
Excel likes to change anything that looks like a possible date to a date. To force this not to happen put a "'" in front of the formula.
ActiveCell.Value = "'" & Right((ActiveCell.Offset(0, -1).value), 6)
This will force it to stay text. The down side to this is, if it is a number it will be saved as text.
Excel likes to try to interpret certain data, rather than just leaving it as is. It especially does that with strings that look like dates, and with numeric entries.
Two ways to workaround are
Put the text prefix character in front of your string. This is usually a single quote. (see Scott's answer for code)
Format the cell as Text before you place the value there.
Sub foo()
Range("B12").Activate
Do
ActiveCell.NumberFormat = "#"
ActiveCell.Value = Right((ActiveCell.Offset(0, -1).Formula), 6)
ActiveCell.Offset(1, 0).Activate
Loop Until ActiveCell.Offset(0, -1).Value = 0
End Sub
With this simple goal, I don't know why you need VBA looping.
You can just mass set the formular1c1 to =RIGHT(RC[-1],6).
Option Explicit
Sub Right6()
Const R6LeftCol = "=RIGHT(RC[-1],6)"
Dim oRng As Range, lRow As Long
lRow = Cells(Rows.Count, "A").End(xlUp).Row
Set oRng = Range("B12")
Range(oRng, Cells(lRow, "B")).FormulaR1C1 = R6LeftCol
Set oRng = Nothing
End Sub

VBA Loop through range and replace value in adjacent row cell

I have a question regarding some code which doesn't seem to be working properly for me.
I have set up some code for what I believe is a basic loop through range and replace adjacent row cell, and although no errors are occurring I am not getting the desired result.
If anyone knows better could they look through the code below and give me some advice / a fix to get things rolling:
For Each cCell In Range("C16,C1000")
'perform action if cell value = "-"
If ActiveCell.Value = "-" Then
'move to adjacent cell
ActiveCell.Offset(0, 1).Select
'change the cell value to "-"
Selection.cell.Value = "-"
Else
ActiveCell.Offset(0, 1).Select
End If
Next cCell
Rather than using ActiveCell.Value you should just use cCell.Value
Also, avoid using Select. It's evil.
For example:
cCell.Offset(0,1).Value = "-"
yes avoid using select. But if you have to, you need to do this. You have to select cCell in each iteration so that ActiveCell picks it up.
You don't need to use Select though and shouldn't, you can still update cCell without selecting it first. As stated by joseph4tw.
For Each cCell In Range("C16,C1000")
'perform action if cell value = "-"
cCell.select
If ActiveCell.Value = "-" Then
'edit adjacent cell
ActiveCell.Offset(0, 1).Value = "-"
End If
Next cCell