External reference changing with InputBox - vba

Good morning,
I have two different workbooks (wb1 and wb2), each has two worksheets, "2018" and "2019", containing some data.
I'm trying to create a macro that takes an input with InputBox that has to be 2018 or 2019 and, depending on the choice, it has to insert a SUMIF formula into the worksheet whose name has been tapped in, in the second workbook, with reference to different columns of wb1.
The point is that, depending on what it is inserted in InputBox, the formula in wb2 has to reference to the worksheet "2018" or "2019" of wb1.
=SUMIF('[wb1.xlsm]2018'!$C$3:$C$4412;A3;'[wb1.xlsm]2018'!$K$3:$K$4412)
Above there is the formula that I have now. Is it possible to remove "2018" after the square bracket and add the variable related to InputBox?
Thanks for your help
Edit from comments:
I tried to modify the formula, using Application.SumIf. The problem is that it now gives me run-time error 1004 Application-defined or object-defined error on the line that starts with Sumact = Application...
year_check = InputBox("Insert the year you need to check")
schedule_worksheet = "Schedule - " & year_check
family_worksheet = "Family - " & year_check
Dim Sumact As Range
For i = 9 To 200
index_row = index_row + 1
Set Sumact = wbfu.Worksheets(family_worksheet).Range(Cells(2, index_row), Cells(2, index_row))
Sumact = SumIf(wb.Worksheets(schedule_worksheet).Range("C:C"), wb.Worksheets(schedule_worksheet).Range(Cells(1, index_row), Cells(1, index_row)), wb.Worksheets(schedule_worksheet).Range("K:K"))
Next i

Related

VBA code to clear just constants on destination sheet

I have filtered my cumulative sales from SalesMasterSheet to different sheets each named after each particular customer but I got stuck at trying to add excel formulas because my VBA code always clears content of the range of cells on sheetActive.
I have tried the special cell method so as to clear only constants but it doesn't work.
Any help would be appreciated.
below is my code:
Private Sub Worksheet_activate()
Dim i, LastRow
LastRow = Sheets("MasterSheet").Range("A" & Rows.Count).End(xlUp).Row
Sheets("ACCIMA").Range("A1:L500").ClearContents
For i = 2 To LastRow
If Sheets("MasterSheet").Cells(i, "C").Value = "ACCIMA" Then
Sheets("MasterSheet").Cells(i, "C").EntireRow.Copy _
Destination:=Sheets("ACCIMA").Range("A" & Rows.Count).End(xlUp).Offset(1)
End If
Next i
End Sub
So far what it does is copy entries with "ACCIMA" on column C from Mastersheet to sheet("ACCIMA"), but i would like to put a formula in sheet("ACCIMA") but because Sheets("ACCIMA").Range("A1:L500").ClearContents
all formulas clear once i make the sheet active.
Given the low amount of informations you give I sort of understood your problem this way:
If your code always clears content of the range of cells on the active sheet you should try to add the worksheet you are working on in your code, e.g.
cells(1,1).value = "test"
would turn into
worksheets("customer1").cells(1,1).value = "test"
After new informations:
Copy the content of your range "A1:K500", ignore the column "L" which has your formular and then add your formulars in column "L".
worksheets("customer1").cells(1,1).formula = "..."
Keep in mind, that your syntax for the formula changes in comparison with the synatx on the actual excel sheet.
e.g.:
=IF(A1="empty";"empty";"not empty")
Will turn into:
worksheets("customer1").cells(1,1).formula = "=IF(A1=""empty"",""empty"",""not empty"")"

How to put an excel formula to a dynamic range of cells using VBA?

