formatting codes for footer not being applied and page orientation data mismatch - vba

I have a worksheet(adHoc) where cell b28 contains
"&9 2014 YTD Financial Data for PP" & Chr(10) & " &D &T" & Chr(10) & " Version 1.0" & Chr(10) & " &F"
When I use the above to update the footer of another worksheet in a different workbook. I don't get the embedded formatting - it displays exactly what is contained in the cell b28.For example excel should see &9 and make the font 9 points.
I am also getting a datatype mismatch error with the page orientation. The contents of cell b36 is xlLandscape.
I posted a copy of this question last week on another board but did not get any answers. I hope someone here has answer.
http://www.mrexcel.com/forum/excel-questions/919033-updating-pagesetup-using-cells-master-worksheet-orientation-formatting-footer-excel-visual-basic-applications.html
This is the code I am using.
Sub page_setup()
Dim reportWB As Excel.Workbook
Dim sheet As Excel.Worksheet
'open report workbook - name of workbook is in cell b4
Set reportWB = Workbooks.Open(Workbooks("macros.xlsm").Sheets("adHoc").Range("b4").Value)
Dim leftFooter
leftFooter = Workbooks("macros.xlsm").Sheets("adHoc").Range("b28").Value
For Each sheet In reportWB.Sheets
With sheet
.PageSetup.leftFooter = leftFooter
.PageSetup.Orientation = Workbooks("macros.xlsm").Sheets("adHoc").Range("b36").Value
End With
Next
End Sub

Reading in your footer definitions like that they are treated as literal string, not code. You need to resolve the code to valid footer strings somehow.
For the LeftFooter string, you can use Evaluate to resolve it, but it will need to be written as if it's a Excel Formula, not VBA, so use
"&9 2014 YTD Financial Data for PP" & Char(10) & " &D &T" & Char(10) & " Version 1.0" & Char(10) & " &F"
Note the I use Char rather than Chr, the Excel formula equivalent.
For Orientation you are using a named constant, which won't work. Either put the value on your Excel sheet (2 in this case) or write your own code to resolve the name to its value
Working version (with corrected source data on sheet as descibed above)
Sub page_setup()
Dim reportWB As Excel.Workbook
Dim sheet As Excel.Worksheet
Dim wsSource As Worksheet
'open report workbook - name of workbook is in cell b4
Set wsSource = Workbooks("macros.xlsm").Sheets("adHoc")
Set reportWB = Workbooks.Open(wsSource.Range("b4").Value)
Dim leftFooter
leftFooter = wsSource.Range("b28").Value
For Each sheet In reportWB.Sheets
With sheet
.PageSetup.leftFooter = Evaluate(leftFooter)
.PageSetup.Orientation = wsSource.Range("b36").Value
End With
Next
End Sub
To handle the constants you could add a UDF that resolves the string names to values and call that from your settings sheet
Eg
Function GetConst(s As String) As Variant
Select Case s
Case "xlLandscape"
GetConst = xlLandscape
Case "xlPortrait"
GetConst = xlPortrait
' etc
End Select
End Function
Put in cell B36 GetConst("xlLandscape") (as a string, not formula), and change your Orientation line of code to
.PageSetup.Orientation = Evaluate(wsSource.Range("b36").Value)
Add any other named constants you want to the Select Case statement.

