VBA Hyperlinks.Add method prepending local folder to Address - vba

I've been lurking here for a while but this is my first post so let me know if I need to change something. Anyways, here goes:
I'm trying to create a macro that will add hyperlinks to cells in a worksheet. The problem is that after running the macro, I notice that the folder location of my spreadsheet has been prepended to the address that I specified. Is there something I need to do in order to indicate that this is a webpage and not a local file? Excerpt from the macro is below.
Dim IGQ As Range
Dim IGQno As String
Dim IGQno1 As String
For Each IGQ In Range("A2:A10") 'Actual range is much larger
IGQno = IGQ.Value
IGQno1 = Left(IGQ, 1)
Sheets("Cameron DCDA").Hyperlinks.Add Anchor:=IGQ, _
Address:="""http://xxxx""&IGQno1&""xxx""&IGQno&""xxxxx""" 'It's a company website so they probably don't want me to share it
Next
The result is that a hyperlink is created for each cell but it links to file:///C:\Users\John.Doe\Documents\"http://xxxx"&IGQno1&"xxx"&IGQno&"xxxxx"
I've tried using fewer quotation marks in the address since it seems like overkill but I get the compile error "Expected: end of statement"
Do you guys have any suggestions?

Too many quotes
Address:="http://xxxx " & IGQno1 & "xxx" & IGQno & "xxxxx"
Also - be sure to leave a space before your & otherwise it will be interpreted as a variable type suffix:
What are possible suffixes after variable name in VBA?

Related

store word content in variable

How do I copy the entire content (approx 2 pages) of a Word document in VBA and store in a variable?
I keep trying several things, none of which works:
Dim mainData As String
ThisDocument.Activate
ActiveDocument.WholeStory 'error on this line
mainData = Selection.Text
With 'record macro' I can simulate selecting a piece or the entire text, but I can't simulate storing that into a variable.
The above code throws
'This command is not available because no document is open',
but hadn't I first activated this (the current) document, and then selected it (ActiveDocument.WholeStory)?
Why doesn't this work?
Later edit: I managed to do the selection like this:
Dim sText As String
Application.Selection.ClearFormatting
Application.Selection.WholeStory
sText = Application.Selection.Text
MsgBox sText
but the problem is I can't store the entire text (2 pages) in a variable. Part of it is truncated. Would you know how to store word by word (I only need a word at a time anyway)?
Later edit. I applied strReverse on the text to find out the text is actually stored entirely in the variable, just not fully displayed in the message box.
Don't use ThisDocument in code, unless you specifically want to address the file in which the code is stored and running. ThisDocument is the "code name" of that file.
Instead, use ActiveDocument to mean the document currently active in the Word window.
An addition, if you want the Selection in the currently active document, there's no reason to activate it - it's already active.
So to get the entire document content in a string
Dim mainData As String
mainData = ActiveDocument.Content.Text
where Content returns the entire main body's text as a Range object.
Note: The MsgBox has an upper character limit. If you're working with long text strings and want to see what they hold the following has more (but not "infinite") capacity:
Debug.Print mainData
All you need is:
Dim mainData As String
mainData = ActiveDocument.Range.Text

Excel: Is that possible to erase names from other files using vba macro?

Note : I am a total newbie in VBA and Excel, but I know my stuff in programming. This is why I am posting this for a friend of mine.
He tried to remove all names he had in his workbook (1 workbook = 1 file, right ?), so he applied this macro he found on the web, without exactly knowing what it does :
Sub Del_Name()
Dim Loop As Integer
For Loop = ActiveWorkbook.Names.Count To 1 Step -1
If MsgBox("Erase: " & ActiveWorkbook.Names(Loop).Name & " - " & ActiveWorkbook.Names(Loop).Value & "?", vbQuestion + vbYesNo, "Confirm...") = vbYes Then
ActiveWorkbook.Names(Loop).Delete
End If
Next
End Sub
Then, in his file's name manager there are names referencing to some other files, such as :
http://randomServer:port/user/randomFolder/[file.xls]randomSheet'!$AD$6:$AF$6
\\random\folder[anotherFile.xls]anotherSheet'!#REF!
He doesn't know where this names come from.
So, his concern, and my question here : is that possible that the vba macro erased names within distant files ? Is that even possible ?
I have looked hours for information about that, some posts I have read suggest this could be possible, but I am still quite confused, any help would be much appreciated.
Thanks in advance
no. it is not possible that the vba macro erased names within remote files.
all it did was to delete a list of links that were stored in the excel file.
same as if you delete a favourite link in your web browser, you are not actually changing anything on the website that link pointed to.
it is possible to use a macro to modify remote files. you must have access to the file system that contains the file and you must have "write" permission to that file. then you could open the file and update it. or run an update SQL query. plus some other ways that i cannot think of right now.

Creating cross-references in VBA but losing formatting on save

