Experiment with Autoshow method, Excel VBA, Value top 10, Error 1004 - excel

saw this question was posted earlier but the answer was a workaround using a macro filter. Still trying to understand how the "Autoshow Method" works from https://msdn.microsoft.com/en-us/library/office/ff835595.aspx
The code I'm working with is:
Sub Test()
ActiveSheet.PivotTables("Pivot4").PivotFields("Base Contract #") _
.AutoShow xlAutomatic, xlTop, 10, "Sum of Not Satisfactory"
End Sub
Runtime Error 1004 - Unable to get pivotTable properties of the worksheet class
What else do I need to declare to have the code work?
Thanks!
Art

Related

Excel 2011 for Mac: Compile error on line that should not be compiling

I am creating an Excel Macro-Enabled Workbook for both Windows & Mac. One platform on the Mac I want it to run on is Excel 2011.
My workbook uses a custom Ribbon tab. Sometimes, depending on what the user does, I want the text of the ribbon buttons to change. So I have code that does this.
I know that a custom Ribbon tab is not possible in Excel 2011. That is okay. However, there is a line in my code that is giving me a compile error on that version of Excel. I thought I had it set that it would not compile the code if running on this version of Excel, but it doesn't seem to be working.
I am defining a variable of type IRibbonUI for use inside a standard module. (The module is Module3, and it is dedicated to code having to do with the Ribbon.) I wrap the variable definition code (along with the rest of the code in this module) in an #IF statement, like so:
#If Not Mac or MAC_OFFICE_VERSION >=15 Then
Dim ribbonUI As IRibbonUI
... rest of the code in Module3 ...
#End If
This means it should not compile at run-time on Excel 2011.
When the workbook opens, I do not get any errors. However, when I am running a sub (let's call it "UpdateOptions", and it is in Module1) that calls a sub that changes the Ribbon (let's call that one "ChangeRibbon", which is in Module3*), I get a compile error on the ribbonUI line: User-defined type not defined
I don't understand why, because as far as I understand, the code in that module shouldn't be compiling at run-time.
*ChangeRibbon should never actually be run on Excel 2011. I have an IF statement that makes sure it is not, like so:
Sub UpdateOptions()
... some code ...
#If Not Mac or MAC_OFFICE_VERSION >=15 Then
Module3.ChangeRibbon
End If
... some other code ...
End Sub
When I step through the code, the error happens when UpdateOptions is first called by another sub. The step-through highlights the name of the sub as the line that is causing the error:
Sub UpdateOptions()
Does anyone know why this is happening? It doesn't make any sense to me.
I'll post it as an answer since it won't fit into the comment section.
It seems that you enter your code, even thought it should not. The easiest explanation is, that your if statement is not evaluated properly. You should check the values of Mac and MAC_OFFICE_VERSION, this should already show you what went wrong. Another reason could be that you made a wrong assumption about how VBA evaluates logic clauses: https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/operator-precedence
If you split/nest the the If-Block it is easier to see which evaluation goes wrong:
Public Sub testVer()
#If Not Mac Then
Debug.Print "Not a Mac"
#Else
#If MAC_OFFICE_VERSION >= 15 Then
Debug.Print "Mac Version equal or above 15: ", MAC_OFFICE_VERSION
#Else
Debug.Print "Mac Version below 15: ", MAC_OFFICE_VERSION
#End If
#End If
End Sub
Here is a small example to see how your if clause gets evaluated:
In VBA the clause Not A Or B is the same as (Not A) Or B, so maybe you just mixed up logic.
Sub testOrNot()
printNotAOrB True, True
printNotAOrB True, False
printNotAOrB False, True
printNotAOrB False, False
End Sub
Private Sub printNotAOrB(A As Boolean, B As Boolean)
Debug.Print "A = " & A, "B = " & B
Debug.Print "Not A Or B :", Not A Or B
Debug.Print "Not (A Or B):", Not (A Or B)
Debug.Print "(Not A) Or B:", (Not A) Or B
Debug.Print
End Sub
I had the thought of if I could possibly "fake out" Excel 2011 into thinking I had created a custom data type for IRibbonUI (and, as it turned out, I had to do it for another type, too) and that worked. In my module dealing with all my Ribbon code, I put this at the top:
#If Mac And MAC_OFFICE_VERSION < 15 Then
Type IRibbonUI
ribbontype As String
End Type
Type IRibbonControl
ribboncontrol As String
End Type
#End If
I no longer receive the compile error.
In regards to L8n's answer, I don't believe the logic of the IF statement was a problem. I had also tried calling on a Function I created long ago to test if the version of Excel was Excel 2011 for Mac. So my IF statement started like this:
#IF ExcelForMac2011 = False Then
I know my function works properly, because I call it many other times in my workbook, and it has always worked correctly. So I don't think it was a logic problem in the IF statement. I think this was a bug in Excel 2011. Unfortunately, it has MANY, MANY bugs.

