How to take a named path string stored in Excel's name manager and open a file using it. The stored string contains the entire file string - excel-2010

The first routine grabs the filename string as the user locates a file which was exported from Quickbooks
The second routine writes that name into the name manager as a string under the name
"PathToEmployeeWithholding"
The third routine attempts to open the file using the name stored in the name manager
I have verified in the name manager that the name and correct path string is there, but I have not been successful in using that name to retrieve the file for reading.
The current code returns a 1004 error, but debug.print does give the correct path, pasting the string in the windows run box opens the spreadsheet, and so does a static statement with the path.
Thanks in advance for your help
lang-VB
'HouseKeepingCODE Module
Sub GetPath()
'This sub gets the path to a File defined by the user within the routine
'It then calls another sub that applies that path to a name in the worksheet.
' Before calling this routine, The name should first be searched for, and then verified, then opportunity given to change the name.
Dim MyPath As String 'String to hold the path to an excel spreadsheet exported from quickbooks
Dim NameToChange As String 'String that holds the name manager name to store the path under
Dim NameComment As String 'Comment to identify the name in the name manager
NameToChange = "PathToEmployeeWithholding"
NameComment = "This Name contains the Path to the 'Employee Withholding' worksheet exported from quickbooks using VBA"
With Application.FileDialog(msoFileDialogFilePicker)
If .Show <> 0 Then
MyPath = .SelectedItems(1)
End If
End With
'Debug.Print PathToWithholding
'This routine should be modified
'It should simply get a path to a file,
'And return that path to the calling subroutine
'The calling subroutine should then add comment and call the changevalueofname subroutine
Call ChangeValueOfName(NameToChange, MyPath, NameComment) 'this routine stores the retrieved text string in the name manager
End Sub
Sub ChangeValueOfName(NameToChange As String, NewNameValue As String, Comment As String)
'
' ChangeValueOfNameMagagerName Macro
' Changes the Value of a defined name in the Name Manager
'This should be used to change the name.
'
'Once the file is selected data needs to be imported to an array, and the
'Employee name values need to be checked against the worksheets in the workbook and against the recap sheet
'If changes are needed, it needs to write them into the workbook, including changing recap sheet and adding
'worksheets for any new employees
'
'
'
'
With ActiveWorkbook.Names(NameToChange)
.Name = NameToChange
.RefersTo = NewNameValue
.Comment = Comment
End With
End Sub
'****problem subroutine below***
Sub UpdateEmployeewithholding()
'This sub will clean employee withholding as it is exported from quickbooks and then read the file into this workbook
'The path is already stored in the names manager
'This routine needs to integrate changevalueofname and getpath. They should update before executing the balance of this routine
Dim MyWorkBook As Workbook
Dim MyPath As Variant 'Contains path to employee withholding spreadsheet as exported from quickbooks. This sheet is to be modified for reading, but not saved
Dim MyRange As Range 'Contains a defined range after setting it so
Dim whichrow As Variant 'Marks the starting point for routines that find and delete blanks as well as those that define range values and scan them into an array
Dim Direction As Variant 'Defines whether we are progressing over "Rows" or "Columns"
Dim ArrayWidth As Range 'Holds the top row addresses of the array
Dim ArrayHeight As Range 'Holds the left column addresses of the array
Dim MyArray As Variant 'Holds the array to transfer to this spreadsheet
Dim Width As Long 'Holds the array width to prevent loosing it when the original spreadsheet closes
Dim Height As Long 'Holds the array height to prevent loosing it when the original spreadsheet closes
whichrow = 1 'We are starting in cell A! or R1C1
Direction = "Rows"
'******************************************************************************************************
'***INSERT Code that will read the string value stored in the name manager Name "PathToEmployeeWithholding" into the variable "MyPath"
' and eliminate the hard coded path from the routine
' STILL MISSING
'*****************************************************************************************************
'Setting MyPath to the fixed path to employee withholding until we can get the routine to 'open the workbook from a varialbe
'stored in the name manager
MyPath = ThisWorkbook.Names("PathToEmployeeWithholding")
'ActiveWorkbook.Names (PathToEmployeeWithholding)
Debug.Print MyPath 'This works
Set MyWorkBook = Workbooks.Open(MyPath) '***Problem line returns 1004 stored-path could
'not be found
Debug.Print ActiveWorkbook.Name
'**** The immediate statement below worked ***
debug.Print thisworkbook.Names("PathToEmployeeWithholding")="D:\redacted\Employee Withholding .xlsx"
'***Code below to extract data from workbook opened above