I am new to VBA and am using the following snippet to populate a range of cells with a vlookup function:
With wbk1.Sheets("classes")
.Range("AA2:AA" & .Range("C" & .Rows.Count).End(xlUp).Row).Formula = "=VLOOKUP(C2,lookup!$A$2:$B$14,2,FALSE)" 'Actual vlookup
In order to make this dynamic, I want to replace the .Range("AA2:AA" & .Range("C" & .Rows.Count) part with a dynamic reference (in my case the first empty column in the same sheet).
First, I find the first empty column with this one-liner:
first_empty_column = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
However, when I do
With wbk1.Sheets("classes")
.Range(ws.Cells(1, first_empty_column) & .Range("C" & .Rows.Count).End(xlUp).Row).Formula = "=VLOOKUP(C2,lookup!$A$2:$B$14,2,FALSE)" 'Actual vlookup
I get "Runtime Error '1004': Application-defined an object-defined error.
What is the syntax to define hard-coded ranges dynamically in this context?
You need to use the following Range reference logic:
'PSEUDO-CODE
.Range(LeftTopCell, RightBottomCell)
where both LeftTopCell and RightBottomCell can be set with any valid range reference.
Moreover, you can not combine reference to range from two different sheets. You are referencing both ws and Sheets("classes") in single range reference.
Try with this:
With wbk1.Sheets("classes")
.Range(.Cells(1, first_empty_column), _
.Cells(.Range("C" & .Rows.Count).End(xlUp).Row, first_empty_column)).Formula = "=VLOOKUP(C2,lookup!$A$2:$B$14,2,FALSE)" 'Actual vlookup
End With

excel vba - syntax error

I can't quite figure out what the syntax error in Excel VBA is, the error I am seeing is: "run-time error 1004: Application-defined or object-defined error"
Sheets("Totals").Select
x = Range("A139").Activate
Range("E139:AB166").Formula = "=INDEX(""Model""!$A$3:$Z$1000,MATCH($" & x & ",""Model""!$A$3:$A$1000,0),MATCH(E$3,""Model""!$A$3:$Z$3,0))"
I am attempting to use an Index Match Match formula where the index reference is another worksheet in the file. I am trying to populate the formula in Range E139:AB166, such that the x variable is locked to Column A and the last match function is locked on the third row (E$3).
x = Range("A139").Activate
This line of code should force the cursor to that cell in the 'model' worksheet. 'Model' is the name of the worksheet in the file. I thought "" were necessary to alert vba that the string refers to the worksheet name.
What if the worksheet name is comprised of two strings so "Model 1". What would be then the syntax, this?
""Model 1""!A3
'x' is the cell where new data is added, I wrote a line of code to have it dynamically changed.
x = Range("A" & insert_at).Activate
Where insert_at is a variable that equals the last row,in the worksheet that is not empty, + 1.
insert_at = lastRow + 1
So the idea is to dynamically add additional data from the 'Model' worksheet to the current worksheet 'Totals' below any existing data in the 'Totals worksheet.
I appreciate any assistance with this.
Thanks!
Type a correct working formula in E139 then use this little Sub I wrote once, to turn it into a vba usable formula string.
Sub RngToVba(src As Range)
'writes the VBA code to re-create the formulae in given range
'by Patrick Honorez - www.idevlop.com
'usage: from debug window, type RngToVba [L14:R14]
' or RngToVba range("L14:R14")
Dim c As Range
For Each c In src
Debug.Print "range(""" & c.Address & """).formula = """ & _
Replace(c.Formula, """", """""") & """"""
Next c
End Sub
And...for god's sake, stop using those useless select and activate.
Sheets("Totals").Range("E139:AB166").Formula = someString
is faster, easier to debug, and more readable.

Run time error '1004' for entering a formula into each sheet in the workbook

So I had a code that was working. Basically pieces together different parts in cells A2 and A1 of each worksheet to create unique tab names. But I ran into a situation of duplicate tab names. So I adjusted the formula by making it a little longer to avoid these errors but now when I run the Macro I get Run-Time error '1004'. With no clue on why because nothing changed but the formula.
Here's the code:
Sub Tab_Name_Creation()
Dim s As Worksheet
Dim formula As String
For Each s In ActiveWorkbook.Worksheets
s.Activate
With ActiveWindow
.View = xlNormalView
End With
Next s
Call UnhideRows
formula = "=IF(R[-3]C=""Facility Variance Report"",IF(MID(R[-2]C,FIND("":"",R[-2]C)+2,20)=""Baptist Memorial Hos"",MID(R[-2]C,FIND(""_"",R[-2]C)+1,2)&""-""&TRIM((MID(R[-2]C,FIND("":"",R[-2]C)+2,17)))&IF(IFERROR(FIND(""West"",R[-2]C),0)>0,"" W"","""")&"" ""&MID(R[-2]C,FIND(CHAR(1),SUBSTITUTE(R[-2]C,""-"",CHAR(1),2))+1,3)&"" -FVar"",MID(R[-2]C,FIND(""_"",R[-2]C)+1,2)&""-""&TRIM(" & _
"2]C,FIND("":"",R[-2]C)+2,20)))&IF(IFERROR(FIND(""West"",R[-2]C),0)>0,"" W"","""")&""-FVar""),IF(MID(R[-2]C,FIND("":"",R[-2]C)+2,20)=""Baptist Memorial Hos"",MID(R[-2]C,FIND(""_"",R[-2]C)+1,2)&""-""&TRIM((MID(R[-2]C,FIND("":"",R[-2]C)+2,17)))&IF(IFERROR(FIND(""West"",R[-2]C),0)>0,"" W"","""")&"" ""&MID(R[-2]C,FIND(""-"",R[-2]C,FIND(""-"",R[-2]C)+1)+1,3)&""-LTM"",MID(" & _
"ND(""_"",R[-2]C)+1,2)&""-""&TRIM((MID(R[-2]C,FIND("":"",R[-2]C)+2,20)))&IF(IFERROR(FIND(""West"",R[-2]C),0)>0,"" W"","""")&""-LTM""))"
For i = 5 To ThisWorkbook.Worksheets.Count
Worksheets(i).Range("A4").NumberFormat = "General"
Worksheets(i).Range("A4") = formula
Next i
Call RenameFromA4
Call SortWorkBook
Call listsheets
MsgBox "Report Has Been Updated"
End Sub
To give you some background on the macro itself. I have a sheet with about 94 sheets with the tab names in account numbers which made it hard for people to understand. So i created this macro that first changes the workbook view to normal view, than unhide rows at the top of the spreadsheet, than inserts the formula that giving issue, than it renames the tabs, sort them and than create/organize a table of contents.
Any insight why I get run time error on line will be appreciated:
Worksheets(i).Range("A4") = formula
Example of the Formula
Cell A1 contains :LTM Income Statement
Cell A2 Contains : HM_LA_217368 - HM: St. Martin Hospital
The formula in excel: IF(A1="Facility Variance Report",IF(MID(A2,FIND(":",A2)+2,20)="Baptist Memorial Hos",MID(A2,FIND("_",A2)+1,2)&"-"&TRIM((MID(A2,FIND(":",A2)+2,17)))&IF(IFERROR(FIND("West",A2),0)>0," W","")&" "&MID(A2,FIND("-",A2,FIND("-",A2)+1)+1,3)&"-FVar",MID(A2,FIND("_",A2)+1,2)&"-"&TRIM((MID(2:2,FIND(":",A2)+2,20)))&IF(IFERROR(FIND("West",A2),0)>0," W","")&"-FVar"),IF(MID(A2,FIND(":",A2)+2,20)="Baptist Memorial Hos",MID(A2,FIND("_",A2)+1,2)&"-"&TRIM((MID(A2,FIND(":",A2)+2,17)))&IF(IFERROR(FIND("West",A2),0)>0," W","")&" "&MID(A2,FIND("-",A2,FIND("-",A2)+1)+1,3)&"-LTM",MID(A2,FIND("_",A2)+1,2)&"-"&TRIM((MID(A2,FIND(":",A2)+2,20)))&IF(IFERROR(FIND("West",A2),0)>0," W","")&"-LTM"))
Produces a result of "LA-St. Martin Hospital-LTM" So that will be the new tab name.
So I concatenated the formula to fit string :
formula = "=IF(R[-3]C=""Facility Variance Report"",IF(MID(R[-2]C,FIND("":"",R[-2]C)+2,20)=""Baptist Memorial Hos"",MID(R[-2]C,FIND(""_"",R[-2]C)+1,2)&""-""&TRIM((MID(R[-2]C,FIND("":"",R[-2]C)+2,17)))&IF(IFERROR(FIND(""West"",R[-2]C),0)>0,"" W"","""")&"" ""&MID(R[-2]C,FIND(""-"",R[-2]C,FIND(""-"",R[-2]C)+1)+1,3)&""-FVar""" & _
formula = formula & "MID(R[-2]C,FIND(""_"",R[-2]C)+1,2)&""-""&TRIM((MID(2:2,FIND("":"",R[-2]C)+2,20)))&IF(IFERROR(FIND(""West"",R[-2]C),0)>0,"" W"","""")&""-FVar"")" & _
formula = formula & "IF(MID(R[-2]C,FIND("":"",R[-2]C)+2,20)=""Baptist Memorial Hos"",MID(R[-2]C,FIND(""_"",R[-2]C)+1,2)&""-""&TRIM((MID(R[-2]C,FIND("":"",R[-2]C)+2,17)))&IF(IFERROR(FIND(""West"",R[-2]C),0)>0,"" W"","""")&"" ""&MID(R[-2]C,FIND(""-"",R[-2]C,FIND(""-"",R[-2]C)+1)+1,3)&""-LTM""" & _
formula = forumla & "MID(R[-2]C,FIND(""_"",R[-2]C)+1,2)&""-""&TRIM((MID(R[-2]C,FIND("":"",R[-2]C)+2,20)))&IF(IFERROR(FIND(""West"",R[-2]C),0)>0,"" W"","""")&""-LTM""))"
Still getting a error on the string

VBA: insert max formula, referencing column of a closed workbook

First Post. I have a workbook that is a list of customer names, each name is a link to their individual workbook that is on a sharepoint site. The second column is a "Last contact" column which has a formula
=MAX('https://example.com/folder/Folder/Customer Library/Area/T/[Customername.xlsm]Notes'!$B$2:$B$120)
I am able to make this formula manually by opening the linked workbook, selecting the cell on my customer list, enter "=max(" then highlight the range i want on the linked workbook. Works Fine.
Enter VBA because we want to simplify the procedure for adding customers to the list. I have a userform where you type in the customer name in a textbox1, and the address of the sharepoint wb in textbox 2. The submit button has the following code which inserts the customer name with a link to the sharepoint book in target cell of column A. This works fine. I also am trying to insert the MAX formula in the adjacent cell of column B. I can get the formula to the correct place. However, I am running into issues on the web reference, as it is textbox2's value. When I use textbox2.value it gives errors. Sorry for the book, here is the code without the web book reference:
Private Sub CommandButton1_Click()
Sheets("Dashboard").Select
NextFree = Range("A2:A" & Rows.Count).Cells.SpecialCells(xlCellTypeBlanks).Row
Range("A" & NextFree).Select
ActiveCell.Hyperlinks.Add Anchor:=ActiveCell.Offset(0, 0), Address:=TextBox2.Value, TextToDisplay:=TextBox1.Value
Range("B" & NextFree).Formula = "=MAX(Notes'!$B$2:$B$120)"
UserForm1.Hide
Unload Me
End Sub
Between =Max( & Notes'... I know there needs to be textbox2 value, but I don't understand the syntax I suppose. The "Notes" is the sheet where the range is on the sharepoint wb. The range is the same for all additions to the customer list. Thank you for your help.
Update: I am now trying this code but get error Type Mismatch.
Private Sub CommandButton1_Click()
Sheets("Dashboard").Select
Dim SPbook As Workbook
Dim SPsheet As Worksheet
Dim SPrange As Range
Set SPbook = Workbooks.Open(TextBox2.Value)
Set SPsheet = Sheets("Notes")
Set SPrange = SPsheet.Range("B1:B120")
NextFree = Range("A2:A" & Rows.Count).Cells.SpecialCells(xlCellTypeBlanks).Row
Range("A" & NextFree).Select
ActiveCell.Hyperlinks.Add Anchor:=ActiveCell.Offset(0, 0), Address:=TextBox2.Value, TextToDisplay:=TextBox1.Value
Range("B" & NextFree).Formula = "=MAX([" & SPrange & "])"
UserForm1.Hide
Unload Me
End Sub
You should reference textbox2.Value as follows:
Range("B" & NextFree).Formula = "=MAX(" & textbox2.Value $ "Notes'!$B$2:$B$120)"
Formula field takes a string so you just have to build the string concatenating your values.
If textbox2.Value is giving you an error this would not resolve this. Please include more details of this error including complete error message and what values are being passed to subroutine from the form. Regards,