Excel VBA Function stops execution before completion without error message

I set out to write a simple function to determine the length of a string in points. Having googled around I decided to avoid the font metrics problem by having excel do the work for me.
Here is the code.
Option Explicit
Function txtWidthPts(MyText As String) As Integer
'A cell on a working worksheet has been named "WidthTest" for easy reference & to ensure data is not overwritten.
'set WidthTest word wrapping off so that strings placed in there aren't wrapped
Application.ScreenUpdating = False
With [WidthTest]
.WrapText = False
.Value = MyText
'autofit WidthTest
.Columns.AutoFit
'get the width of the column
txtWidthPts = .Width
.ClearContents
End With
End Function
I tested the function by placing it in a cell on a working worksheet thus:
=txtWidthPts("Test123")
When I have this working I will be using it in code not as a worksheet function.
My problem is that the function does not throw an error and stops execution on the line:
.Value = MyText
I have placed the code and name into an empty workbook to ensure no interaction with other workbook contents / code.
I have searched extensively and tried various suggestions (DoEvents, Application.Update = False, etc, etc.) to no result.
I have cleared all breakpoints, closed and opened the workbook & restarted. I have tested with options set to Break on All Errors.
No result.
I suspect I am missing something obvious but it has me beat at the moment.
Any and all suggestions will be most welcome.
So, #YowE3K was right on the money. After fixing the error in the original code (Corrected code above) this runs fine from vba. I knew I was missing something obvious.
Curiosity sub-question: the function works as desired and indeed, as #YowE3K observed, it does not modify the Excel environment. However the result returned is dependent on it appearing to have modified the Excel environment. Seriously WTF. Just wanting to understand.
Thanks again YoWE3K.

Deselecting Pivot Table Items Error

I'm trying to use the code in this link, but I keep getting the runtime error 438 "Object doesn't support this property or method" for the line
ActiveSheet.PivotItems(1).Visible = True
Does anyone know what's going on?
Full Code:
Sub DeleteAllFields()
Dim i As Long
ActiveSheet.PivotItems(1).Visible = True
For i = 2 To ActiveSheet.PivotItems.Count
ActiveSheet.PivotItems(i).Visible = False
Next
End Sub
Full disclosure - I am a novice VBA user.
Thank you!
The error relates to you using .PivotItems() with the object ActiveSheet.
The PivotItems() property is part of the PivotFields() object so you would need something like:
ActiveSheet.PivotTables("PivotTable1").PivotFields("Example Field").PivotItems(1).Visible = True

Excel error 1004 "Unable to get .... property of WorksheetFunction class" appearing inconsistently