I'm creating a word document from scratch as an OLE object via VBA, and have created cross-references in it. I am actually using LotusScript, but the principles of VBA should apply.
Once I have created the cross-reference, I format the entire table cell that contains it (Arial 8 Italic), but when the document is saved, the field updates its format. I know that I can set a property of the field manually by ticking the "Preserve formatting during updates " option in the Word front-end, but is there a VBA property for that?
NB, The cross-reference is to a heading, and the formatting I'm getting appears to be the same as that heading, which is not what I want.
Many thanks,
Phil
I found the solution :-)
This is LotusScript, but I'm sure VB users can work out what it means. Also, I call a function and 3 subroutines, which are all self-explanatory. rg is a Range, in which I've just created the cross-reference. Due to the nature off the application, I know that the field is the first one in the range. The final line is the important one.
Set rg = getTableCell(subTable, 2, 1).Range
Dim fld As Variant
Set fld = rg.Fields(1)
Call SetItalicsOnOff(rg, True)
Call SetFontFace(rg, "Arial")
Call SetFontSize(rg, 8)
fld.Code.Text = fld.Code.Text & " \* MERGEFORMAT"

Inserting a formula using Excel VBA

I am needing to insert a formula in using vba coding.
at the moment the line of code is
=IF(
AND(
Compliance="No",
OR(
Delivery <> "",
C31 <> ""
)
),
"Please Delete Compliance Data",
IF(
AND(
E11="",
E13="",
E23="",
E25="",
E26="",
E28="",
E30="",
E31=""),
VLOOKUP(C15,'Extrapolated RV Calculator'!B:S,18,0),
"Please complete form / SC request"
)
)"
It seems to error out on the text portions inside the code.
Any help would be appreciated.
Here are four ways to use quotation marks inside strings in VBA:
Replace "" with Chr$(34). 34 is the ASCII code for quotation marks
Use String(2,Chr$(34)) to make double quotes
Use two double quotation marks for every one (per Tim's comment)
Replace two double quotation marks with a different method, like ISBLANK for worksheet functions.
None of these is better. I usually use two double quotation marks to escape them. But sometimes I get so many quotation marks together that it's hard to read and maintain, so I'll use a different method. Here's an example:
Dim aFormula(1 To 5) As String
aFormula(1) = "=IF(AND(Compliance=""No"",OR(Delivery<>" & String(2, Chr$(34))
aFormula(2) = ",C31<>" & String(2, Chr$(34)) & ") ),"
aFormula(3) = Chr$(34) & "Please Delete Compliance Data" & Chr$(34)
aFormula(4) = ",IF(AND(ISBLANK(E11),ISBLANK(E13),ISBLANK(E23),ISBLANK(E25),ISBLANK(E26),ISBLANK(E28),ISBLANK(E30),ISBLANK(E31)),"
aFormula(5) = "VLOOKUP(C15,'Extrapolated RV Calculator'!B:S,18,0),""Please complete form / SC request""))"
Sheet1.Range("R13").Formula = Join(aFormula, vbNullString)
To empower you for the future I strongly recommend you do the following when you want to use functionality in Excel in your VBA code that you are not acquainted with yet.
Go to the developer menu and press the record macro button.
Now fill in a formula in a cell, Clear a cells content by pressing delete and clearing a cells content by going into the cell and deleting all the characters and press enter.
Now stop the macro. And go to the VBA window. See how the code is structured to accomplish these things.
Apply this also whenever you want to do other things to get a good idea of what you can use to get the results you want without having to browse around on the internet for ages!
Also watch the local variables in the locals window or Debug.Print the string you try to build to see hwat it looks so far

reverse engineer vba code excel

I am not a VBA programmer. However, I have the 'unpleasant' task of re-implementing someones VBA code in another language. The VBA code consists of 75 modules which use one massive 'calculation sheet' to store all 'global variables'. So instead of using descriptive variable names, it often uses:
= Worksheets("bla").Cells(100, 75).Value
or
Worksheets("bla").Cells(100, 75).Value =
To make things worse, the 'calculation sheet' also contains some formulas.
Are there any (free) tools which allow you to reverse engineer such code (e.g. create Nassi–Shneiderman diagram, flowcharts)? Thanks.
I think #JulianKnight 's suggestion should work
Building on this, you could:
Copy all the code to a text editor capable of RegEx search/replace (Eg. Notepad++).
Then use the RegEx search/Replace with a search query like:
Worksheets\(\"Bla\"\).Cells\((\d*), (\d*)\).Value
And replace with:
Var_\1_\2
This will convert all the sheet stored values to variable names with row column indices.
Example:
Worksheets("bla").Cells(100, 75).Value To Var_100_75
These variables still need to be initialized.
This may be done by writing a VBA code which simply reads every (relevant) cell in the "Bla" worksheet and writes it out to a text file as a variable initialization code.
Example:
Dim FSO As FileSystemObject
Dim FSOFile As TextStream
Dim FilePath As String
Dim col, row As Integer
FilePath = "c:\WriteTest.txt" ' create a test.txt file or change this
Set FSO = New FileSystemObject
' opens file in write mode
Set FSOFile = FSO.OpenTextFile(FilePath, 2, True)
'loop round adding lines
For col = 1 To Whatever_is_the_column_limit
For row = 1 To Whatever_is_the_row_limit
' Construct the output line
FSOFile.WriteLine ("Var_" & Str(row) & "_" & Str(col) & _
" = " & Str(Worksheets("Bla").Cells(row, col).Value))
Next row
Next col
FSOFile.Close
Obviously you need to correct the output line syntax and variable name structure for whatever other language you need to use.
P.S. If you are not familiar with RegEx (Regular Expressions), you will find a plethora of articles on the web explaining it.