Filename in variable used for formulas and copying - vba

I am trying to use a wildcard filename as a variable so I can use it to copy and do some formulas. And then I want to flatten all the formulas.
It looks like this:
This first part works (first thing opens wildcard file from a cell formula and second assigns only filename without path to variable Prod - hovering over variable prod gives exactly what it should)
Dim wbProd As Workbook
Windows("SB.xlsm").Activate
Set wbProd = Workbooks.Open(FileNAME:=Sheets("refs").Range("B48").Value)
Dim Prod As String
Windows("SB.xlsm").Activate
Prod = Worksheets("refs").Range("B49").Value
Windows("Weekly.xlsx").Activate
With Workbooks(" & Prod & ").Sheets("Report 1")
.Range("A2:BG10", .Range("A2:BG10").End(xlDown)).Copy Workbooks("WeeklyData X.xlsx").ActiveSheet.Range("A2")
End With
Windows("WeeklyData X.xlsx").Activate
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Report 1")
ws.UsedRange.Value = ws.UsedRange.Value
I am getting an error with this first part of copying: With Workbooks(" & Prod & ").Sheets("Report 1"). When I use this copying method without using filename in a variable it works and also when I use variable filename to do Vlookups it works. I dont know what would be the reason not to work here.
Also if you have better way to flatten all the formulas and preseve formats (coz of dates) it would be great.
Thanks,

A quick fix would be to create a Workbook variable (Dim myWB as Workbook),
Then do Set myWB = Workbooks(Prod). Then just do With myWB.Sheets("Sheet1").
The issue is that Excel needs quotes in the sheet name, and so your book is literally being understood as being titled & Prod &. So, to keep your current idea, you need to just add an additional quote to each quote: With Workbooks("" & Prod & "").Sheets("Report 1").
Personally I recommend setting up a workbook variable, but either works!
Edit:
#drLecter - Very welcome! You'll also run into the "double quotes" issue when trying to set up formulas that have quotes in them. IE The worksheet formula =Vlookup("myText",A1:D1,2,False) would, in VBA, become
Cells(1,1).Formula = "=Vlookup(""myText"",A1:D1,2,False)".
As you can see, if I didn't use double quotes, VBA would stop reading the formula at
Cells(1,1).Formula = "=Vlookup(

