Any suggestions for determining if a user-selected Excel file is the incorrect one? I am having the user select the excel file to be parsed and I want to refuse processing it if appears to be an incorrect format.
If the file being parsed has headings, then check some of the text.
Sub ImportXYZ()
' ... Code to import
If ActiveWorkbook.Worksheets("Sheet1").Range("A1") <> "XYZ" Then
MsgBox CStr(ActiveWorkbook.Name) & vbCr & _
"The file you selected does not contain XYZ data!" & vbCr & "Please try again."
' ... Code to reset
Call ImportXYZ
End If
' ... Code to process import
End Sub
Put a hidden version field or other string in the excel file and break the execution if the string does not match. Assuming of course that you have control over the file or template, from which the file is created.
As an alternative to putting a marker that identifies the right type of file inside a worksheet, you can also use Workbook properties. Create a Custom property "MyExcelFilesClassification", and give the property a value like "MyTypeOfWorkbook". When your code opens the file, check that the Property has the right value, with something like:
Office.DocumentProperties customProperties = workbook.CustomDocumentProperties as Office.DocumentProperties;
foreach (Office.DocumentProperty property in customProperties)
{
if (property.Name == "MyExcelFilesClassification")
{
string modelType = property.Value as string;
if (modelType == "MyTypeOfWorkbook")
{
// do something
}
}
}
This is C# code, but the VBA or VB syntax shouldn't be very different.
Related
Trying to get data from Excel and merge it into Word using MailMerge (just like how it is done in this video).
However, fields aren't getting updated after running this code. VBA isn't throwing any error so looks like code is fine. Can you please help?
Sub getdata()
Dim numRecord As Integer
Dim myName As String
myName = InputBox("Enter the field name and relax!")
Set dsMain = ActiveDocument.MailMerge.DataSource
If dsMain.FindRecord(FindText:=myName, Field:="Fields") = True Then
numRecord = dsMain.ActiveRecord
End If
End Sub
Note: Data in Excel looks like this:
Fields First Layer Second Layer
CC 5 3
So when someone enters CC in Input box I want first_layer and Second_layer fields in word to get updated to 5 and 3 respectiely.
If you're running the mailmerge from Word, you don't actually need any VBA for this - it can all be done with a SKIPIF field. For example the following field code does the same as the macro in the video is supposed to:
{SKIPIF{FILLIN "Name to merge" \o}<> {MERGEFIELD Name}}
or:
{SKIPIF{FILLIN "Name to merge" \o}<> «Name»}
Note: The field brace pairs (i.e. '{ }') for the above example are all created in the document itself, via Ctrl-F9 (Cmd-F9 on a Mac or, if you’re using a laptop, you might need to use Ctrl-Fn-F9); you can't simply type them or copy & paste them from this message. Nor is it practical to add them via any of the standard Word dialogues. Likewise, the chevrons (i.e. '« »') are part of the actual mergefields - which you can insert from the 'Insert Merge Field' dropdown (i.e. you can't type or copy & paste them from this message, either). The spaces represented in the field constructions are all required.
Hi I have a macro that creates multiple sheets and has Name, Number, Sheet Category. The last being my own project parameter.
I can successfully create the sheets with name and number but I am having difficulty adding the value from CSV file to the project parameter "SD_Sheet Category". Below are some code grabs to help explain.
Public Module mSheetCreator
Public Structure structSheet
Public sheetNum As String
Public sheetName As String
Public sortCategory As String
End Structure
Then I have a function that reads the CSV file and does the following:
Try
currentRow = MyReader.ReadFields()
'create temp sheet
Dim curSheet As New structSheet
curSheet.sheetNum = currentRow(0)
cursheet.sheetName = currentRow(1)
curSheet.sortCategory = currentRow(4)
'add sheet to list
sheetList.Add(curSheet)
Then I have a transaction that does the following:
For Each curSheet As structSheet In sheetList
Try
If sheetType = "Placeholder Sheet" Then
m_vs = ViewSheet.CreatePlaceholder(curDoc)
Else
m_vs = ViewSheet.Create(curDoc, tblock.Id)
m_vs.Parameter("SD_Sheet Category").Set(CStr(curSheet.sortCategory))
End If
m_vs.Name = curSheet.sheetName
m_vs.SheetNumber = curSheet.sheetNum
The problem is this code:
m_vs.Parameter("SD_Sheet Category").Set(CStr(curSheet.sortCategory))
I am getting a warning that says it's an "implicit conversion from 'String' to 'Autodesk.Revit.DB.BuiltInParameter'"
once I build solution
When I run the code in Revit it produces an error saying
"Conversion from string 'SD_Sheet Category" to type 'Integer' is not valid"
It creates the sheets but disregards all the info in the CSV file. I know the rest of the code works as I have removed this particular line of code so I know it isn't the problem
Any suggestions??
I believe that as of a particular version of Revit API you cannot use .Parameter(“name”)
Because there might be two parameters with the same name.
So you need to do something more like
Dim cat as Parameter
Cat = m_vs.GetParameters(“sd_sheet category”).First()
Cat.Set(CSTR(cursht.sortCategory))
Good luck!
The last week I asked how to solve an error in an evaluate statement (Error in Evaluate statement macro).
Once fix it, I have other error with the same evaluate statement, it doesn't give me any value.
I will describe what I have and what I try.
#DbLookup in Calculate Text
I have this code into in an calculate Text and it works fine.
suc := #Trim(#Left(LlcPoliza;2));
_lkp := _lkp := #DbLookup("":"NoCache";"C1256EAD:00478951";"People2"; "D"+suc; "FullName");
#If( #IsError( _lkp ) ; " " ; _lkp );
#Name([CN];_lkp)
LlcPoliza is a document field (doc.LlcPoliza) and in a document it has for example the value C2H2H2.
The formula give first the value C2 and then look up into People2 who is D+C2 and give me a person.
It works fine.
Evaluate Statement (#DbLookup) in a Class
I have a class DirectorSucursal.
Class DirectorSucursal
Private m_branch As String
'Constructor class
Public Sub New (branch)
Dim subString As String
subString = Left(branch, 2)
me.m_branch = subString
End Sub
'Deleter Class
Public Sub Delete
End Sub
'Sub show the code about Suc
Public Sub GetCodSuc
MsgBox m_branch
End Sub
'Function get the name director
Public Function getNameDirector As String
Dim varResult As Variant
varResult = Evaluate({#DbLookup("":"NoCache";"C1256EAD:00478951";"People2"; "D} & m_branch & {"; "FullName)"})
getNameDirector = CStr( varResult(0) )
End Function
End Class
Then, in a button I instantiate the new object DirectorSucursal with the parameter of the field doc.LlcPoliza(0) like this.
Sub Click(Source As Button)
Dim director As New DirectorSucursal(doc.LlcPoliza(0))
director.GetCodSuc
director.getNameDirector
end Sub
The field doc.LlcPoliza(0) has the value C2H2H2. GetCodSuc show the value C2, but the function getNameDirector doesn't work.
It shows the error:
Operation failed
Evaluate Statement (#DbLookup) in click button
I have tried the same but into a click sub.
Sub Click(Source As Button)
Dim subString As String
subString = Left(doc.LlcPoliza(0), 2)
Dim eval As String
eval = Evaluate({#DbLookup("":"NoCache";"C1256EAD:00478951";"People2"; "D} & subString & {"; "FullName)"})
Msgbox eval
End Sub
The field doc.LlcPoliza(0) has the value C2H2H2. But it doesn't work
It shows the error:
Operation failed
My question is: what am i doing wrong? Why the code works fine in a calculate text with #Formula but with Lotusscript not?
Thanks.
EDIT 1:
I have added and Error Goto, modified the class code, modified #dblookup in calculate text and I have this error:
Error in EVALUATE macro
Please read documentation and use help! evaluate always returns an ARRAY, as stated in the help:
Return value
variant
The result of the evaluation. A scalar result is returned.
To make your code return a STRING you need to change it like this:
Public Function getNameDirector As String
Dim varResult as Variant
varResult = Evaluate({#DbLookup("":"NoCache";"C1256EAD:00478951";"People2"; "D} & m_branch & {"; "FullName")})
getNameDirector = Cstr( varResult(0) )
End Function
The CStr is just there for the case where the #DBLookup returns an error or a number (both possible)
Just a few things in general:
NEVER write even one line of LotusScript- code without error handler. It will cause you trouble FOR SURE. If you had error handling in place, then it would have told you in which line the error occured...
NEVER use the result of #DBLookup without checking for #IsError... It will cause lot of troubles when the lookup fails.
IF you use #Iserror, then don't do the Lookup twice, assign the lookup to a variable and check that one for #Iserror, like this. Otherwise performance will go down in big forms:
Example:
_lkp := #DbLookup("":"NoCache";"C1256EAD:00478951";"People2"; "D"+suc; "FullName");
#If( #IsError( _lkp ) ; " " ; _lkp )
EDIT: As Knut correctly stated in his answer the real cause for the error was a typo in the formula ( Fullname)" instead of Fullname") that I fixed in my example as well.
1) My suggestion is to never (or at least very seldom) use Evaluate() in Lotusscript. You have proper Lotusscript functionality to do almost everything.
One of the major reasons is that the code is very hard to debug (which is what you are now experiencing).
2) Don't use extended notation when you work with fields. The best practice is to use the GetItemValue and ReplaceItemValue methods of the NotesDocument class for performance reasons as well as compatibility reasons.
3) In the examples with buttons you have a reference to doc, but it is never declared or initialized in the code. If you would use Option Declare at the top of your code you would catch these kinds of errors.
4) I also reccomend against using replica ID to reference databases, that makes it very hard to maintain in the future. Unless you have a very good and convincing reason, reference them by server and filename instead.
I would suggest you refactor your code to something like this:
'Function get the name director
Public Function getNameDirector() As String
Dim db as NotesDatabase
Dim view as NotesView
Dim doc as NotesDocument
Dim key as String
Dim fullname As String
Dim varResult As Variant
Set db = New NotesDatabase("Server/Domain","path/database.nsf")
If db Is Nothing Then
MsgBox "Unable to open 'path/database.nsf'"
Exit Function
End if
Set view = db.GetView("People2")
If view Is Nothing Then
MsgBox "Unable to access the view 'People2'"
Exit Function
End if
key = "D" & m_branch
Set doc = view.GetDocumentByKey(key)
If doc Is Nothing Then
MsgBox "Could not locate document '" & key & "'"
Exit Function
End if
fullname = doc.GetItemValue("FullName")(0)
End Function
Ando of course update the button actions in the same way.
Yes, it is a few lines longer, but it is much more readable and easier to maintain and debug. And you have error handling as well.
Change your last part in #DbLoookup code line to:
"FullName")})
I have a VBA code in Excel that ask the user where an .xls file is a make something with that file.
What I'd like to do now is to pass the name of the file (myFile) to VBA code that I have in Access, in order to update a table with that file and other fields.
In VBA Excel, the name of the Sub is: Sub UpdateSupplier(myFile As String)
What is the code that I should use in VBA Access in order to use myFile?
Try this: Declare your variable myFile as public, that means not write:
Dim myFile in your Excel Sub,
but write instead
Public myFile in the Declare Section of the module.
Then create a new Function in this module, which only gives back this public variable myFile:
function GiveMemyFile() as string
GiveMemyFile = myFile
end function
Now you can call this function from Access to get the value of myFile.
think I found the solution now, it's so simple if you found it:
Your 'Makro' in Excel should look like this:
function Test (ByRef strFilename)
strFilename = yourFilename
end function
The first 'trick' is, to use a ByRef Parameter 'strFilename' to give back your Filename.
Now in Access you can use:
strNewFilename = ""
xl.Run "Test", strNewFilename
Debug.Print strNewFilename
and you will see the filename the Excel Macro wrote in the variable.
I have tested this and it worked fine for me. Good luck!
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.