Why do I get a Run-Time error '1004' on a MacBook when I copy the code from a PC version of VBA - arrays

I am new to VBA and learning; however, I am also running VBA on my MAC instead of PC. That being said, I copy the code down just like I have seen in VBA used by PCs and I get a run-time Error '1004'Method 'Range' of object '_Global' failed. Can someone please explain to me why that is?
My code is simple: MonthArray(1) = Range("myMonths").Cells(i,1).value
Thoughts anyone?
Sub Array_OneDimension()
Dim MonthArray(1 To 12) As String
Dim i As Byte
For i = 1 To 12
MonthArray(i) = Range("myMonths").Cells(i, 1).Value 'This is where the error is
Next i
End Sub
I was expecting the code to loop through the range and pull out the value in the locals window.

Related

application defined or object defined error whey copying data into array

I am used to assigning ranges to arrays. However, for some reason right now I am constantly getting an application or object defined error (the first code line below). The second line below works fine. It is identical to the first line except I just copy the range showing all the variables exist.
I have checked in the watch window, arrActuals is Variant/Variant(). Adding .Value at the end of the first line did not solve the error either. Any ideas on why this is happening?
arrActuals = wkbOVHFile.Sheets(szAOPPage).Range(Cells(iStartCopy, IntActOVHCol), Cells(iEndCopy, IntActOVHCol))
wkbOVHFile.Sheets(szAOPPage).Range(Cells(iStartCopy, IntActOVHCol), Cells(iEndCopy, IntActOVHCol)).Copy
Cells without a qualifying worksheet object defaults to the active sheet, so your code fails when wkbOVHFile.Sheets(szAOPPage) is not the active sheet.
More robust like this:
Dim rng As Range
With wkbOVHFile.Sheets(szAOPPage)
Set rng = .Range(.Cells(iStartCopy, IntActOVHCol), _
.Cells(iEndCopy, IntActOVHCol))
End With
arrActuals = rng.Value
rng.Copy

Syntax check fails on array as parameter to sub

I have two related problems. It seems like I don't have a library attached. I have searched and cannot find what I am missing. This is a call to a sub from a function that is called(referenced) in an Excel cell.
The syntax checker fails when I put an array in as a parameter like this which is taken from this VB Page
Sub EmptyValid210917 _
(RefData As String, RefRow As Integer, PhraseArray As String(,), _
DayIndex As Integer, EmptyCol As Boolean, ValidCol As Boolean)
The second related issue is the syntax check fails when I try to dim an array like this:
Dim ColOffset(,) As Integer
It will accept this:
Dim ColOffset(2, 2) As Integer
But does not accept loading as below which is taken from this VB Guide How To
Dim ColOffset(2, 2) As Integer = {{1,2},{3,4}}
Perhaps this is also related. When I call the max function. I get: Compile Error - Method or data member not found
FirstValidDay = Math.Max(1, 2)
Thank you for your help.

How to obtain 2 dimensional arrays of Single in VB.NET exactly like in VBA?

I have some code written in VBA that uses a function of the particular environment I programmed in, which given some empty, not fixed-dimensional Single arrays, gives them back 2 dimensional and filled with data. It also produces a Variant as output.
The VBA code is:
Dim vDummy As Variant
Dim RealLev1() As Single, ImagLev1() As Single
vDummy = FFPOL1Array(RealLev1, ImagLev1)
Now, I know for sure that FFPOL1Arrayis a routine written in FORTRAN, but I cannot access to its code by any means.
I successfully managed to address the same routine in a VB.NET piece of code by writing a workaround that "links" my code to the environment mentioned above and uses its own scripting routines.
My VB.NET code would be:
Dim vDummy As Object
Dim RealLev1(,) As Single, ImagLev1(,) As Single
vDummy = NSI.FFPOL1Array(RealLev1, ImagLev1)
NSI is the "scripting routines object", which is working with many other functions and subroutines.
Sadly the code above does not work because (according to the debugger) of a type conflict. So I checked the Classes-Explorer and found out that the FFPol1Array class is defined as:
get_FFPOL1Array(ByRef System.Array, ByRef System.Array) As Object
set_FFPOL1Array(ByRef System.Array, ByRef System.Array, ByRef Object)
Thus I tried to Dim my arrays as System.Array instad of Single but this failed too always because of a type conflict. What am I doing wrong?
OK this was a little ridiculous but I managed to understand that I eventually had to initialize the Arrays, because the FORTRAN function did not do that:
Dim RealLev1 As Array = Array.CreateInstance(GetType(Single), 1, 1)
Dim ImagLev1 As Array = Array.CreateInstance(GetType(Single), 1, 1)
This did the job. Even better was:
Dim RealLev1(,) As Single = Array.CreateInstance(GetType(Single), 1, 1)
Dim ImagLev1(,) As Single = Array.CreateInstance(GetType(Single), 1, 1)
As #Nathan_Sav suggested, get_FFPOL1Array is returning an Object so you need to use Set.
Set vDummy = NSI.FFPOL1Array(RealLev1, ImagLev1)