The problem was in the fact that pulling the name back from name manager always added an = sign plus open and close quotes for delimiters. .eg
="string\text"
The solution was to strip the delimiters using the mid function
Sub UpdateEmployeewithholding()
'This sub will clean employee withholding as it is exported from quickbooks and then read the file into this workbook
'The path is already stored in the names manager
'This routine needs to integrate changevalueofname and getpath. They should update before executing the balance of this routine
Dim MyWorkBook As Workbook
Dim MyPath As String 'Contains path to employee withholding spreadsheet as exported from quickbooks. This sheet is to be modified for reading, but not saved
Dim MyRange As Range 'Contains a defined range after setting it so
Dim whichrow As Variant 'Marks the starting point for routines that find and delete blanks as well as those that define range values and scan them into an array
Dim Direction As Variant 'Defines whether we are progressing over "Rows" or "Columns"
Dim ArrayWidth As Range 'Holds the top row addresses of the array
Dim ArrayHeight As Range 'Holds the left column addresses of the array
Dim MyArray As Variant 'Holds the array to transfer to this spreadsheet
Dim Width As Long 'Holds the array width to prevent loosing it when the original spreadsheet closes
Dim Height As Long 'Holds the array height to prevent loosing it when the original spreadsheet closes
Dim StrLength As Long
whichrow = 1 'We are starting in cell A! or R1C1
Direction = "Rows"
MyPath = ThisWorkbook.Names("PathToEmployeeWithholding") 'get string from name manager
Debug.Print MyPath 'As stored in name manager the name always returns and = sign plus open and close quotes
StrLength = Len(MyPath) 'In order to get the workbook to open programatically these must be stripped
MyPath = Mid(MyPath, 3, StrLength - 3) 'The mid statement strips these delimiters off, leaving just the text
Debug.Print MyPath
Set MyWorkBook = Workbooks.Open(MyPath)
Debug.Print ActiveWorkbook.Name
'Stuff below gets data from opened workbook

Related

How to use a variabe value to name a file using SPSS syntax?

I have a data set with 100+ variables for each of many people.
I have two variables for the person's name: lastname and firstname.
How can I create an output file using the names (i.e., the values of the variables lastname and firstname)?
I would like to do a split file by lastname firstname and export the data for each person into a text file that uses the person's name as the file name.
Below is what my spss command file is doing now. How can I get the command file to spit out separate files for each person?
SORT CASES BY lastname firstname .
SPLIT FILE BY lastname firstname .
PRINT / " ".
PRINT /
"===================================================================".
PRINT / "Report of Selected Responses from the".
PRINT / "Survey Form Document".
Print /"Responses for Candidate: " .
Print / firstname.
Print / lastname.
PRINT /
"===================================================================".
DO IF (Q1.5month EQ "" OR sysmis(q1.5day) OR sysmis(q1.5year) ).
Print
/ "1.5. Some or all of date of birth left blank".
END IF.
[More such print statements.]
EXECUTE.
SPLIT FILE OFF.
First create an empry string variable and populate it:
String firstname_lastname (A100).
Compute firstname_lastname=concat(rtrim(firstname),"_",rtrim(lastname)).
EXECUTE.
Then go to Data menu, Split into files, select your new firstname_lastname variable as the split variable, and.under options select "value labels". Pick a folder and you are done. Maybe click paste, to have everything in syntax 😉

Microsoft Access: Complex string search to update field in another table

