Open File based on Dictionary Value matched to Public Variable - vba

I have an excel file with a list of codes in column 1 relating to different workbooks.
At first I created a code that would loop through the codes and I would manually open the specific workbook using "Application.GetOpenFilename".
Now, I decided to make it more efficient and because the file path doesn't change I figured I'd create a global public variable with the file path location.
I create a dictionary that adds all the codes. (That is the loop between 2 and 50) The value in each row of Cells(i,1) contains an abbreviated code which is then tied to a public variable with the full file path/location. In this case, all the codes in rows 2 through 50 are ABC123 (key = ABC123). Other times I have multiple codes, which is why I add to a dictionary to keep the unique values and can then open these individual files.
I was hoping to loop through the dictionary to open the specific files related to the code, instead it tried to open the string value rather than the file path. ABC123.xls rather than C:\Users\xxxx\xxxx\ImportantFile2018.xls
I'm trying to figure how to get the dictionary key to equal the public variable I assigned with the same name.
Do not get hung up on variable names, these are just examples. The major issue is how to retrieve the variables value (file path) when the variable name (ABC123) matches a cell's value. Every cell value in column 1of the data has a matching variable with a filepath.
Option Explicit
Public ABC123 As String
Sub DefinedVariables()
ABC123 = C:\Users\xxxx\xxxx\ImportantFile2018.xls
End Sub
Sub Reporting_Update()
Dim dictClient As New Scripting.Dictionary
Dim key As Variant
Call DefinedVariables
For i = 2 To 50
If dictClient.Exists(Cells(i, 1).Value) Then
Else:
dictClient.Add Cells(i, 1).Value
End If
Next
For Each key In dictClient
Workbooks.Open FileName:=key

Related

Use VBA to assign and locate a specific table in a docx file by a method other than number of table

I have an access database I'm using to populate various docx templates. The same table appears in these docx files, but it's location (in relation to other tables) is not the same in each file. Is there a way to assign a label or a name to a table, such that the VBA can locate it by this means rather than by the normal table number?
The only way to index them through the .Tables collection is by ordinal. But, you could always pick one of the Table properties like .ID, .Title, or .Descr to build your own retrieval function. Using .ID it might look something like this:
Private Function GetTableById(seeking As String) As Table
Dim i As Long
With ThisDocument
For i = 1 To .Tables.Count
If .Tables(i).ID = seeking Then
Set GetTableById = .Tables(i)
Exit Function
End If
Next
End With
End Function
Called like this:
Dim foo As Table
Set foo = GetTableById("bar")
If Not foo Is Nothing Then
'...

Requested Member of Collection Does not Exist - VBA error when copying from array to Word table

I am reading a string from a csv file and trying to print this into respective cells in a word document table. So far I have this, but it keeps throwing the Collections does not exist error:
Private Sub CommandButton1_Click()
Dim MyData As String, strData() As String
Open "D:\Users\file2.csv" For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, ",")
For i = 1 To UBound(strData)
ActiveDocument.Tables(1).Cell(i, 2).Range.Text = strData(i)
Next i
End Sub
Basically I am taking the ith element of the array and pasting it in the ith row of the second column.
The csv file has only 1 line (will always have only one line) with 6 fields:
hello,world,blah,haha,yes,huh
To be safe (and for testing purposes), my table is an 8x8 table, and it still throws the error on the ActiveDocument... line.
To be even safer, I have 2 tables, (just in case my Table number is off (not sure if it begins at 1 or 0)).
Changed the line to:
ActiveDocument.Tables(1).Cell(1, i).Range.Text = strData(i - 1)
And it works. However the text is only displayed after I close the user form. How do I get the text show upon button click?
Turns out I had a another function after, that I was not using. When I commented out this function, it worked. I still do not know why an unused function would prevent the userform from displaying the entered data, but it works.
Regarding the Collection does not exist error, I changed the line to:
ActiveDocument.Tables(1).Cell(1, i).Range.Text = strData(i - 1)
and now it works

Excel: Populate cells with data from file names that use common naming convention

