Excel Macro - Error setting cell formula - vba

I need to add a function in my worksheet using macros. I need to pass a variable to the Excel function since myWorkbook and sheetName, to which it will reference, are variable.
MyRange = Workbooks(myWorkbook).Sheets(sheetName).Range("H11:H32")
theFormula = "=SUM(" & MyRange & ")"
Range("B2").Select
ActiveCell.FormulaR1C1 = theFormula
I get error 13: Type Mismatch.
I am not an avid VBA programmer, and this is giving me a big headache. I tried defining theFormula as String but no hope.

You need to convert the Range object to a string representation of the range, for example to set the formula to =SUM($H$11:$H$32) you would;
Dim MyRange As Range
set MyRange = Workbooks(myWorkbook).Sheets(sheetName).Range("H11:H32")
theFormula = "=SUM(" & MyRange.Address(ReferenceStyle:=xlR1C1) & ")"
Range("B2").Select
ActiveCell.FormulaR1C1 = theFormula
Or if you dont want R1C1 notation you can;
ActiveCell.Formula = "=SUM(H11:H32)"

Sub MakeSum(sBookName As String, sSheetName As String)
Dim rMyRange As Range
Set rMyRange = Workbooks(sBookName).Sheets(sSheetName).Range("H11:H32")
If rMyRange.Parent.Parent.Name = ActiveWorkbook.Name Then
With ActiveSheet
'same sheet, so just use address
If rMyRange.Parent.Name = .Name Then
.Range("B2").Formula = "=SUM(" & rMyRange.Address & ")"
Else
'same workbook, different sheet, so prepend sheet name
'single quotes prevent error when there's a space in the sheet name
.Range("B2").Formula = "=SUM('" & rMyRange.Parent.Name & "'!" & rMyRange.Address & ")"
End If
End With
Else
'not the same workbook, use external address
ActiveSheet.Range("B2").Formula = "=SUM(" & rMyRange.Address(, , , True) & ")"
End If
End Sub

Progragmatically this wont work - you are saying the cell formula should equal "=SUM(" & MyRange & ")" - however when is this actually evaluated ?
does theFormula =SUM(" & MyRange & ")
work?

Related

Consolidate data in Excel with VBA

At some point I need to consolidate data (simply sum duplicated items). I would like to parameterize Sources:= argument - actually everything works the way I amused when using option after single quote mark. When using src variable I'm getting: Cannot open consolidation source file (picture attached). Looking forward for some tips.
Here is the code:
Sub Format()
' Keyboard Shortcut: Ctrl+Shift+C
'Definition
Dim wb As Workbook
Dim ws As Worksheet
Dim rg As Range
Dim lRow As Integer
Dim src As String
Set wb = ActiveWorkbook
Set ws = ThisWorkbook.ActiveSheet
'Format data
Range("H2").Select
ActiveCell.FormulaR1C1 = "=RC[-5]&""*""&RC[-4]&""*""&RC[-3]&""*""&RC[-2]"
Range("I2").Select
ActiveCell.FormulaR1C1 = "=RC[-7]"
' Find the last non-blank cell in column B(2)
lRow = Cells(Rows.Count, 2).End(xlUp).Row
Set rg = Range("H2", Cells(lRow, 9))
' AutoFill of formated data
Range("H2:I2").Select
Selection.AutoFill Destination:=rg, Type:=xlFillDefault
'Consolidate
src = """" & "'" & wb.Path & "\[" & wb.Name & "]" & ws.Name & "'!R2C8:R" & lRow & "C9" & """"
Debug.Print src
'Range("K2").Consolidate Sources:= _
"'C:\Users\pl1aji0\Documents\Projekty\USA\2020\L034.00080 Innovation\700\BPM\[test.xlsx]Sheet1'!R2C8:R11C9" _
, Function:=xlSum, TopRow:=False, LeftColumn:=True, CreateLinks:=False
Range("K2").Consolidate Sources:= _
src _
, Function:=xlSum, TopRow:=False, LeftColumn:=True, CreateLinks:=False
End Sub

Excel VBA: Formula with reference to cell in another worksheet (variable)

