I'm attempting to write hyperlinks to cells via one button click from the ribbon in Excel 2007. These hyperlinks must, in turn, execute another routine that does stuff to the row on which they're located. However, the standard method of Worksheet_FollowHyperlink() will not work, as I need to execute this via an external xlam addin, and as far as I understand, this event triggers from hyperlink clicks located only in the same worksheet.
As a result, I have found that using the =HYPERLINK("#funName()","Click me") method works, but a problem exists that I am still experiencing.
The following is a trimmed down version of my already-working code:
Sub InsertLink() ' This is run directly by the callback for an IRibbonControl button click
With Sheet1
lastrow = Range("A" & Rows.count).End(xlUp).Row
While i <= lastrow
Range("E" & i).Value = "=HYPERLINK(""#consolidateDuplicate(A" & i & ",C" & i & ")"",""Copy this row to next"")"
Wend
Call MsgBox ("Finished inserting hyperlinks on each row.", vbOKOnly)
End With
End Sub
Sub consolidateDuplicate(PN, Quantity)
Dim thisRow, prevQuant As Long
thisRow = Selection.Row
MsgBox("You clicked the hyperlink for " & thisRow & "Q: " & Quantity & ", PN: " & PN)
End Sub
Clicking the ribbon button successfully writes all hyperlinks into their respective rows as expected. However, when I try to click any of these hyperlinks, thus executing consolidateDuplicate() in the same add-in module, I immediately receive a "Reference is not valid" warning followed by the MsgBox message.
I have tried removing all code from the routine to no avail. I also tried the standard brute-force bypass method of adding On Error Resume Next ... On Error Goto 0 as well as Application.DisplayAlerts = False ... Application.DisplayAlerts = True. Neither helps. I still receive the warning.
So while my script works fine and does what I want it to in the end, I feel like there should be a way to suppress the warning, or fix whatever is causing it, which I have a feeling, like Worksheet_FollowHyperlink(), is from storing the routine in the scope of an add-in module (required for my application), rather than keeping it totally contained in the calling workbook/sheet itself.
Any ideas?
Your consolidateDuplicate subroutine should be a Function, returning the address that the hyperlink should take you to. The lack of a return value is what is causing the "Reference is not valid" error.
The following code might work, effectively telling the hyperlink to take you to the cell in which the hyperlink was located:
Function consolidateDuplicate(PN, Quantity) As Range
Dim thisRow, prevQuant As Long
thisRow = Selection.Row
MsgBox ("You clicked the hyperlink for " & thisRow & "Q: " & Quantity & ", PN: " & PN)
Set consolidateDuplicate = Selection
End Function
Related
I have an excel workbook, in one of the sheet we have sumiff formulas in 13 columns. these formulas are placed up to 15000 rows.
=SUMIFS($C:$C,$A:$A,A3,B:B,RIGHT($N$1,10))
all the formulas are deleting automatically some times, how to trace this or what is the cause of deleting all the formulas in 13 columns.
With the help of VBA you may find the cause.
Press Alt+F11 to bring the VBA editor.
Double click on the ThisWorkbook module of the Workbook having problems in left-top panel to edit it.
Add the following code (adapted from here)
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim aCell As Range
Dim del As Boolean
del = False
For Each aCell In Target.Cells ' Target may contain more than one cells.
'If aCell.Formula = "" Then ' Option #1
If Len(Trim(aCell.Value)) = 0 Then ' Option #2
'MsgBox "Cell " & aCell.Address & " in sheet " & Sh.Name & " has been cleared or deleted." ' Uncomment this line for further diagnostics
del = True
'Else ' Uncomment these two lines for further diagnostics
' MsgBox "Cell " & aCell.Address & " in sheet " & Sh.Name & " has been changed."
End If
If (del) Then Exit For
Next
MsgBox "At least on cell in range " & Target.Address & " in sheet " & Sh.Name & " has been cleared or deleted."
End Sub
Options #1 or #2 should work equally well.
You may uncomment some of the lines for further diagnostics.
It may become too verbose, and I expect it not be necessary.
You will need to save the workbook as .xlsm.
I have a shared spreadsheet that has both a form for users to enter data into and a log for the data to be moved to once the user hits the "submit" button (calls the Submit_to_Log sub). The macro works well in an unshared file; the only issue is when I share the file and two or more users try to submit data at the same time, the macro tries to write both of their data to the same, next blank row. The user who submits the data first gets their data submitted successfully, but the second user encounters an error where their data isn't submitted to the log but is still deleted from the form. Sheet3 refers to the log and sheet1 refers to the form. Any tips on how to improve this code?
Sub Submit_to_Log()
On Error GoTo ErrorHandler
Dim rng_form As Range
erow = Sheet3.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row
Set rng_form = Sheet1.Range("B3:S" & Range("K2").End(xlDown).Row)
If IsEmpty(Sheet1.Range("K3").Value) Then
MsgBox "First row must be filled!" & vbNewLine & vbNewLine & "If the first row is filled, please make sure that column K is filled out."
End
End If
rng_form.Copy
Sheet3.Range("B" & erow).PasteSpecial xlPasteValues
Sheet3.Activate
Sheet3.Range("A1").Select
Sheet1.Activate
rng_form.EntireRow.Delete
MsgBox "Your requests have been submitted." & vbNewLine & vbNewLine & "If you still see requests in the form waiting to be submitted, please make sure that there are no empty rows between your requests and/or that each request has column K filled out."
Exit Sub
ErrorHandler:
MsgBox "There was an error. Please try again."
End Sub
I've created a function which checks if a sheet exists in an external workbook. Code as follows (I've checked this and this works perfectly with other sheets, commenting out the If statement that references this stops the error):
Function ExtSheetExists(formString) As Boolean
Dim val As Variant
On Error Resume Next
val = ExecuteExcel4Macro(formString)
ExtSheetExists = (val <> Error(2023))
On Error GoTo 0
End Function
Note: FormString is passed as "'" & wkBookRef1 & firstShtName & "'!" & "R6C12" where wkBookRef1 is just the path to the spreadsheet and firstShtName is the spreadsheet name that is being looked up.
However later when I go to update the same spreadsheet using the UpdateLink method it pops up the Select Sheet dialogue box and thus stops the run of the macro. Does anyone have an inkling as to what is going on here?
The select sheet box is as follows:
It's a bug. Effectively the formstring is run and the message box is suppressed. However it seems that it remains as a latent process in the other spreadsheet. So when it is updated it shows the suppressed message box.
I need a simple error handling code for my small macro, I have search the web but have nothing simple, seems to be all very complicated.
I down load sales reports in .txt form on a weekly basis, I run separate macro to do stuff and then add to a master page. Not every week do sales reports download as there may not have been sales for that particular region.
I need a simple error handler so that if it does not find the report, it moves to the next sub.
Any help appreciated
Sub MXM_POS()
Workbooks.OpenText Filename:="C:\Users\903270\Documents\Excel\MXMPOS*.txt"
‘Run macro code
Run ("DLK_POS")
End Sub
Here is a simple basic structure that you can expand on as needed:
Sub MXM_POS()
On Error GoTo ErrHandler
' code here
ExitSub:
' shutdown code here
Exit Sub
ErrHandler:
If Err.Number <> 0 Then
Dim mbr As VbMsgBoxResult
mbr = MsgBox( _
"Error #" & Err.Number & ": " & Err.Description & vbNewLine & _
"Would you like to continue?", vbExclamation Or vbYesNo)
If mbr = vbYes Then Resume ExitSub
Application.Quit
End If
End Sub
When I desire a stack dump I construct that within the Source property of the Err object using concatenation with a newline, and then only display the MsgBox result at the top of the calling stack, usually either the Event Handler that launched the code or the top-level macro invoked by the user.
I have an Excel VBA function that does a POST to an ASPX page. My goal is for it to work similar to the HYPERLINK function. The function could be used an indefinite number of times in the spreadsheet and each time would be executed from a different cell address, and be passed a series of parameters (url, postdata, etc). The function works fine except that it runs automatically instead of only when the user clicks on the active cell.
Function WinHTTPPostRequest(url, question, choice1, choice2, choice3, choice4, image, answer, linkDisplay)
Dim http
Dim formData As String
formData = "&choice1=" & choice1 & "&choice2=" & choice2 & "&choice3=" & choice3 & "&choice4=" & choice4 & "&question=" & question & "&image=" & image & "&answer=" & answer
formData = replaceSpaceWithPlus(formData)
Call BrowserSend(url, formData)
WinHTTPPostRequest = "Click Here"
End Function
After googling, what I've been able to find is only solutions with select/case statements for which cell was clicked and the click functionality is spreadsheet wide rather than active cell specific. This needs to be a function the user can copy indefinitely (though in this case it will only be copied vertically in the same column).
Any suggestions would be greatly appreciated.
You can achieve your goal with a slightly different Excel structure. Say we place an Inserted hyperlink in a cell (that is a hyperlink not using the =HYPERLINK() function). The destination of the hyperlink would the the cell itself. The "friendly name" would be your parameter list.
We would also include a hyperlink follow event macro.
So if we click on the hyperlink, we really don't jump anywhere. Instead the event macro will be triggered. The event macro will pick up your parameters and perform the POST.
EDIT#1:
Here is a simple example............pick a cell, any cell, and run this macro:
Sub HyperMaker()
Dim subadd As String
subadd = ActiveSheet.Name & "!" & Selection.Address(0, 0)
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:= _
subadd, TextToDisplay:="P1,P2,P3"
End Sub
This places a hyperlink in the cell that goes absolutely nowhere!
Next place this event macro in the worksheet code area:
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
ary = Split(ActiveCell.Value, ",")
MsgBox ary(0) & vbCrLf & ary(1) & vbCrLf & ary(2)
End Sub
Now if you click on the cell, the event macro will be triggered; it will grab the parameters from the cell and do SOMETHING.
You, of course, will modify this event macro to perform your POSTing operation.