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
Related
I have a bunch of cells that I won't to get the html representation of.
From the post Export specific range into an HTML I use the answer to save an html representation to a file, but is there a way to output it to a variable instead?
My final use of this html does not except classes in the html so I need to search and replace text within the output before I can use it.
Is there a way to change the output of the following code from a file to a variable?
Sub Export()
Dim rng As Range
file1 = ThisWorkbook.Path & "\" & "test.html"
Set rng = Sheets("Tabelle1").Range("A1:C10")
ActiveWorkbook.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=file1, _
Sheet:=rng.Worksheet.Name, _
Source:=rng.Address, _
HtmlType:=xlHtmlStatic).Publish
End Sub
The content of your sheet's range is already stored in the rng object variable, hence, all of its information is there, it will prevail as long as you like in the code, why would you add another variable to it?
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
I am trying to write a VLOOKUP in a cell as a string, with VBA. This means that I do not want the result to appear in the cell as a value, but I want the whole VLOOKUP expression instead (For this example : "VLOOKUP(C6,'[path_to_file.xlsm]OTD Table!$B:$F,4,0)"). The challenge is that the range argument of the VLOOKUP is a concatenation of a path (path_to_file.xlsm) that the user selects with a GetOpenFilename, and a string that specifies the tab in which the lookup table is located ("OTD Table!$B:$F,4,0").
The issue I am getting is very interesting :
When I print my expression in a Msgbox, the expression appears correctly. However, when I write it in a cell, the path mysteriously appears incorrectly.
Sub macro()
dim data_file_new as String
data_file_new = CStr(Application.GetOpenFilename(FileFilter:="Excel Workbooks (*.xls*),*.xls*", Title:="Select new data file")) ' The user selects the file
str_ = "=VLOOKUP(C6," & "'[" & data_file_new & "]OTD Table!$B:$F,4,0)" ' This will display the expression correctly
cells(1,10)="=VLOOKUP(C6," & "'[" & data_file_new & "]OTD Table!$B:$F,4,0)"' This will not display the same thing as in the messagebox above
end Sub
I hope one of you guys can make sens of this !
Because you're dropping a formula into a cell that you want to display as straight text, you have to be explicit with Excel and tag the text string to prevent interpreting it as a formula. The simplest way to do this is pre-pend the string with a single-quote "'".
Sub macro()
Dim data_file_new, str_ As String
str_ = "'=VLOOKUP(C6,'["
data_file_new = CStr(Application.GetOpenFilename(FileFilter:="Excel Workbooks (*.xls*),*.xls*", Title:="Select new data file")) ' The user selects the file
str_ = str_ & data_file_new & "]OTD Table!$B:$F,4,0)" ' This will display the expression correctly
ActiveSheet.Cells(1, 10).Value = str_
End Sub
Yeah either you'll need to set the string to add a single quote, or you'll need to change the numberformat of the cell to text (Cells(1,10).NumberFormat = "#")
Either of those should work.
Q1: The routine below does not work.
Sub test()
TXT = Sheets("INDEX").Cells(2, 1).Value
AKO = Sheets("TOBESEEN").Cells(1, 1).Address
Sheets("INDEX").Hyperlinks.Add Anchor:=Sheets("INDEX").Cells(1, 2), Address:="",
SubAddress:=AKO, TextToDisplay:=TXT
End Sub
Q2. Is there a place where I can see ALL the properties of the cell? When I type the "dot" after cells, VBA DOES NOT GIVE any options.
Like
sheet1.cell(1,2).VALUE
sheet1.cell(1,2).ADDRESS
sheet1.cell(1,2).?
I suspect my problem is related to the definition of AKO, but I am not sure what the correct property is (if not ADDRESS)
Thank you
Q1: Try to use this code:
Sub test()
TXT = CStr(Sheets("INDEX").Cells(2, 1).Value)
AKO = Sheets("TOBESEEN").Cells(1, 1).Address
Sheets("INDEX").Hyperlinks.Add _
Anchor:=Sheets("INDEX").Cells(1, 2), _
Address:="", _
SubAddress:=Sheets("TOBESEEN").Name & "!" & AKO, _
TextToDisplay:=TXT
End Sub
Q2: you can use F2 help. There you can see a list of properties and methods of any object.
When you create a hyperlink in a document, you need to give the "full" address of the cell you are linking to (sheet name and cell address), not just the .Address (which is the absolute address on a given sheet, but doesn't include the sheet information). To get the full address (including the sheet) of a cell, you need to add an additional parameter to the Address():
.Address(External:=True)
which will give you the full address, including workbook and sheet name. Unfortunately, if you create this link and then change the name of the workbook (maybe because you had not saved it up to this point), the link will break.
It is therefore (slightly) more robust to create a link that doesn't include the workbook name. The following routine does this for you. Note that is usually a good idea to split your code into small self-contained functions that do one thing particularly well - you can re-use your code more easily, and the main program becomes easier to read and maintain. I suggest therefore that you create the following function:
Sub addLink(target As Range, location As Range, text As String)
' create a hyperlink with text "text"
' in the cell "location"
' pointing to the range "target"
Dim linkAddress As String
linkAddress = target.Address(external:=True) ' this is the "full" address
'remove everything between brackets - this is the workbook name:
bLeft = InStr(1, linkAddress, "[") ' location of left bracket
bRight = InStr(bLeft, linkAddress, "]") ' location of right bracket
linkAddress = Left(linkAddress, bLeft - 1) + Mid(linkAddress, bRight + 1)
' now create the link:
location.Parent.Hyperlinks.Add _
anchor:=location, _
Address:="", _
SubAddress:=linkAddress, _
TextToDisplay:=text
End Sub
You can call this from your code above as follows:
Dim TXT As String, AKO As Range, LOC As Range ' define types when possible
TXT = Sheets("INDEX").Cells(2, 1).Value ' I called this text
Set AKO = Sheets("TOBESEEN").Cells(1, 1) ' I called this target (note - need Set)
Set LOC = Sheets("INDEX").Cells(1, 2) ' I called this location
addLink AKO, LOC, TXT
As for the second part of your question - "I can't see the properties of Cells()". Yes, that is annoying. It happens that Cells() is a lot like a Range object; you can see in the above that I was able to do Set AKO = Sheets("TOBESEEN").Cells(1,1) which demonstrates this. You can declare a variable as being of the type Range, and then tooltips will work for you:
Dim r As Range
r.
and as you type r. you will see a list of the properties of Range (which are also the properties of Cells):
It is annoying that Cells doesn't just do this by itself. It is annoying that Address() doesn't have an option to include the sheet name and not the workbook name. Excel is full of annoyances. In fact, there is even a book called "Excel Annoyances". And more could be written, I'm sure…
At least there are usually VBA tricks to work around these things and get the job done.
Say you have two Workbooks one called “MyWorkbook” and the other called “PatchMyWorkbook”. Both workbooks are open at the save time. The “PatchMyWorkbook” has a macro to add a button and assign an existing macro of “MyWorkbook” to “MyWorkbook” The existing macro in “MyWorkbook” is called “PrintPage”
Windows(“MyWorkbook”).Activate
Sheets("Sheet1").Activate
ActiveSheet.Buttons.Add(665.25, 43.5, 89.25, 45).Select
Selection.OnAction = "PrintPage"
This does not cause an error while the “PatchMyWorkbook” code executes but the newly added buttons macro will point to “’PatchMyWorkbook’!PrintPage” rather than just “PrintPage” of the “MyWorkbook”
Question: How can you set the “OnAction” for a macro button across workbooks so that the macro will point to the current workbook not the workbook from where the macro has been created?
In my opinion .OnAction property should be set in this way:
Selection.OnAction = myWbk.Name & "!PrintPage"
By the way, the idea from your comment (changed a bit below):
Selection.OnAction = "'" & myWbk.Name & "'" & "!" & "PrintPage"
is working for me as well (Excel 2010).
You need to include the name of the sheet or module where PrintPage is defined.
Dim methodName As String
With <module or sheet where 'PrintPage' is defined>
methodName = "'" & MyWbk.Name & "'!" & .CodeName & ".PrintPage"
End With
MyWbk.Sheets("Sheet1").Shapes("ButtonName").OnAction = methodName
The single quotes surrounding MyWbk.Name are important.
A quick and easy way is :
workbooks("name_of_workbook").Worksheets("name_of_sheet").Shapes("name_of_button").OnAction = "name_of_your_macro"
Just substitute the different "name_of_..." by your names.
Does it work?