Use dir() !
Microsoft Documentation link - dir() function
-Returns a string representing the name of a file, directory, or folder that matches a specified pattern or file attribute, or the volume label of a drive.
just adapt something like this::
Sub LoopThroughFiles()
Dim MyObj As Object, MySource As Object, file As Variant
file = Dir("c:\testfolder\")
While (file <> "")
If InStr(file, "test") > 0 Then
MsgBox "found " & file
Exit Sub
End If
file = Dir
Wend
End Sub

Related

Calling a global/public variable in moduleB whose value was defined in moduleA

I wrote 4 macros to do things, but it requires 2 inputs from the user to make sure the right file is being used because some of the macros switch back and between 2 workbooks. I only had access to a few of the files, but I knew that eventually I would have access to the rest of the 35 files. If I didn't have the inputs, I would have to manually change the filename in the macro code, but I don't want to do that, so I used inputs. But now that I have all the files in the right format, I am trying to a separate macro that has a list of the other files in a separate workbook, and then opens those files and does the macros, but it would require the inputs a lot. So now, I'm trying to remove that need for the inputs. But I'm unfamiliar with public variables and somewhat familiar with the calling of other subroutines.
My setup is this:
option explicit
public current as string
Sub master_macro
dim i as integer
dim path as string
dim wb as workbook
dim sht as worksheet
set wb = workbooks("name.xlsx")
set sht = wb.worksheets(1)
path = "C:\xxx\"
wb.activate
for i = 1 to 20
currun = sht.cells(i,1).value 'this takes the value from the separate workbooks that has the file names
full_currun = currun & ".xlsx"
with workbooks.open(path & full_currun)
.activate
call blanks
call lookup
call transfer
call combine
.save
.close
end with
next i
The last 2 macros switch between 2 sheets. So in those macros, the currun is generated the an inputbox, albeit a different name.
nam = inputbox("yadda yadda")
set wb = workbooks(nam & ".xlsx")
I'm trying to get the currun vaue that is defined in the master macro to macro3 and macro4.
You see the part where it says Sub master_macro? What you are doing there is declaring a procedure, which is a basically a general term to describe "a block of self-contained code that does something when it is run." Procedure declarations have three major components:
type - this is what you are doing with Sub; you are saying it is a subroutine, which is distinct from a function Function in that it does not return a value
name - this is the identifier you use to refer to the procedure elsewhere in your code. it is supposed to be descriptive since that enhances the readability. "master_macro" is not bad, but as a general rule you don't want to use underscores when naming procedures in VBA.
parameters - this is where you define the set of variable values that can be passed to the procedure when it is run. each parameter is separated by a comma and declared using the syntax [pass type] + [variable name] + [variable type]. [pass type] is either ByRef or ByVal; the basic distinction is that ByRef sends a direct reference to the variable, while ByVal sends a copy of the value.
The last part is what you are missing to solve this problem. Both macro3 and macro4 are declared (in module B) like master_macro is here. If they need to know what the currun value is then simply add (ByVal currun As String) to their declarations. When they are called from another procedure, as they are in master macro, they will expect to receive a string. Change the two lines in master macro from:
Call macro3
Call macro4
to
Call macro3(full_currun)
Call macro4(full_currun)
and macro3 and macro4 will have the value of full_currun stored in their own internal variable currun for use as they need.
Thanks guys. managed to get it to work. Here's the finished work below
sub master()
dim i as integer
dim path, currun, fullcurrun as string
dim wb as workbook
dim sht as worksheet
set wb = workbooks("Name.xlsx")
set sht = wh.worksheets(1)
path = "C:\xxx\"
wb.activate
for i = 1 to ?
currun = sht.cells(i,1).value
fullcurrun = currun & ".xlsx"
workbooks.open(path & fullcurrun)
call blank(currun)
call lookup(currun)
call transfer(currun)
activeworkbook.save
activeworkbook.close
call transfer(currun)
next i
end sub
public sub blank/lookup/transfer(byval currun as string)
blah blah blah
end sub

Turn String Into Hyperlink with Preset Name in Excel with VBA

I have a userform where I will be wanting people to enter a link e.g. bbc.com & I want the program to automatically turn this string into a hyperlink (blue underlined) called "website".
Here's what I have so far.
PublicProperty Get Link() as string
Link=Me.Linkbvalue
.cells(blankrow,1).value=me.link
EDIT: Note, words generic to protect company. Actually the problem is not it starting with local server. In the following the file is in the folder but not the subfolder
Entry="\directory\folders_directory\folder\file"
when running code,
address becomes
\directory/folders_directory\folder\sub_folder"\directory\folders_directory\folder\file"
The following might help.
It will convert column A values to hyperlinks.
Sub GetHyperlink()
For Each xCell In Range("A:A")
If xCell.Value <> "" Then
ActiveSheet.Hyperlinks.Add Anchor:=xCell, Address:="http://www." & Replace(xCell.Formula, "www.", ""), TextToDisplay:="Website"
End If
Next xCell
End Sub
This is something that should work, if you read the the entry variable from the Form:
Sub TestMe()
Dim entry As String
entry = "bbc.com"
Dim httpPrefix As String
httpPrefix = "https://"
If Left(entry, Len(httpPrefix)) <> httpPrefix Then
entry = httpPrefix & entry
End If
With Worksheets(1)
.Hyperlinks.Add Anchor:=.Cells(1, 1), _
Address:=entry, _
TextToDisplay:="website"
End With
End Sub
Some business logic is needed to decide whether to write https:// or http:// or anything similar. You may consider using Trim() to remove possible empty cells from the left and the right.

Variable Reference directory in code

I would like to have a user be able to type in the directory of another spreadsheet into a cell, then use that in my macro. In code like:
Range("X1") = Directory
Range("A1").FormulaR1C1 = 'Directory'!RC)
When Range("X1") is where the user types in the Directory of the desired reference file
It looks like you're trying to reference a separate sheet in the same workbook. If that's the case then you can try:
Range("A1").FormulaR1C1 = "'" & Range("X1").Value & "'!RC..."
However, this works very similarly to the =INDIRECT() worksheet function which may be a better solution especially if this is a static formula. To use this, in cell A1 enter:
=INDIRECT("'" & X1 & "'!RC...")
You can read more about the INDIRECT function here.
You can make user choose a file from a dialog box by
range("X1").value = application.getopenfilename
dim MyDir as string
MyDir = range("X1").value ' and use MyDir variable in code from now on
Hope that was what you were looking for, cheers