I have 1000+ files (mostly PDFs) that all follow a common naming convention, e.g.:
CA0001.02 Tax Return A-333 650.5ca 20140729.pdf
Each file has different information in its filename (the "CA number" is different, the "A-number" is different, the date is different, etc.).
I want to create a spreadsheet so that I can manipulate the data that these file names contain; in other words, take the 5 pieces of info listed in the filename and turn it into 5 columns in Excel.
In my research I've come across ways to insert the Excel filename into the current sheet, but that's not what I want. I want to insert the filenames of thousands of other files located elsewhere on the computer. My ideal solution would ensure that:
Each file gets its own row
Each field in the filename goes into the appropriate Excel column
Any filenames that are missing data wouldn't break the operation (e.g., if the date "20140729" wasn't at the end of the file, then the whole thing wouldn't break, it would just leave that cell empty and move to the next file).
I imagine this will require VBA or Command Prompt (and maybe something else?) but my skill with VBA is pretty weak. I would really appreciate any suggestions to get me started. Thanks!
Your question is too generic for a simple answer. The following VBA function with some help from Google should get you started:
Sub Test()
Dim FN As String, R As Integer
R = 1
FN = Dir("C:\*")
Do While FN <> ""
Cells(R, 1) = FN
If InStr(FN, "CA") Then Cells(R, 2) = "This contains CA!"
FN = Dir
R = R + 1
Loop
End Sub

VBA edit cell in master template file

I have a button in a template (XLT) that saves the new workbook to a directory. The filename needs to auto-increment from the one used previously. I can't rely on a directory search as the documents may be moved/deleted over time.
Is it possible to auto-increment a cell in the template file, from code running in the new workbook?
As long as it is possible to save the template, you could store the value in a Name (these are most commonly used to store ranges, but can be used to store constants).
When you create the Name, just type a value instead of a range into the RefersTo area. Then you can access it like this:
Sub WhatsTheValue()
Dim intValue As Integer
intValue = Evaluate(ThisWorkbook.Names("NextValue").RefersTo)
ThisWorkbook.Names("NextValue").Value = intValue + 1
MsgBox intValue & vbNewLine & Evaluate(ThisWorkbook.Names("NextValue").RefersTo)
End Sub
The code will get the current value of the NextValue Name, assign it to the intValue variable and will immediately increment the Name.
You would, of course, have to save the template each time. This may cause problems if multiple people are accessing the template.

Populate a userform Combobox with a list of subdirectory names in a defined directory

I apologize if this question was answered previously on this board. My searches didn't turn up what I'm looking for. I am a VBA novice and would like to know if there is a way to populate a userform combobox with the names of all subdirectories contained within a predefined directory (I need the list to be updated every time the userform is launched). I've seen some code that does this on other websites but they were for earlier versions of Excel and I could not get them to work. I am using Excel 2007. I appreciate any help you may be able to provide.
Option Explicit
Private Sub UserForm_Initialize()
Dim name
For Each name In ListDirectory(Path:="C:\", AttrInclude:=vbDirectory, AttrExclude:=vbSystem Or vbHidden)
Me.ComboBox1.AddItem name
Next name
End Sub
Function ListDirectory(Path As String, AttrInclude As VbFileAttribute, Optional AttrExclude As VbFileAttribute = False) As Collection
Dim Filename As String
Dim Attribs As VbFileAttribute
Set ListDirectory = New Collection
' first call to Dir() initializes the list
Filename = Dir(Path, AttrInclude)
While Filename <> ""
Attribs = GetAttr(Path & Filename)
' to be added, a file must have the right set of attributes
If Attribs And AttrInclude And Not (Attribs And AttrExclude) Then
ListDirectory.Add Filename, Path & Filename
End If
' fetch next filename
Filename = Dir
Wend
End Function
A few notes, since you said you had little experience with VBA.
Always have Option Explicit in effect. No excuses.
Dir() is used in VB to list files.
Collections are a lot more convenient than arrays in VBA.
There are named parameters available in function calls (name:=value). You don't have to use them, but they help to make sense of long argument lists. Argument order is irrelevant if you use named parameters. You cannot mix named and unnamed parameters, though.
You can have optional arguments with default values.
Note that assigning to the function name (ListDirectory in this case) sets the result of a function. You can therefore use the function name directly as a variable inside that function.
Set AttrInclude to -1 if you want to return all types of files. Conveniently, -1 is the numerical value of True., i.e. ListDirectory("C:\", True).
Set AttrExclude to 0 if you want to exclude no files. Conveniently, 0 is the numerical value of False., i.e. ListDirectory("C:\", True, False), which also is the default.
All logical operators in VB 6.0 are bit-wise, hence you can check whether a file is a directory by using If Attribs And VbDirectory Then ...
You can combine multiple bit values with Or, e.g. vbSystem Or vbHidden.
Consequently, you can filter directories with a simple bit-wise logic check.
Use the Object Browser (hit F2) to inspect available Functions, Types and Constants, for example the constants in the VbFileAttribute enum.