programming for excel with foxpro (or any suggestions) - excel

I have a macro in excel that works.
Sub jim()
Range("$A$1").CurrentRegion.Select
Selection.RowHeight = 13
Selection.Font.Bold = True
…etc.
If I open a csv and run this macro it selects the seen data and then later does stuff to it.
So I made a foxpro program to do the same.
When I try to run in foxpro, I get a variable not found error.
local oExcel, oSheet
oExcel = CreateObject([Excel.Application])
oExcel.Visible = .T.
k:\wellcarestuff\All Data Files\"+ALLTRIM(xlfiles(1,1))
osheet = oexcel.workbooks.open("k:\wellcarestuff\all data files\20131210_CT_TransportationAddresses.csv") <<<=== it opens and shows the sheet here
Range("$A$1").CurrentRegion.Select <<<?=== get an error here?
Is the var it wants the current osheet?

On the line with the path, it looks like you are missing the beginning quote marks so it things that k:... is a variable. Should be:
"k:\wellcarestuff\All Data Files\"+ALLTRIM(xlfiles(1,1))
Try that and see if it works.

Related

What about "Application" as default object in Excel VBA?

I have just written this easy macro in Excel VBA for merging a group of selected cells:
Sub Macro_Merge()
Dim Temp As String
Dim S As Variant
Temp = ""
For Each S In Selection
If Temp = "" Then
Temp = CStr(S.Value)
Else:
Temp = Temp + "," + CStr(S.Value)
End If
Next
Selection.Merge
Selection.Value = Temp
Selection.VerticalAlignment = xlTop
End Sub
This works fine, but I always see that annoying dialog box, warning me about loosing data while merging (which is exactly what I'm trying to avoid in my macro).
I can get rid of that dialog box, configuration the Application's DisplayAlerts property:
Application.DisplayAlerts = False
Selection.Merge
Selection.Value = Temp
Application.DisplayAlerts = True
This is working fine.
So, as Application is the default object, I tried to clean up my code, as follows:
DisplayAlerts = False
Selection.Merge
Selection.Value = Temp
DisplayAlerts = True
As you see, I simply omit mentioning the Application object. This is something which is allowed and I've done in the past. (If not in VBA, then Delphi, maybe?)
... but to my surprise, the dialog box appears again (although pressing F1 brings me to the official "Application.DisplayAlerts" documentation).
This leaves me with a simple question:
If a simple DisplayAlerts = ... does not equal Application.DisplayAlerts = ... anymore, what does it mean and how can I use it?
For your information, I'm working with Excel-365.
DisplayAlerts is an undeclared variable.
Certain Application properties and methods can (effectively) have the Application omitted:
ActiveCell, ActiveSheet, ActiveWorkbook, ActiveWindow, Addins, Charts, Selection, etc.
Calculate, Evaluate, Intersect, Run, Union, etc.
(but see this answer why/how this works):
A boolean property such as DisplayAlerts (EnableEvents, ScreenUpdating, etc) doesn't fall into the above category.
A golden rule in order not to fall into such a trap is the usage of Option Explicit while writing macros.
Just to add some information to the answer of #BigBen. If you write something like Workbooks or ActiveSheet in your code, VBA is not looking into the Application-object - it is looking into a (rather well hidden) object named Global.
The global object is exposing some (but not all) properties and methods of the Application-object, so ActiveSheet is referring to Application.ActiveSheet - but not because the Application has a member with this name but because the Global object defines that ActiveSheet means Application.ActiveSheet. In fact even the Application-object is accessed via the Global object.
There is hardly any information about this Global object or its concept. I found a page from Microsoft describing the Global object of MS Word, but the only explanation there is "Contains top-level properties and methods that don't need to be preceded by the Application property.". For Excel, I found this page on O'Reilly.
From time to time you get strange error messages like "Excel VBA Method 'Range' of object'_global' failed" - this is a pointer to the Global object. I would be glad to learn more about the concepts and mechanics of this object, but I am afraid that there are only very few people around that know more (except of course Mathieu Guindon AKA Mr. Rubberduck...). In daily life, we take it for granted that things like ActiveSheet simply works.

VBS, when opening an Excel file, changes number format, destroying data

when try to open an excel file using VBScript, the values/numbers format gets change, destryoing the values.
For example: "0.0" is changed to "__0.0" (with spaces befores), "9000.0" is turned into "__9000.0" (with spaces befores) and "288" is replaced by "288000".
Some knows how to solve this?
Here is my code to open the file:
Dim ExcelFile
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set ExcelFile = objExcel.Workbooks.Open("File Directory")
I need the data as original (functional) in order to be used by another file.

To stop Excel updating calling Excel from AutoHotkey via COM

Let an handle to our currently active Excel sheet is created in an .ahk script through
Xl := ComObjActive("Excel.Application")
and then some values are managed, as instance through
Xl.Sheets("Book1").Range("K2:K239").Copy
It looks like AutoHotkey allows for using VBA syntax to interact with Excel workbooks and sheets, but what if I wanted to stop the Excel autoupdating function like I would do in VBA?
Application.ScreenUpdating = False
I've tried something like
Xl.Application.ScreenUpdating = False
and
Xl.ScreenUpdating = False
but AutoHotkey returns error in both the cases.
I think all you are missing is a colon... Xl.ScreenUpdating := False

How do I make an Excel VBA Function that works when I reopen the document?

OK, I've just written a very simple VBA script that goes off and grabs the file size of a file found at a specified location (edit update code from dscarr):
Public Function FileSize(path As String) As Variant
On Error GoTo Err_FileSize:
Dim retVal As Variant
Dim filesys As Object
Dim file As Object
retVal = ""
Set filesys = CreateObject("Scripting.FileSystemObject")
Set file = filesys.GetFile(path)
retVal = file.Size
Exit_FileSize: On Error Resume Next
FileSize = retVal
Exit Function
Err_FileSize: retVal = "Error: " & Err.Description
Resume Exit_FileSize
End Function
If I import this into a new workbook, save the document as a "Excel Macro-Enabled Workbook" alongside an empty file called readme.txt and then put "./readme.txt" in A1 and "=FileSize(A1)" in A2, A2 evaluates properly to the file size of readme.txt, 0 bytes. Great. If I then save the document, close and reopen it, I'm warned that macros are disabled. If I enable them, the content of A2 has changed to #VALUE! and nothing I do will make the function work again. Has anyone seen this before, can anyone point out the mistake that I'm making here?
edit: the issue seems to be caused by me using relative paths. I can't explain why it works for a new workbook, but not once saved and reopened, but using absolute paths solves the problem, which as dscarr identified, was a "File Not Found" issue.
I duplicated your code in an Excel 2007 Macro Enabled workbook and found that it worked just fine with the following caveats
It does not automatically update the value (e.g. run the FileSize function) when you open the workbook. This can be compensated for by adding some code to the Worrkbook_Open event handler that calculates the workbook.
I get the #VALUE error when it cannot find the file that is specified. Indeed, when the file is missing or incorrectly named the line "Set file = filesys.GetFile(path)" throws the error number 53 "File Not Found". In this case the return value is never set because the line of code that sets it is never called. You could try setting a default value of "File Not Found" before actually attempting to retrieve the file size.
In Excel 2010, Go File->Options->Trust Center->Macro Settings and make sure the Enable option button has been selected.

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