Formatting errors when SavingAs text files from worksheets

This is a question related to: Create text Files from every row in an Excel spreadsheet I have implemented ExactaBox great solution with the following code:
Sub SaveRowsAsENW()
Dim wb As Excel.Workbook, wbNew As Excel.Workbook
Dim wsSource As Excel.Worksheet, wsTemp As Excel.Worksheet
Dim r As Long, c As Long
Set wsSource = ThisWorkbook.Worksheets("worksheet1")
Application.DisplayAlerts = False 'will overwrite existing files without asking
r = 1
Do Until Len(Trim(wsSource.Cells(r, 1).Value)) = 0
ThisWorkbook.Worksheets.Add ThisWorkbook.Worksheets(1)
Set wsTemp = ThisWorkbook.Worksheets(1)
For c = 2 To 7
wsTemp.Cells((c - 1) * 2 - 1, 1).Value = wsSource.Cells(r, c).Value
Next c
wsTemp.Move
Set wbNew = ActiveWorkbook
Set wsTemp = wbNew.Worksheets(1)
'wbNew.SaveAs wsSource.Cells(r, 1).Value & ".csv", xlCSV 'old way
wbNew.SaveAs "textfile" & r & ".enw", xlCSV 'new way
'you can try other file formats listed at http://msdn.microsoft.com/en-us/library/office/aa194915(v=office.10).aspx
wbNew.Close
ThisWorkbook.Activate
r = r + 1
Loop
Application.DisplayAlerts = True
End Sub
Option Explicit
I have used this solution and it works fine. The only trouble I have is that some of the lines get quotation marks in the output file.
This is an example of output text file (line 2-3 demonstrates the error):
0 Journal Article 'No quotation marks
"%A Wofford, J.C."
"%A Goodwin, Vicki L."
%T A field study of a cognitive approach to understanding transformational and .. 'No quotation marks
This formatting seem to be added when it is being saved (it is not part of the cell formatting). Do any of you have any ideas of why this happens? /How can I adapt my code to fix it?
True. .csv stands for comma-separated values, where a field contains a comma it has to be 'escaped' (here with quotes) or would be split into different fields before/after each comma. Answer provided before does however offer alternatives - of which Tab delimited is the most logical.
This is likely past the point of being helpful to you, but after hitting this problem recently myself I thought I'd share my eventual solution. The formatting you're seeing is actually the result of a MS saving issue, which appends quotes to lines that have certain characters.
In my case I wrote out the file as usual and then called a sub that cleans the file of the problem extra characters. First I replaced any output that would need quotes with something like an asterisk or any other character that would never occur in my file. Then I saved the file as normal and called the below code, used to replace any character with another, twice. Once to remove the quotes Excel created, the second time to replace my dummy character with quotes. The code executes fairly quickly and renames the file so you can be certain the result is finished processing. Hopefully useful to others searching.
It's still clunkier than I'd like since you save a file and then edit it, but it worked well enough to become my final solution in the end.
Sub ReplaceStringInTextFile(FileNameAndLoc As String, OutFile As String, SearchForWords As String, SubstituteWords As String)
'This macro searches a file, replacing one string with another, saving it, and renaming it.
Dim objFSO As Object
Dim objReadFile As Object
Dim objWriteFile As Object
'Set Objects
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objReadFile = objFSO.opentextfile(FileNameAndLoc, 1, False)
'Read file contents
Contents = objReadFile.readall
'Close read file
objReadFile.Close
'Copy contents without double quotes
NewContents = Replace(Contents, SearchForWords, SubstituteWords)
'Write output
Set objWriteFile = objFSO.opentextfile(FileNameAndLoc, 2, False)
objWriteFile.write NewContents
objWriteFile.Close
'Rename file
Name FileNameAndLoc As OutFile
End Sub

Is it possible in Excel VBA to change the source code of Module in another Module