I have a table that is linked to Access to return the results of emails into a folder. All of the emails being returned will be answering the same questions. I need to parse this email body text from this table and update several fields of another table with this data. The problem is that the linked table brings the text in super messy. Even though I have the email that is being returned all nicely formatted in a table, it comes back into access a hot mess full of extra spacing. I want to open a recordset based on the linked table (LinkTable), and then parse the LinkTable.Body field somehow so I can update another table with clean data. The data that is coming back into LinkTable looks like this:
Permit? (Note: if yes, provide specific permit type in Additional Requirements section)
No
Phytosanitary Certificate? (Note: if recommended, input No and complete Additional Requirements section)
Yes
Additional Requirements: if not applicable, indicate NA or leave blank (Type of permit required, container labeling, other agency documents, other)
Double containment, The labeling or declaration must provide the following information: -The kind, variety, and origin of each lot of seed -The designation “hybrid” when the lot contains hybrid seed -If the seed was treated, the name of the substance or p
The answer of the first two should either be yes or no, so I figured I could set up code with case statements and based on a match I should place yes or no in the corresponding field in my real table (not sure how to deal with the extra spaces here), The third one could have any number of responses, but it is the last question so anything after the "(Type of permit required, container labeling, other agency documents, other)" could be taken and placed in the other table. Does anyone have any ideas how I could set this up? I am at a bit of a loss, especially with how to deal with all of the extra spaces and how to grab all of the text after the Additional Requirements paragraph. Thank you in advance!
My select statement to get the body text looks like this:
Set rst1 = db.OpenRecordset("SELECT Subject, Contents FROM LinkTable WHERE Subject like '*1710'")
There are multiple ways to do this, one is using Instr() and Len() to find beginning and end of the fixed questions, then Mid() to extract the answers.
But I think using Split() is easier. It's best explained with commented code.
Public Sub TheParsing()
' A string constant that you expect to never come up in the Contents, used as separator for Split()
Const strSeparator = "##||##"
Dim rst1 As Recordset
Dim S As String
Dim arAnswers As Variant
Dim i As Long
S = Nz(rst1!Contents, "")
' Replace all the constant parts (questions) with the separator
S = Replace(S, "Permit? (Note: if yes, provide specific permit type in Additional Requirements section)", strSeparator)
' etc. for the other questions
' Split the remaining string into a 0-based array with the answers
arAnswers = Split(S, strSeparator)
' arAnswers(0) contains everything before the first question (probably ""), ignore that.
' Check that there are 3 answers
If UBound(arAnswers) <> 3 Then
' Houston, we have a problem
Stop
Else
For i = 1 To 3
' Extract each answer
S = arAnswers(i)
' Remove whitespace: CrLf, Tab
S = Replace(S, vbCrLf, "")
S = Replace(S, vbTab, "")
' Trim the remaining string
S = Trim(S)
' Now you have the cleaned up string and can use it
Select Case i
Case 1: strPermit = S
Case 2: strCertificate = S
Case 3: strRequirements = S
End Select
Next i
End If
rst1.MoveNext
' etc
End Sub
This will fail if the constant parts (the questions) have been altered. But so will all other straightforward methods.

Parsing Listbox results and updating values

The included code pulls parameters from a form and executes a stored procedure. The result is captured via a list box object and displayed on the form. How can I parse the result from the stored procedure, modify values, and then submit it back so the list box shows the updates?
My stored procedure returns a list of user accounts and their status (1,0). What I want to do is update the status from 1,0 to true,false so that when the results are shown in the form, the listbox shows true and false as opposed to 1,0.
Dim paramAcctNo As String
Dim paramProfileId As String
Dim query1 As String
Dim query2 As String
'Populating the form parameters
paramAcctNo = [Forms]![frm_userlookup]![lst_searchresults]
paramProfileId = [Forms]![frm_userlookup]![tb_hidden]
'Executing SP
query1 = "EXEC dbo.sp_ADCON_userDetailView '" & paramAcctNo & "','" & paramProfileId & "'"
'assigning results to listbox to display in form
Me.listbox1.RowSource = query1
If you are allowed to change the actual values in the query1 table after your stored procedure has run, you can run two simple UPDATE queries to change the 1s to True and the 0s to False.
UPDATE query1 SET [field name that contains the 1] = "True"
WHERE ([field name that contains the 1]="1")
UPDATE query1 SET [field name that contains the 0] = "False"
WHERE ([field name that contains the 0]="0")
A problem that you might run into is with a Type mismatch error. If the field containing the 0s and 1s is numeric, you won't be able to update it to a string value.

Simple method to remove files from a listbox - LOTUS 7

