Correct Syntax to add Hyperlinks to Excel Worksheet from an Array - arrays

I have an Excel macro which uses DIR in a lopp to retrieve all files from all folders and displays them on a worksheet. The bit of code which outputs to the worksheet on each iteration is:
rOut.Range("A1:B1").Offset(iFile).Value = Array(sName, sFile)
I would like to output the first cell as a hyperlink to the folder the file is located in (stored in variable sPath), and in the second cell I would like to output the filename, which is also a hyperlink to open the file.
I came up with this bit of code:
With rOut
With .Cells(1, 1)
.Offset(iFile).Hyperlinks.Add Anchor:=.Offset(iFile), Address:=sPath, TextToDisplay:=sName
End With
With .Cells(1, 2)
.Offset(iFile).Hyperlinks.Add Anchor:=.Offset(iFile), Address:=sName, TextToDisplay:=sFile
End With
End With
I know this is sloppy, and it is markedly slower than the above array syntax, but I just can't figure it out.
Suggestions?
Thanks.

Related

Can't copy a value from one worksheet over to an array in another worksheet

In the same workbook, I've got two worksheets: Model and Results.
My goal is to copy the value of a cell in Model (for e.g., F8) over to a cell in an array (c4 to I23) in Results called ResultsArray (see code below).
When I run my module, no error appears, but the code doesnt seem to work either (the value of F8 doesnt get copied over to the specified cell in ResultsArray).
Appreciate any help.
Tried running different variations of the code below
Sub CopyTest()
Dim ResultsArray As Variant
ResultsArray = Worksheets("Results").Range("C4:I23")
ResultsArray(1, 1) = Worksheets("Model").Range("F8").Value
End Sub
I'm using ResultsArray(1,1) because I am hoping to introduce a loop into the code to populate cells in the array based on the loop counter, e.g., ResultsArray(loopcounter,1)
So turns out I just needed to add "Set" in the 2nd line before "ResultsArray" when assigning the range from the worksheet "Model" to it:
Sub CopyTest()
Dim ResultsArray As Variant
Set ResultsArray = Worksheets("Results").Range("C4:I23")
ResultsArray(1, 1) = Worksheets("Model").Range("F8").Value
End Sub
I've tested this addition and it works

application defined or object defined error whey copying data into array

I am used to assigning ranges to arrays. However, for some reason right now I am constantly getting an application or object defined error (the first code line below). The second line below works fine. It is identical to the first line except I just copy the range showing all the variables exist.
I have checked in the watch window, arrActuals is Variant/Variant(). Adding .Value at the end of the first line did not solve the error either. Any ideas on why this is happening?
arrActuals = wkbOVHFile.Sheets(szAOPPage).Range(Cells(iStartCopy, IntActOVHCol), Cells(iEndCopy, IntActOVHCol))
wkbOVHFile.Sheets(szAOPPage).Range(Cells(iStartCopy, IntActOVHCol), Cells(iEndCopy, IntActOVHCol)).Copy
Cells without a qualifying worksheet object defaults to the active sheet, so your code fails when wkbOVHFile.Sheets(szAOPPage) is not the active sheet.
More robust like this:
Dim rng As Range
With wkbOVHFile.Sheets(szAOPPage)
Set rng = .Range(.Cells(iStartCopy, IntActOVHCol), _
.Cells(iEndCopy, IntActOVHCol))
End With
arrActuals = rng.Value
rng.Copy

VBA - file saves as tab-delimited instead of csv

I'm getting slightly confused by this issue. I have a macro that grabs data from one spreadsheet, re-formats it and saves in another spreadsheet. Everything works perfectly well but this piece of code seems to be working incorrectly:
Set NewBook = Workbooks.Add
With NewBook
.Title = "Pts"
.SaveAs Filename:="C:\Minestar_exports\" & Pts & "", FileFormat:=xlCSV,
CreateBackup:=False
.Close
End With
The trouble is that it save the file all right but seems to ignore the FileFormat:=xlCSV bit and saves it as TAB-delimeted instead. It's no biggie, when macro finishes running I just overwrite the temporary file using proper file format but still I couldn't figure out why this is happening. Any suggestions?
maybe, it has to do with your Windows regional settings.
Have a look to: http://excel.tips.net/T003232_Specifying_a_Delimiter_when_Saving_a_CSV_File_in_a_Macro.html
with regards, Christian Hahn.

Excel - VBA Question. Need to access data from all excel files in a directory without opening the files