Long Array VBA Issue

I'm trying to enter a long-array Formula into VBA that is >255 characters. I have followed past suggestions to dim both halves of the formula and merge them later. I am still having errors getting the array to function properly and was hoping someone could help review the code.
Here's the original code that exceeds the character limit I'm trying to get working:
Sub TestMacro()
Range("AZ7").Select
Selection.FormulaArray = _
"=SUM(IF(CONCATENATE(R3C3,[#Route],[#[Assumed Coating Type]],[#Diameter],[#[Year Installed (Coating)]])=CONCATENATE(HCA!R26C[86]:R13642C[86],HCA!R26C[-48]:R13642C[-48],HCA!R26C[87]:R13642C[87],HCA!R26C[-19]:R13642C[-19],HCA!R26C[88]:R13642C[88]),HCA!R26C[-36]:R13642C[-36]))"
End Sub
Here is my latest attempt to split the code in half following past advice: https://www.mrexcel.com/forum/excel-questions/853889-long-array-visual-basic-applications-issue.html
http://dailydoseofexcel.com/archives/2005/01/10/entering-long-array-formulas-in-vba/
Sub LongArrayFormula()
Dim theFormulaPart1 As String
Dim theFormulaPart2 As String
theFormulaPart1 = "=SUM(IF(CONCATENATE(R3C3,[#Route],[#[Assumed Coating Type]],[#Diameter],[#[Year Installed (Coating)]])""X_X_X)"")"
theFormulaPart2 = "=CONCATENATE(HCA!R26C[86]:R13642C[86],HCA!R26C[-48]:R13642C[-48],HCA!R26C[87]:R13642C[87],HCA!R26C[-19]:R13642C[-19],HCA!R26C[88]:R13642C[88]),HCA!R26C[-36]:R13642C[-36]))"
With ActiveSheet.Range("AZ7")
.FormulaArray = theFormulaPart1
.Replace """X_X_X)"")", theFormulaPart2
End With
Any help is appreciated, thanks.
You should keep your truncated formula syntactically correct. Try it like this:
theFormulaPart1 = "=SUM(IF(CONCATENATE(R3C3,[#Route],[#[Assumed Coating Type]],
[#Diameter],[#[Year Installed (Coating)]])=X_X_X,HCA!R26C[-36]:R13642C[-36]))"
' ^^^^^
theFormulaPart2 = "CONCATENATE(HCA!R26C[86]:R13642C[86],HCA!R26C[-48]:R13642C[-48],HCA!R26C[87]:R13642C[87],HCA!R26C[-19]:R13642C[-19],HCA!R26C[88]:R13642C[88])"
With ActiveSheet.Range("AZ7")
.FormulaArray = theFormulaPart1
.Replace "X_X_X", theFormulaPart2
End With
Here I inserted X_X_X (could be anything else) in the place of some "closed expression" in the formula. That keeps the truncated formula correct from a syntax point of view, so the statement .FormulaArray = theFormulaPart1 can accept it. Replacement can then proceed in the second step.
You can also try this(
please don't run it from the VBE, try to run it from sheets environment. Go to Developer-Macros-Your Macro -Run or Run it from a button or shortcut and it will work without problem):
Range("AZ7").Select
Selection.Formula = _
"=SUM(IF(CONCATENATE(R3C3,[#Route],[#[Assumed Coating Type]],[#Diameter],[#[Year Installed (Coating)]])=CONCATENATE(HCA!R26C[86]:R13642C[86],HCA!R26C[-48]:R13642C[-48],HCA!R26C[87]:R13642C[87],HCA!R26C[-19]:R13642C[-19],HCA!R26C[88]:R13642C[88]),HCA!R26C[-36]:R13642C[-36]))"
SendKeys "{F2}"
SendKeys "^+{ENTER}"

"PrintTicket provider failed to convert DEVMODE to PrintTicket"

few years ago I wrote a WPF (Visual Basic 2012 based) app which included "printing" some report using standard WPF printdialogs/paginators/features....
everyting worked fine since then (2011/2015), and I did not change a line of that working code...
Now I had to change something (not printing related) to that project and of course I checked the printing features as well...
now the "printing" code fails when using it... actually is not the "paginator" code, but accessing the PrintTicket/Que objects fails reporting
"PrintTicket provider failed to convert PrintTicket to DEVMODE. Win32 error: The parameter is incorrect. "
but it's weird as it does not always fail, and it fails differently with different printers...
using for instance "PDF Creator" virtual printer, it fails writing/settings some properties of my Que object and not others, while using a different printer fails on others...
for instance, PDF Creator virtual printer:
1) myQue.DefaultPrintTicket = myTicket = OK
2) myQue.CurrentJobSettings.Description = "some title" = OK with some printer, FAILS with a different printer
but 2) only fails the very first time it is set, and I can "resolve" "looping" a few times with a minor time sleep.... again, the second or third time it succeded...
so I wrote an ugly code like
Dim dlg As New PrintDialog
.....
myTicket = dlg.PrintTicket
myQue = dlg.PrintQueue
'-----
' to check in a loop if the interesting
' properties has been set
Dim ticketIsSet(1) As Boolean
For iLoop As Integer = 1 To 5
'it can fail with DEVMODE = NULL
Try
If Not ticketIsSet(0) Then
myQue.DefaultPrintTicket = myTicket
ticketIsSet(0) = True
End If
If Not ticketIsSet(1) Then
myQue.CurrentJobSettings.Description = Me.Title
ticketIsSet(1) = True
End If
Catch ex As Exception
Errors.Add(ex.Message)
System.Threading.Thread.CurrentThread.Sleep(1000)
End Try
If ticketIsSet(0) AndAlso ticketIsSet(1) Then Exit For
Next
If Errors.Count Then
' it's still ok if title can't be set... :(
If ticketIsSet(0) Then Errors.Clear()
End If
so far, "so good" as I get the job done... but only partially... as my Paginator is used to (succesfully) populate a System.Windows.Controls.DocumentViewer... this alternate documentviewer window can later actually print if requested...
and again, with different printers it succed or fail with "PrintTicket provider failed to convert PrintTicket to DEVMODE. Win32 error: The parameter is incorrect. " exception...
with PDF Creator virtual printer it succed, with a different physical printer it fails...
I tried the very same looping trick as above, like
Dim Errors As New Specialized.StringCollection
Dim bDone As Boolean = False
For iLoop As Integer = 1 To 5
Try
Dim writer As System.Windows.Xps.XpsDocumentWriter = System.Printing.PrintQueue.CreateXpsDocumentWriter(m_printQueue)
writer.Write(Me.docViewer.Document.DocumentPaginator, Me.m_printTicket)
writer = Nothing
bDone = True
Catch ex As Exception
Errors.Add(ex.Message)
System.Threading.Thread.CurrentThread.Sleep(1000)
End Try
If bDone Then Exit For
Next
If bDone Then Errors.Clear()
If Errors.Count <> 0 Then BasShowErrors(Errors, Me, False)
and here it fails (again, on some printers) on
writer.Write(Me.docViewer.Document.DocumentPaginator, Me.m_printTicket)
with "PrintTicket provider failed to convert PrintTicket to DEVMODE. Win32 error: The parameter is incorrect. " exception...
obviously that printer is ok as regards other programs like World, Excel and the like, and it's ok as well with all other (NOT WPF based) projects... and again this only occur "NOW", as it worked like a charme at the time of the initial development...
my current settings are:
Win7 Ultimate sp 1
SQL 2014 Dev Edition (not relevant)
Visual Studio 2012 Ultimate Version 11.0.61219.00 Update 5
Microsoft .NET Framework version 4.6.01055
I even tried "repairing" the NET Framework with NetFramwork Repair Tool (https://www.microsoft.com/en-us/download/details.aspx?id=30135) with no success...
any hint is very appreciated :)
TIA
asql

Resources