I have an Excel .xlam file that adds a button in the ribbon to do the following:
Scan the ActiveSheet for some pre-set parameters
Take my source text (a string value, hard coded directly in a VBA Module) and replace designated areas with the parameters retrieved from step 1
Generate a file containing the calculated text
I save the source text this way because it can be password protected and I don't need to drag another file around everywhere that the .xlam file goes. The source text is saved in a separate module called "Source" that looks something like this (Thanks VBA for not having Heredocs):
'Source Module
Public Function GetSource() As String
Dim s As String
s = ""
s = s & "This is the first line of my source text" & vbCrLf
s = s & "This is a parameter {par1}" & vbCrLf
s = s & "This is another line" & vbCrLf
GetSource = s
End Function
The function works fine. My problem is if I want to update the source text, I now have to manually do that in the .xlam file. What I would like to do is build something like a Sub ImportSource() in another module that will parse some file, rebuild the "Source" Module programatically, then replace that Module with my calculated source code. What I don't know is if/how to replace the source code of a module with some value in a string variable.
It's like metaprogramming at its very worst and philosophically I'm against doing this down to my very core. Practically, however, I would like to know if and how to do it.
I realize now that what you really want to do is store some values in your document in a way that is accessible to your VBA, but that is not readable to a user of the spreadsheet. Following Charles Williams's suggestion to store the value in a named range in a worksheet, and addressing your concern that you don't want the user to have access to the values, you would have to encrypt the string...
The "proper way" to do this is described in this article - but it's quite a bit of work.
A much shorter routine is found here. It just uses simple XOR encryption with a hard coded key - but it should be enough for "most purposes". The key would be "hidden" in your macro, and therefore not accessible to prying eyes (well, not easily).
Now you can use this function, let's call it encrypt(string), to convert your string to a value in the spreadsheet:
range("mySecretCell").value = encrypt("The lazy dog jumped over the fox")
and when you need to use it, you use
Public Function GetSource()
GetSource = decrypt(Range("mySecretCell").value)
End Function
If you use the XOR version (second link), encrypt and decrypt would be the same function...
Does that meet your needs better?
As #brettdj already pointed out with his link to cpearson.com/excel/vbe.aspx , you can programmatically change to code of a VBA module using the VBA Extensibility library! To use it, select the library in the VBA editor Tools->References. Note that you need to also change the options in your Trust center and select: Excel Options->Trust Center->Trust Center Settings->Macro Settings->Trust access to the VBA project object model
Then something like the following code should do the job:
Private mCodeMod As VBIDE.CodeModule
Sub UpdateModule()
Const cStrModuleName As String = "Source"
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Set VBProj = Workbooks("___YourWorkbook__").VBProject
'Delete the module
VBProj.VBComponents.Remove VBProj.VBComponents(cStrModuleName)
'Add module
Set VBComp = VBProj.VBComponents.Add(vbext_ct_StdModule)
VBComp.Name = cStrModuleName
Set mCodeMod = VBComp.CodeModule
'Add procedure header and start
InsertLine "Public Function GetSource() As String"
InsertLine "Dim s As String", 1
InsertLine ""
'Add text
InsertText ThisWorkbook.Worksheets("Sourcetext") _
.Range("___YourRange___")
'Finalize procedure
InsertLine "GetSource = s", 1
InsertLine "End Function"
End Sub
Private Sub InsertLine(strLine As String, _
Optional IndentationLevel As Integer = 0)
mCodeMod.InsertLines _
mCodeMod.CountOfLines + 1, _
Space(IndentationLevel * 4) & strLine
End Sub
Private Sub InsertText(rngSource As Range)
Dim rng As Range
Dim strCell As String, strText As String
Dim i As Integer
Const cLineLength = 60
For Each rng In rngSource.Cells
strCell = rng.Value
For i = 0 To Len(strCell) \ cLineLength
strText = Mid(strCell, i * cLineLength, cLineLength)
strText = Replace(strText, """", """""")
InsertLine "s = s & """ & strText & """", 1
Next i
Next rng
End Sub
You can "export" and "import" .bas files programmatically. To do what you are asking, that would have to be the approach. I don't believe it's possible to modify the code in memory. See this article