So I have a "master" excel file that I need to populate with data from excel files in a directory. I just need to access each file and copy one line from the second sheet in each workbook and paste that into my master file without opening the excel files.
I'm not an expert at this but I can handle some intermediate macros. The most important thing I need is to be able to access each file one by one without opening them. I really need this so any help is appreciated! Thanks!
Edit...
So I've been trying to use the dir function to run through the directory with a loop, but I don't know how to move on from the first file. I saw this on a site, but for me the loop won't stop and it only accesses the first file in the directory.
Folder = "\\Drcs8570168\shasad\Test"
wbname = Dir(Folder & "\" & "*.xls")
Do While wbname <> ""
i = i + 1
ReDim Preserve wblist(1 To i)
wblist(i) = wbname
wbname = Dir(FolderName & "\" & "*.xls")
How does wbname move down the list of files?
You dont have to open the files (ADO may be an option, as is creating links with code, or using ExecuteExcel4Macro) but typically opening files with code is the most flexible and easiest approach.
Copy a range from a closed workbook (ADO)
ExecuteExcel4Macro
Links method
But why don't you want to open the files - is this really a hard constraint?
My code in Macro to loop through all sheets that are placed between two named sheets and copy their data to a consolidated file pulls all data from all sheets in each workbook in a folder together (by opening the files in the background).
It could easily be tailored to just row X of sheet 2 if you are happy with this process
I just want to point out: You don't strictly need VBA to get values from a closed workbook. You can use a formula such as:
='C:\MyPath\[MyBook.xls]Sheet1'!$A$3
You can implement this approach in VBA as well:
Dim rngDestinationCell As Range
Dim rngSourceCell As Range
Dim xlsPath As String
Dim xlsFilename As String
Dim sourceSheetName As String
Set rngDestinationCell = Cells(3,1) ' or Range("A3")
Set rngSourceCell = Cells(3,1)
xlsPath = "C:\MyPath"
xlsFilename = "MyBook.xls"
sourceSheetName = "Sheet1"
rngDestinationCell.Formula = "=" _
& "'" & xlsPath & "\[" & xlsFilename & "]" & sourceSheetName & "'!" _
& rngSourceCell.Address
The other answers present fine solutions as well, perhaps more elegant than this.
brettdj and paulsm4 answers are giving much information but I still wanted to add my 2 cents.
As iDevlop answered in this thread ( Copy data from another Workbook through VBA ), you can also use GetInfoFromClosedFile().
Some bits from my class-wrapper for Excel:
Dim wb As Excel.Workbook
Dim xlApp As Excel.Application
Set xlApp = New Excel.Application
xlApp.DisplayAlerts = False ''# prevents dialog boxes
xlApp.ScreenUpdating = False ''# prevents showing up
xlApp.EnableEvents = False ''# prevents all internal events even being fired
''# start your "reading from the files"-loop here
Set wb = xlApp.Workbooks.Add(sFilename) '' better than open, because it can read from files that are in use
''# read the cells you need...
''# [....]
wb.Close SaveChanges:=False ''# clean up workbook
''# end your "reading from the files"-loop here
''# after your're done with all files, properly clean up:
xlApp.Quit
Set xlApp = Nothing
Good luck!
At the start of your macro add
Application.ScreenUpdating = false
then at the end
Application.ScreenUpdating = True
and you won't see any files open as the macro performs its function.

Re-Initializing "ThisWorkbook.Path"

First, thanks to those of you who gave me the suggestion on using "ThisWorkbook.Path". It worked like a charm.
However, my code walks through seven (7) workbooks and when using "ThisWorkbook.Path" I can not re-initialize the "This.Workbook". Let me elaborate.
This is the workbook where the Macro resides:
Workbooks("Financial_Aggregator_v3.xls").Activate
This is the first workbook where the code adds a tab and does sub-totals. Basically, ThisWorkbook.Path works here:
Workbooks("Chapter_7-10_Mechanical.xls").Activate
After doing what I need done with "Mechanical" I have the following code snippet, which never turns out TRUE:
Workbooks("Financial_Aggregator_v3.xls").Activate
If FileThere(ThisWorkbook.Path & Application.PathSeparator & "Chapter_7-90_ECS_1_LLC.xls") Then
The code for the function, which works for the "Mechanical" sheet is:
Function FileThere(FileName As String) As Boolean
FileThere = (Dir(FileName) > "")
End Function
FYI, I tried to break all of the different Workbooks into different Sub(), but that didn't work. I also triple-checked the name of the workbooks.
Thanks in advance.
"ThisWorkbook" in Excel.VBA is sort of like "Me", in that it only applies to the workbook (.XLS) that actually holds the VBA code that is executing the "ThisWorkbook". What you need to do is to use Workbook objects to abstract the particular workbook that you want to test or manipulate.
Try something like this:
Public Sub TestWB()
Dim CurrWB As Workbook
'To get a workbook into our object variable:'
Set CurrWB = Workbooks("Chapter_7-10_Mechanical.xls")
'To Change the .Path:'
CurrWB.SaveAs NewFileName, AddToMru:=True
End Sub

Resources