I am trying to create a macro that links a cell from another worksheet (this is stored as a variable called SheetName). The user is prompted with an Input box to select a cell. I would like to have a cell in another worksheet reference to the selected cell.
Here is the relevant code:
Dim WorkRng As Range
Total1 = "Select Total cell"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", Total1, WorkRng.Address, Type:=8)
Worksheets("WorksheetA").Range("C6").formula = "=" & 'SheetName.Name' & "!" & WorkRng.Address
The last line is where I am running into object errors.
Any help is greatly appreciated!
Try,
Worksheets("WorksheetA").Range("C6").formula = _
"='" & SheetName.Name & "'!" & WorkRng.Address
'note the quote here "='" and here "'!"
Where is sheetname defined? It then needs to be concatenated into the string
DIm SheetName As Worksheet
Set SheetName = Worksheets("Sheet2")
formula then
"=" & SheetName.Name & "!" & [A1:B2].Address

Creating Copies from a Master Workbook using VBA

I have two files, one the file in which I want to run the macro in and another external file.
Within the file that the macro is running in (henceforth the "master" file), there is something that looks like this:
The code that I have so far is this:
Sub test()
For i = 1 To 3
If Not Range("B" & i).Value = "X" Then
Range("C2").Value = Range("A" & i).Value
Calculate 'updates the formula
Range("B" & i).Value = "X" 'update the check
Range("D2").Copy 'this is the tricky part - this is what is needed. The formula links needs to be broken so that only the values remain
Range("D2").PasteSpecial xlPasteValues
ActiveWorkbook.SaveCopyAs "C:\Users\n0269777\Desktop\" & Range("A" & i).Value & ".xlsm" 'the problem with SaveCopyAs is that the formula originally is now overwritten.
'thus I need some way to refer back to the 'master' workbook, the one where the formula has not yet been overwritten
End If
Next i
End Sub
What I want to achieve is that the macro will loop through and check to see if a workbook has been created with the names in column A. Then, it will update the value in "C2". Finally, a copy is saved -- and the formula is overwriten to its value, rather than remain a formula. This is the difficulty in that I cannot simply save a copy of the workbook -- the formula would have been overwritten after the run of the macro.
This is what happens in Type3.xlsm after running the macro. As you can see, the value in "D2" is 1, whereas it should be 3.
I have also considered this method:
Sub test2()
For i = 1 To 3
If Not Range("B" & i).Value = "X" Then
Range("C2").Value = Range("A" & i).Value
Calculate 'updates the formula
Range("B" & i).Value = "X" 'update the check
Set wboor = ActiveWorkbook
fileaddress = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name
Range("D2").Copy 'this is the tricky part - this is what is needed. The formula links needs to be broken so that only the values remain
Range("D2").PasteSpecial xlPasteValues
wboor.SaveCopyAs "C:\Users\n0269777\Desktop\" & Range("A" & i).Value & ".xlsm" 'Perhaps I can save a copy first? Then close the workbook, so the formula is preserved
wboor.Close
Workbooks.Open Filename:=fileaddress 'but then, how do I call the original file, and then loop the macro to run again?
End If
Next i
End Sub
Any suggestions/help would be appreciated!
Not sure it was necessary to start a new question, but anyway try this.
Sub test()
Dim wb As Workbook, s As String, i As Long
For i = 1 To 3
If Not Range("B" & i).Value = "X" Then
Range("C2").Value = Range("A" & i).Value
Calculate 'updates the formula
Range("B" & i).Value = "X" 'update the check
s = "C:\Users\n0269777\Desktop\" & Range("A" & i).Value & ".xlsm"
ActiveWorkbook.SaveCopyAs s
Set wb = Workbooks.Open(s)
wb.Sheets(1).UsedRange.Value = wb.Sheets(1).UsedRange.Value
wb.Close True
End If
Next i
End Sub
You could save a copy of the formula, and put it back into the workbook each time. ie:
Option Explicit
Sub test()
With ThisWorkbook.ActiveSheet
Dim formulaText As String
formulaText = .Range("D2").Formula
Dim i As Long
For i = 1 To 3
If Not .Range("B" & i).Value = "X" Then
.Range("C2").Value = Range("A" & i).Value
Calculate 'updates the formula
.Range("B" & i).Value = "X" 'update the check
.Range("D2").Copy
.Range("D2").PasteSpecial xlPasteValues
ActiveWorkbook.SaveCopyAs "C:\Users\n0269777\Desktop\" & Range("A" & i).Value & ".xlsm"
.Range("D2").Formula = formulaText
End If
Next i
End With
End Sub

