How to display desired text in hyperlink using VBA code - vba

I have displayed my hyperlink in the column E as shown
\\maroon\cgm images\mech.pdf
But I want to display only mech.pdf in the cell how to modify my code.
my code used for displaying above hyperlink is shown below:
str = "\\maroon\CGM Images\" & pn & ".pdf"
ActiveSheet.Hyperlinks.Add Range("e" & i), str
In this I want to show only pn & str.

You need to specify TextToDisplay
ActiveSheet.Hyperlinks.Add Anchor:=Range("e" & i), Address:=Str, TextToDisplay:=pn & ".pdf"
Sometimes the Excel VBA reference is indeed helpful to find out on your own how functions and methods work: Hyperlinks.Add Method (Excel)

If you have
\maroon\cgm images\mech.pdf
in a cell and you wanna get only the name of the pdf with ".pdf" you can do the next code:
Dim spliter() as String
Dim str_pdf as String
str = \maroon\cgm images\mech.pdf ' Cells(a,b).value
spliter = Split(str, " ") 'To do the first split (You can delete ', " "' )
spliter = Split(spliter(1), "\")
'Now spliter(1) == mech.pdf so...
str_pdf = spliter(1) ' spliter(0) == images , spliter(1) == mech.pdf

Related

Passing values from Excel to Word with VBA

For Each cell In rng
workSheetName = Format(SaturdayIsComing(), "mm-dd-yyyy") & " " & cell.Value
If WorksheetExists(workSheetName) Then
Dim localRange, localCell As Range
Set localRange = Worksheets(workSheetName).Range("D8:D19")
Dim contents As Variant
contents = ""
Dim firstLine As Boolean
firstLine = True
For Each localCell In localRange
If Len(localCell.Value) > 0 Then
If firstLine Then
contents = contents & localCell.Value & Chr(11)
Else
contents = contents & Chr(9) & Chr(9) & Chr(9) & localCell.Value & Chr(11)
End If
Else
contents = fixString(contents)
End If
If Len(contents) > 0 Then
firstLine = False
End If
Next localCell
For Each cc In wDoc.SelectContentControlsByTag(cell.Value & "Notes")
If Len(contents) > 0 Then
cc.Range.Text = fixString(contents)
Else
cc.Range.Text = "No Issues Found"
End If
Next
Else
errorCodesString = errorCodesString & cell.Value & ":"
End If
Next cell
Output to Word
Forgot to terminate the meeting
This is a test message\'s
If my cell contains a ' then I get an error saying
One of the values passwed to this method or property is incorrect
I know a ' is a comment in VBA. How do I go around this while preserving the notes that someone had added to the Excel cell?
You need to write a piece of code to search for quotes, either the single (') or double (") variety and either add a backslash before them OR double the character so '' in place of ' and "" in place of " and run this on contents before assigning it to cc.Range.Text.
This routine can also check for other instances of incorrect strings and fix them.
Something like this would do:
Function fixString(ByVal strIn As Variant) As String
Dim i As Integer
Const strIllegals = "\'"""
For i = 1 To Len(strIllegals)
strIn = Replace(strIn, Mid$(strIllegals, i, 1), "\" & Mid$(strIllegals, i, 1))
Next i
fixString = strIn
End Function
Try changing cell.Value to Replace(cell.Value, "'", "")
Or is it contents that has the apostrophe in it? A bit confusing.
Try changing contents to Replace(contents , "'", "")

How to add quotes for every string value in a csv file via Excel VBA?

I have a csv file, and I need a VBA function that adds quotes to every string value in the file, so that something like
vertical,device_name,value
mobile,Apple iPad,0
mobile,HTC,3
looks like
"vertical","device_name","value"
"mobile","Apple iPad",0
"mobile","HTC",3
What I have found until now is a macro,
Sub QuotesAroundText()
Dim c As Range
For Each c In Selection
If Not IsNumeric(c.Value) Then
c.Value = """" & c.Value & """"
End If
Next c
End Sub
that does almost exactly what I need - it add the quotes, but not to string, but to excel cells. That means, that this macro does work correctly in a xlsx file, but not in a csv file.
So I need a vba code that adds quotes not to cells, but to string, that are between commas.
By emulating a string builder I was able to process a CSV file with 59,507 Rows x 9 Columns in just over 3 seconds. This process is much faster that standard concatenation.
This function was modified from my answer to Turn Excel range into VBA string
Test
Sub TestProcessCSVFile()
Dim s As String
Dim Start: Start = Timer
ProcessCSVFile "C:\Users\Owner\Downloads\SampleCSVFile_53000kb.csv", "C:\Users\Owner\Downloads\_temp.csv"
Debug.Print "Execution Time: "; Timer - Start; "Second(s)"
End Sub
Code
Sub ProcessCSVFile(OldFile As String, NewFile As String)
Dim Data As String, text As String
Dim vCell
Dim length As Long
Open OldFile For Binary As #1
Data = Space$(LOF(1))
Get #1, , Data
Close #1
text = Space(Len(Data) * 1.5)
For Each vCell In Split(Replace(Data, vbCrLf, "," & vbCrLf & ","), ",")
If Len(vCell) + length + 5 > Len(text) Then text = text & Space(Len(Data) * 0.1)
If vCell = vbCrLf Then
Mid(text, length, 1) = vbCrLf
ElseIf IsNumeric(vCell) Then
Mid(text, length + 1, Len(vCell) + 1) = vCell & ","
length = length + Len(vCell) + 1
Else
Mid(text, length + 1, Len(vCell) + 3) = Chr(34) & vCell & Chr(34) & ","
length = length + Len(vCell) + 3
End If
Next
Open NewFile For Output As #1
Print #1, Left(text, length - 1)
Close #1
End Sub
Results
Read the text file in using line input, then taylor the following process to your needs:
Sub y()
a = "a,b,c,d"
'Split into 1d Array
b = Split(a, ",", , vbTextCompare)
'for each element in array add the quotes
For c = 0 To UBound(b)
b(c) = """" & b(c) & """"
Next c
'join the product up
d = Join(b, ",")
'Print her out
Debug.Print d
End Sub
use workbooks.opentext filename:="your csv file with path",
It will open the csv and separate them into cells,
then apply your macro and save again as csv

I want to use a variable which contains a cell reference within a formula

I have been trying this code out and If I use direct cell reference in the formula it works fine but when I substitute the cell reference for a variable it doesn't work.
Can you tell me where im going wrong.
The aim is to add up all the cells which contain a date in november
This is the code
Private Sub Worksheet_Change(ByVal Target As Range)
Dim last As Long
Dim cussat As Variant
Dim Cussatrange As String
With ActiveSheet
last = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
If Target.Address = "$C$" & last + 1 Then
Range("$B$" & last + 1).Value = Date
Range("$A$" & last + 1).Value = "Moss"
Cussatrange = "J1:J" & last
' I would like to substitue the cell reference in the above formula to use Cussatrange or last
cussat = [=SUMPRODUCT(--(TEXT(J1:J43,"mmm yyyy")="Nov 2014"))]
MsgBox "Last used row number in column A is " & last & " " & cussat & " " & Cussatrange
End If
End Sub
If I understand your question correctly, then you can use something like this:
Dim myFormula As String
Dim template As String
template = "=SUMPRODUCT(--(TEXT({0},""mmm yyyy"")=""Nov 2014""))"
myFormula = Replace(template, "{0}", Cussatrange)
cussat = Application.Evaluate(myFormula)
MsgBox "Last used row number in column A is " & last & " " & cussat & " " & Cussatrange
In the code a template for the formula is created and then the substring (in this case it is {0}) is repalaced with the address which is stored in the string Cussatrange.
For more info about Application.Evaluate method have a look here:
http://msdn.microsoft.com/en-us/library/office/ff193019%28v=office.15%29.aspx.
(Using square brackets (for example, "[A1:C5]") is identical to calling
the Evaluate method with a string argument)

error 1004 when trying to set cell value to value of string

I've seen this question a few times but haven't found a solution that is applicable to my situation, so here it goes:
I have a fairly complicated formula that I want to insert into a cell (complicated as in it's a pain in the butt to follow). I have the components set up in variables, and running the sub give me the correct final variable name in the locals window, however when I try to set the cell to the formula I get a '1004: application-defined or object defined error'. the output should look like this:
Cell A1: =BDS("0","pg_segment","dir = h", "number_of_periods = -3")
However it returns nothing.
I have tried the following: setting the final variable (cmdstr0) to an integer-- this works. As a string ("asdf") also works. Altering the value directly (.value = "string") works. The only thing that doesn't work is when VBA builds the formula itself to insert into the string. Here's the code, and thank you:
sub populate_revenues()
'field = bloomberg field to look up
'direction = output direction (horizontal/vertical)
'geoverride = override to display only geo or product segments
'periods = numbe of periods to display
'cmdstr = the string to be output that will download the data
Dim field As String
Dim direction As String
Dim geoverride As String
Dim periods As String
Dim cmdstr3 As String
Dim cmdstr2 As String
Dim cmdstr1 As String
Dim cmdstr0 As Variant
Let cmdstr2 = 0
Let field = Worksheets("output").Cells(1, 3).Value
Let direction = "Dir = " & Worksheets("output").Cells(1, 5).Value
Let geoverride = " product_geo_override = " & Worksheets("output").Cells(1, 7).Value
Let periods = " number_of_periods = " & Worksheets("output").Cells(2, 3).Value
Let cmdstr1 = "=BDS(" & Chr(34)
Let cmdstr3 = Chr(34) & "," & Chr(34) & field & ", " & Chr(34) _
& direction & Chr(34) & ", " & Chr(34) & geoverride & Chr(34) & ", " & Chr(34) & periods & Chr(34) & ")"
Let cmdstr0 = cmdstr1 & cmdstr2 & cmdstr3
'Let cmdstr0 = 1
Let Worksheets("Sheet2").Cells(10, 1).Value = cmdstr0
End Sub
Also, can anyone please tell me if there's a faster way to format as code than hitting space-bar four times every line?
As you know, you must double-up on the double quotes. So if you want:
=COUNTIF(A1:A10,"apples")
you must use:
Sub demo()
Range("B9").Formula = "=COUNTIF(A1:A10,""apples"")"
End Sub
I, personally, have a lot of trouble with this. What I do to debug is to place an apostrophe at the start of the formula:
Sub demo()
Range("B9").Formula = "'=COUNTIF(A1:A10,""apples"")"
End Sub
This allows me to "see" the text of the formula and fix problems.
B.T.W
To create a code block, hi-light the code and use the paired braces {}

Array Handling in VBA

Is it possible to select multiple values dynamically using Excel Macros.What i meant by dynamically is the number of values to be selected should be entered by the User.
My code is
monthList = monthList & Chr$(34) & "[Time].[Month].&[" _
& Range("Table_Months").Rows(i).Columns(2).Value & "]" & Chr$(34) & ","
Next i
c_mnth = Left(monthList, Len(monthList) - 2)
c_mnth = Right(c_mnth, Len(c_mnth) - 1)
ActiveSheet.PivotTables("PivotTable1").PivotFields("[Time].[Month].[Month]"). _
VisibleItemsList = Array(c_mnth)
By this code I couldn't make it,because at last variable c_mnth consist of all my required field as single string which has to be individual string to execute the code.
Is this what you are trying? (UNTESTED)
Dim MyAr
'
'~~> Rest of your code
'
c_mnth = Left(monthList, Len(monthList) - 2)
c_mnth = Right(c_mnth, Len(c_mnth) - 1)
MyAr = Split(c_mnth, ",")
ActiveSheet.PivotTables("PivotTable1").PivotFields("[Time].[Month].[Month]"). _
VisibleItemsList = Array(MyAr)