So I have a button that displays a listbox that I've created. This listbox has some attachments, it is populated with some items ( the attachments ). Also, I created another button which I want to remove the items that I will select from the listbox. Is there any simple method/formula for doing this? Thanks in advance.
Please try to explain a litte bit more clearly what you are trying to do.
I assume that by "listbox" you mean a field of type listbox. That kind of field can not contain attachments, just text values. Do you mean that the listbox contains the name of one or more attachments?
You talk about "a button that displays the listbox". Is that relevant to the problem?
How is the listbox created and populated? I assume from another, field, containing the names of the attachments?
I used some assumptions (you really need to explain your problems in more detail), and this is how I solved it:
Field 'ListData': Text field, hidden. Contains the values you want to display (e.g. names of attachments), separated by semicolon.
Field 'ListBox': Listbox field, allow multiple values, refresh choices on document refresh, use formula for choices:
#Explode(ListData;";")
Button "Delete Selected":
Sub Click(Source As Button)
Dim ws As New NotesUIWorkspace
Dim uidoc As NotesUIDocument
Dim selected As Variant
Dim listdata As Variant
Dim files List As String
Dim newlistdata As String
Dim i As Integer
Set uidoc = ws.CurrentDocument
'*** Read the field values and split into arrays
listdata = Split( uidoc.FieldGetText("ListData"), ";" )
selected = Split( uidoc.FieldGetText("ListBox"), ";" )
'*** Convert listdata array into a Lotusscript list
Forall file In listdata
files(file) = file
End Forall
'*** Loop through the array of selected values
For i = 0 To Ubound(selected)
'*** Check if the currently processed value is in the files list
If Iselement(files(selected(i))) Then
Erase files(selected(i)) ' Remove/erase from the list
'*** Add code here to remove attachments from document
'*** if that is what you actually want to do.
'*** Use notesEmbeddedObject.Remove method for that.
End If
Next
'*** Now we have the files list with the selected items removed.
'*** Loop though the list and build a string of remaining values
Forall ff In files
newlistdata = newlistdata + ff + ";"
End Forall
'*** Write the new string of remaining attachments back to the listdata field
Call uidoc.FieldSetText("ListData", newlistdata)
Call uidoc.Refresh
End Sub
You just need to think through the problem and figure out what you really want to do, then break it down to smaller steps, solve each one of those, etc. Lotusscript is not different from other languages in that way,
Note: The code may look complicated and is longer than it has to be, as I added plenty of comments so you (hopefully) can understand what is being done...
1) Use hidden multivalue field for options in listbox. Its value will be computed based on default values (#Attachment or another field value) and will remove all values mentioned in another hidden field "removed" (#Replace).
2) "Removed" field will be populated by your Remove button like
FIELD removed := #Trim(#Unique(removed:listbox));#All
"listbox" contains values currently selected in listbox.
3) I recommend to provide some feedback of removed values and ability to undo/reset.

How to get data out of a recordset in excel?

I have the following code:
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Dim AppPath As String
Set cn = CreateObject("ADODB.Connection")
AppPath = Application.ActiveWorkbook.Path
Set rs = CreateObject("ADODB.RecordSet")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & AppPath & "\Masterlist_Current_copy.accdb;"
strSql = "SELECT [Neptune Number],[Description],[Manufacturer],[Manufacturer P/N] FROM [All Components];"
cn.Open strConnection
Set rs = cn.Execute(strSql)
'Need Code here to get Info out of recordset
I am trying to get information out of the recordset that has the query result being dumped into it. I'm trying to figure out how to query the recordset and get the number of rows with a specific value in the "Neptune Number" field. I will then insert the correct number of rows into the worksheet I'm modifying. After that I need to get the data for that value and insert it into the worksheet.
Note: I don't care if recordset, datatable or anything else is used I simply need to be able to do what I described above. Please show code.
The easiest way to get where you I think you are asking to go is to modify your SQL statement changing
strSql = "SELECT [Neptune Number],[Description],[Manufacturer],[Manufacturer P/N] FROM [All Components];"
to
strSql = "SELECT [Neptune Number],[Description],[Manufacturer],[Manufacturer P/N] FROM [All Components] WHERE [Neptune Number] = 'Specific Value' ;"
This will force the sql query to only return the records you need. the .find method can be used for filtering the recordset, but i have avoided using it in this instance as it is cleaner to just ask the db for only the information that you want.
to process the recordset you can use the following
with rs
'will skip further processing if no records returned
if not (.bof and .eof) then
'assuming you do not need the headers
'loop through the recordset
do while not .eof
for i = 0 to .fields.count -1
'assuming the active sheet is where you want the data
cells(row, i + colOffset) = .fields(i).value
next
Rows(Row & ":" & Row).Insert
.movenext
loop
end if
end with
Where row is the starting point of your data and colOffset is the starting column of your data. Note that this code does not do things in the exact order you specified in your question (I am inserting rows as needed instead of calcualting the number of records up front.)
I have avoided using .recordcount because I find depending on the database used it will not return a correct record count.

Resources