AFAIK, there is no (straightforward) way to do what you're trying to do. When you put code in a cell, and then call that cell's value in place of actual code, what VBA is trying to run is not:
.PageSetup.Orientation = xlLandscape
but rather:
.PageSetup.Orientation = "xlLandscape"
which will produce the errors and behavior you're seeing.
As rule of thumb, if your VBA code needs a string (ie, something in ""), or a number, you can do that calculation on the sheet and have the code pull in the value.
For everything else (there's Mastercard) put it in the code. For example:
leftfooter = cell1.value & Chr(10) & cell2.value & Chr(10) & cell3.value
(As a side note, I'm not familiar with the formatting it seems you're trying to do in that string... Those are generally set up through things like
With sheet.PageSetup.leftFooter.
.Font.Size = 9
'etc...
)

Related

VLOOKUP Formula places Apostrophe in front of text and generates Run-time error '1004'

I am writing a macro which inserts some formulas into a column array. I am trying to automate a weekly process, so the input files are variable and are selected through the msoFileDiaglogFilePicker application.
Dim wb_Final As Workbook, nameFinal As String
Set wb_Final = Workbooks.Open(Filename:=Final_Directory)
nameFinal = wb_Final.Name
Dim wb_Summary As Workbook, nameSummary As String
Set wb_Summary = Workbooks.Open(Filename:=Summary_Directory)
nameSummary = wb_Summary.Name
wb_Summary.Sheets("Sheet 1").Activate
With Sheets("Sheet 1")
.Range("AT4:AT5000").Formula = "=IF(OR(AX1=""Open"",AX1=""Won"",AX1=""Won - Pending""),""Yes"",""No"")"
.Range("AU4:AU5000").Formula = "=VLOOKUP(W:W,LOVs!H:I,2,FALSE)"
.Range("AV4:AV5000").Formula = "=IF(IFERROR(VLOOKUP($A:$A,'[" & nameFinal & "]DATA'!$A:$AK,34,FALSE),0)=0,"",VLOOKUP($A:$A,'[" & nameFinal & "]DATA'!$A:$AK,34,FALSE))"
.Range("AW4:AW5000").Formula = "=IF(IFERROR(VLOOKUP($AV:$AV,'[" & nameFinal & "]DATA'!$AH:$CX,48,FALSE),0)=0,"",VLOOKUP($AV:$AV,'[" & nameFinal & "]DATA'!$AH:$CX,48,FALSE))"
'....More formulas similar to above
End With
The first two formulas get placed into the cells and compute with no problem.
The third formula gets placed into the cells as a text with an apostrophe in the front of it in excel. (i.e. '=IF(IFERROR(VLOOKUP...)
The fourth formula generates a Run-time error '1004'
I have tried all the different formula types:
.Formula
.FormulaR1C1
.FormulaLocal
.FormulaR1C1Local
And still receive the same error.
I think I am experiencing a similar issue as stated in this article, but I'm not if I can use the Application.Vlookup function without redefining all the arrays and column references in my current VLOOKUP functions (which would take a VERY long time).
Any help would be much appreciated
You cannot use apostrophes in formulas; instead use quotation marks, and in your case, you'll need to escape it like you did in your prior formulas, example:
VLOOKUP($A:$A,""[" & nameFinal & "]DATA""!$A:$AK,34,FALSE)
Try
With Worksheets("Sheet 1") '>== or Sheet1 depending on actual name
.Range("AW4:AW5000").Formula = "=IF(IFERROR(VLOOKUP($AV:$AV,[" & nameFinal & "]DATA!$AH:$CX,48,FALSE),0)=0,"""",VLOOKUP($AV:$AV,[" & nameFinal & "]DATA!$AH:$CX,48,FALSE))"
End With

VBA error adding a Name with a formula in the reference

I am trying to add a Name to my workbook. The reference has an INDEX formula. I am getting an error on this line of code:
ActiveWorkbook.Names.Add Name:=RangeName, RefersTo:=Reference
I tried it with ActiveWorkbook and also tried defining a worksheet.
I guess it doesn't work, because the name range can not be matched with a worksheet because it has a function in it, but i do not know how to solve. Does anyone have a suggestion?
Sub NameRange_Add3()
Dim RangeName As String
Dim Reference As String
Dim i As Integer
For i = 2 To 6
RangeName = "list" & i
Reference = "=INDEX(tabla_1;;MATCH(" & "hszis" & i & ";hszi_list;0))"
ActiveWorkbook.Names.Add Name:=RangeName, RefersTo:=Reference
Next i
End Sub
When you are using creating formulas in VBA you need to use the English notation, which means points as decimal separators and commas as function argument separators.
You can either do what #brettdj did and use commas
Reference = "=INDEX(tabla_1,,MATCH(" & "hszis" & 1 & ",hszi_list,0))"
or use RefersToLocal instead of RefersTo
ActiveWorkbook.Names.Add Name:=RangeName, RefersToLocal:=Reference
I would prefer the first solution though because otherwise it could fail if you execute the macro on a machine with different language settings.
I ran it with
Reference = "=INDEX(tabla_1,MATCH(" & "hszis" & i & ",hszi_list,0))"
and it worked. Suggest you try removing the bonus ;
Reference = "=INDEX(tabla_1;MATCH(" & "hszis" & i & ";hszi_list;0))"

How to use a variable as one of the values in Excel VBA VLOOKUP

I'm using VBA in Excel and I'm assigning a VLOOKUP as a formula to a cell. It works fine, but I would like to use a variable that refers to the last cell that contains a value in the column.
In the example below, I would the value for $B$269 to change depending on the number of elements in the closed document.
"=VLOOKUP(B2,'Macintosh HD:Users:myself:Documents:[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!$A$1:$B$269,2,FALSE)"
I know I want to use something along the lines of:
Range("B" & Rows.Count).End(xlUp).Address
With that said, I haven't been able to figure out how to incorporate the result, which is something like $B$269 into the VLOOKUP. I know that those formulas return the correct address because I've used it in Debug.Print.
I tried to do something like this:
"=VLOOKUP(B2,'Macintosh HD:Users:myself:Documents:[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!$A$1:"&GetLastRowFunct&",2,FALSE)"
But that didn't work.
Here is my current code:
Sub GetLastRow()
Debug.Print GetLastRowFunct
End Sub
Function GetLastRowFunct() As String
Dim openNwb As Workbook
Const MasterPath = "Macintosh HD:Users:myself:Documents:"
Dim strNewFileName As String
strNewFileName = "Master_Terms_Users.xlsm"
Set openNwb = Workbooks.Open(MasterPath & strNewFileName)
Dim openNws As Worksheet
Set openNws = openNwb.Worksheets(1)
GetLastRowFunct = openNws.Range("B" & Rows.Count).End(xlUp).Address
openNwb.Close
End Function
Any recommendations would be appreciated.
I would rewrite that function to return the entire range address, including worksheet, workbook and path.
Function GetLastRowFunct() As String
Const MasterPath = "Macintosh HD:Users:myself:Documents:"
Dim openNwb As Workbook, strNewFileName As String
strNewFileName = "Master_Terms_Users.xlsm"
Set openNwb = Workbooks.Open(MasterPath & strNewFileName)
with openNwb.Worksheets(1)
GetLastRowFunct = .Range(.cells(1, 1), .cells(rows.count, "B").End(xlUp)).Address(1, 1, external:=true)
end with
openNwb.Close
End Function
The formula construction and assignment becomes simpler to deal with.
rng.formula = "=VLOOKUP(B2, " & GetLastRowFunct & ", 2, FALSE)"
tbh, I'm not sure if you have to supply your own square brackets or not on a Mac.

Excel VBA Runtime Error 1004 when renaming ActiveSheet

I'm at a loss when trying to figure out where this code is tripping up. I am looking to rename the activesheet by using a concat of two ranges on the activesheet and some static text. When only one worksheet is in the workbook, the code works great. As soon as a second worksheet is added, I get a Runtime Error 1004. I'll highlight the line of code where it is breaking. This code currently resides in a normal module.
Option Explicit
Sub updateName()
Dim fNumber
Dim pCheckNumber
Dim asName As String
Dim tempASName As String
Dim worksheetName As Object
If ActiveSheet.Name = "Launch Page" Then Exit Sub
fNumber = ActiveSheet.Range("FlightNumber").Value
pCheckNumber = ActiveSheet.Range("PerformanceCheckNumber").Value
If fNumber <> "" And pCheckNumber <> "" Then
tempASName = "Flight " & fNumber & " | Run " & pCheckNumber & " (0.0%)"
asName = tempASName
MsgBox ActiveSheet.Name & vbCr & asName
ActiveSheet.Name = asName
worksheetName.Caption = asName
Else
Exit Sub
End If
End Sub
I'm in the process of adding error checking to ensure that I don't have duplicate sheet names. However, due to the nature of the field names, this will never occur.
I appreciate all of the insights!
The error you are reporting is, most likely, provoked because of trying to rename a Worksheet by using a name already in use. Here you have a small code to avoid this kind of situations:
Dim newName As String: newName = "sheet1"
Dim addition As String: addition = "_2"
Do While (Not sheetNameFree(newName))
newName = newName & addition
Loop
Where sheetNameFree is defined by:
Function sheetNameFree(curName As String) As Boolean
sheetNameFree = True
For Each Sheet In ActiveWorkbook.Sheets
If (LCase(Sheet.Name) = LCase(curName)) Then
sheetNameFree = False
Exit Function
End If
Next Sheet
End Function
You can adapt this code to your specific needs (for example, by converting addition into a number which grows after each wrong name).
In your code I see one other problem (although it shouldn't be triggering a 1004 error): you are accessing the property Caption from an non-instantiated object (worksheetName), whose exact functionality is not too clear. Just delete this line.
NOTE: good point from KazJaw, you might be using an illegal character. If fNumber and pCheckNumber are numbers or letters, it would be OK.
NOTE2: if with worksheetName you want to refer to an ActiveX Label in your workSheet, better do: ActiveSheet.Label1.Caption (where Label1 is the name of the Label). You cannot define worksheetName as a Label, because it is not a "conventional Label".

Writing formula into Excel through Access VBA

I want to insert in "A1" some text "ABC" and the following cell in "B1" an if statement. However I get only the first entry "ABC" inserted and then an error at FormulaR1C2 "Object doesn't support this property or method". I'm not sure I'm using the R1C2 correctly. I was assuming it stood for Row 1 Column 2, can someone help me out.
Dim Excel_App As Object
Dim strExcel As String
Set Excel_App = CreateObject("Excel.Application")
Excel_App.Visible = True
Excel_App.Workbooks.Add
With Excel_App
.Range("A:B").EntireRow.ColumnWidth = 25
.Range("A2").EntireRow.Font.FontStyle = "Bold"
.ActiveCell.FormulaR1C1 = "ABC"
strExcel = "=IF(A1 = """"," & """EMPTY""" & "," & """FILLED""" & ") "
.ActiveCell.FormulaR1C2 = strExcel
End With
FormulaR1C1 is the method of how the formula is written.
Formula refers to writing a formula in A1 like =B1+C1.
To write that same formula using R1C1 notation, you would write =RC[1] + RC[2]. Furthermore to write =B2+C2 in A1 write this =R[1]C[1] + R[1]C[2] -> so you can see you are offsetting the columns and rows where you want the formula to return values from.
What you want to do in your code is offset the place where the formula will be placed, rather than how it's calculating, so you should write this:
.ActiveCell.Offset(,1).Formula = strExcel
Actually, you should get rid of ActiveCell altogether, unless you absolutely need it.
I would write your code like this for better, more accurate execution:
Dim Excel_App As Object
Dim strExcel As String
Dim wkb as Object, wks as Object
Set Excel_App = CreateObject("Excel.Application")
Excel_App.Visible = True
Set wkb = Excel_App.Workbooks.Add
Set wks = wkb.Sheets(1) 'assumes you want first sheet, can modify for sheet index or name
With wks
.Range("A:B").EntireRow.ColumnWidth = 25
'I think this will actually set every row to 25, is that what you want?
.Range("A2").EntireRow.Font.FontStyle = "Bold"
.Range("A1").Value = "ABC" 'don't need to write Value, but just to show you the property
strExcel = "=IF(A1 = """"," & """EMPTY""" & "," & """FILLED""" & ") "
.Range("B1").Formula = strExcel
End With
FormulaR1C1 is a property which returns the formula of a cell expressed in R1C1 formula style.
You need to reference cells by using the Workbook.WorkSheet.Range syntax.
So first you need to specify the workbook you are working in, which in your case is the workbook added by the statement Excel_App.Workbooks.Add. Your new workbook is automatically named something like "Book1" and automatically has the default number of worksheets added named "Sheet1" through "Sheetn" where n is the default number of sheets.
So you're final code to write to that line is
Excel_App.Workbooks(1).Worksheets("Sheet1").Cells(1, 1) = "ABC"
Excel_App.Workbooks(1).Worksheets("Sheet1").Cells(1, 2).Formula = "=IF(A1 = """"," & """EMPTY""" & "," & """FILLED""" & ")"