Excel VBA to make hyperlink for active cell

I want to make a link from active cell in workbook 1 which can I use it in workbook 2. I use the following code which assigned to a button:
With ActiveSheet
.Hyperlinks.Add Range("F6"), _
.Parent.FullName & "#'" & .Name & "'!" & "$A$1", TextToDisplay:="link"
End With
This code made a link with full path and I can use it in any workbook but I need some changes which I could to:
Make the active cell hyperlink not cell A1 which specified in code.
The value in the active cell become text to display arg of hyperlink function.
Thanks
PS after Vityata answere: how can i change Range("F6") to activecell adress?
In order to obtain the active cell value and address, change your code the corresponding places with the following:
ActiveCell.Address
ActiveCell.Value
I find it just to close this topic.
Sub Button36_Click()
Dim newRange As Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))
With ActiveSheet
.Hyperlinks.Add Anchor:=newRange, _
Address:=.Parent.FullName & "#'" & .Name & "'!" & ActiveCell.Address, TextToDisplay:=ActiveCell.Text
End With
End Sub
try this
Sub add_links_Input_Column()
Dim lRow As Long
Dim ColHead As String
ColHead = InputBox("Enter Column Letter", "Identify Column", [c1].Value)
If ColHead = "" Then Exit Sub
With ActiveSheet
lRow = .Range(ColHead & .Rows.Count).End(xlUp).Row
For Each c In .Range(ColHead & "2:" & ColHead & lRow)
ActiveSheet.Hyperlinks.Add anchor:=c, Address:=c.Value
Next
End With
End Sub

using a variable name in my VBA sumif formula

I have built a code that performs a sumif on another workbook that I open using the get open filename dialogue box. I intend to use this formula daily, and hence the workbook where I intend to obtain the information and the workbook where I intend to paste the results will continue to have varying names basing on the date of the day.
I get a type mismatch on the SUMIF formula. Please help.
Sub flextab()
Dim LastCol As Integer, LastRow As Long
' Get the dimensions
With Sheets("Flex")
LastCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
End With
'Insert a column where required.
Cells(2, LastCol - 1).EntireColumn.Insert
'Insert the date
Cells(2, LastCol - 1).Value = Date - 1
'Insert the balance sheet balances for the day
Dim wb1 As Workbook, wb2 As Workbook
Dim FileName1 As String, FileName2 As String
Dim BalSheet As Worksheet
Dim Ret1
FileName1 = ThisWorkbook.Name
'~~> Get the first File
Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
, "Please select the Balance sheet for the day")
If Ret1 = False Then Exit Sub
Set wb2 = Workbooks.Open(Ret1)
FileName2 = wb2.Name
Workbooks(FileName1).Activate
'let's get a reference to the worksheet with the source values
Set BalSheet = Workbooks(FileName2).Worksheets("Sheet1")
With Worksheets("Flex").Range(Cells(5, LastCol - 1), Cells(109, LastCol - 1))
'let's put in our SUMIF formulas
.Formula = "=SUMIF(" & BalSheet.Range("B2:B20000") & "," & Worksheets("Flex").Range("A5") & " , " & BalSheet.Range("n2:n20000") & ")"
'let's convert the formulas into values
.Value = .Value
End With
wb2.Close SaveChanges:=False
Set wb2 = Nothing
Set wb1 = Nothing
End Sub
You are adding ranges to a string, while ranges are objects. Try this:
"=SUMIF(" & BalSheet.Range("B2:B20000").Address & "," & Worksheets("Flex").Range("A5").Value & " , " & BalSheet.Range("n2:n20000").Address & ")"
instead of this:
"=SUMIF(" & BalSheet.Range("B2:B20000") & "," & worksheets("Flex").Range("A5") & " , " & BalSheet.Range("n2:n20000") & ")"
You are working with 2 workbooks, but you are using some worksheets without qualifier.
If you have focus to the wrong workbook this will fail if the workbook that is active does not have a Flex worksheet.
So change this:
Worksheets("Flex").Range(Cells(5, LastCol - 1)
to this:
wbX.Worksheets("Flex").Range(Cells(5, LastCol - 1)
where the X is the correct workbook.