I have a VBA function within a spreadsheet which operates on another spreadsheet that is opened in an earlier stage of my macro. The macro used to work fine but just recently has started causing a 1004 error ("Unable to get RoundDown property of the WorksheetFunction class") when it runs.
I believe I understand what the error would be caused by (a problem running RoundDown) but I cannot see why it is getting triggered in my macro and the odd part is that when I go into Debug mode and step through the code in the VBE the error does not recur (despite nothing obviously changing).
Does anyone have a similar experience of this sort of error occuring inconsistently and know what I could do to resolve it?
I'm reasonably VBA/Excel-savvy, but any suggestions on further steps to diagnose it would be appreciated. I am wondering if there is some issue with the opened spreadsheet not being ready but I cannot see how.
The code is here. The error occurs on the line marked with a comment.
Public Function GetDatesA(sWorkbookname As String, sSheetname As String, sCell As String) As Variant
Dim vDateList() As Variant
Dim currentCell As Range
Dim n As Long
Set currentCell = Workbooks(sWorkbookname).Worksheets(sSheetname).Range(sCell)
n = 0
Do
If Trim(currentCell.Value) = "" Then
Exit Do
Else
ReDim Preserve vDateList(0 To 1, 0 To n)
vDateList(0, n) = WorksheetFunction.RoundDown(currentCell.Value, 0) 'error occcurs on this line
vDateList(1, n) = currentCell.Column
'Debug.Print currentCell.Value
End If
Set currentCell = currentCell.Offset(0, 1)
n = n + 1
Loop While currentCell.Column < XL_LAST_COLUMN
GetDatesA = vDateList
End Function
Other details are:
Excel version: 2010
File being opened resides locally on my C: drive; my macro is in a spreadsheet on the network
File format for both files is .xls (i.e. Excel 2003) - I don't have the option of changing this
Windows 7 (not that I think it would be relevant)
Two points I've tried already are:
Substitute a different worksheet function (e.g. Min(currentCell)) and that also causes the same problem
Having the file open already seems to stop the problem - I wonder if there is some way that the workbook which is being opened (rather than my main workbook with the macro in it) is not enabled for macros and this is interfering. But even if this is the cause I'm not sure how to get around it!
Any ideas?
This error occurs often when any argument passed to the worksheet function is not of the correct type or simply doesn't make sense.
For example, I've had this problem when calling WorksheetFunction.Asin with an argument bigger than 1. In your case, I'd guess currentCell.Value is a non-numeric value or one not according to your region settings regarding numbers.
Yes, the error message is really misguiding.
I got the "Unable to get * property of WorksheetFunction Class" error using Transpose, MMult,MDterm, and MInverse functions.
I was able to get my code to run by putting "Option Base 1" in the Declarations (before the actual code) section of the particular Module in the Editer.
Excel assumes "Option Base 0" which will add an extra row and column of empty cells. This will cause the error to occur and isn't immediately obvious to see.
I have come accross this before, and for me it was becase the criteria range made no sense, as Andre said above.
See example formula below:
.Cells(11, i).Formula = Application.WorksheetFunction.CountIfs(Sheets("Sheet1").Range("AC8:C" & n), "S")
Have a look at the Range... it makes no sense. Amended the range from "AC8:C" to "AC8:AC" and it will work perfectly

ADODB.Connection undefined

Reference Excel VBA to SQL Server without SSIS
After I got the above working, I copied all the global variables/constants from the routine, which included
Const CS As String = "Driver={SQL Server};" _
& "Server=****;" _
& "Database=****;" _
& "UID=****;" _
& "PWD=****"
Dim DB_Conn As ADODB.Connection
Dim Command As ADODB.Command
Dim DB_Status As Stringinto a similar module in another spreadsheet. I also copied into the same module
Sub Connect_To_Lockbox()
If DB_Status <> "Open" Then
Set DB_Conn = New Connection
DB_Conn.ConnectionString = CS
DB_Conn.Open ' problem!
DB_Status = "Open"
End If
End SubI added the same reference (ADO 2.8)
The first spreadsheet still works; the seccond at DB_Conn.Open pops up "Run-time error '-214767259 (80004005)': [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"
Removing the references on both, saving files, re-opening, re-adding the references doesn't help. The one still works and the other gets the error.
?!?
I observed the same error message and in my case nothing had changed. I wondered if my odbc driver needed to be reinstalled (based on what i read online). In any case, restarting excel did the trick. Sometimes the solution is much simpler. :-)
When the error pops up, check your "locals" windows to see what the CS holds. View > Locals Window
Problem: Your constant isn't found by the compiler.
Solution: With the constant being located in a separate module, you'll need to set it as Public for the other code to see it.
Proof:
In order to prove this theory you can do the following:
Open a new Excel spreadsheet
Go to the VBA designer and add a new module
In this module put:
Const TestString As String = "Test String"
Then add the following code to ThisWorkbook:
Public Sub TestString()
MsgBox (TestString)
End Sub
After adding this return to the workbook and add a button, selecting "TestString" as the macro to run when clicked.
Click the button and a blank message box will appear.
Go back to the VBA designer and change the const in Module1 to Public
Click the button on the spreadsheet and you should now see "Test String" in the message box.
I realize that this question is really old. But for the record I want to document my solutions for the error here: It was a data related error in a spreadsheet! A column was formatted as date and contained a value 3000000. Changing the Format to numbers solved the Error 80004005.

Resources