I can't figure out why it is not deleting the row if the user selects no.
I even tried telling to delete a certain line in the ws but it still did not delete that row
Adding the data if it is not there works.
If it is already there the message box does pop up.
The only function that is not working is the delete.
Sub Submit_Data()
Application.ScreenUpdating = False
Dim App As New Excel.Application
Dim wBook As Excel.Workbook
Dim ws As Worksheet, id, v, m
Dim FileName As String
Dim CurrentJob As Long
Dim CurrentRow As Variant '<--- NOTE
Dim CurrentCell As Variant
Dim iRow As Long
FileName = ThisWorkbook.Path & "\database.xlsm"
'Check File Exist or Not
'If Dir(FileName) = "" Then
'MsgBox "Database File is missing. Unable to proceed.", vbOKOnly vbCritical, "Error"
'Exit Sub
'End If
Set wBook = App.Workbooks.Open(FileName)
App.Visible = False
If wBook.ReadOnly = True Then
TryWriteMode book:=wBook _
, numberOfTries:=4 _
, secondsWaitAfterFailedTry:=10
' MsgBox "test", vbInformation
End If
If wBook.ReadOnly Then
MsgBox "Database is in use. Please try again later.", vbOKOnly + vbInformation, "Read-only book"
Exit Sub
End If
'Transfer the Data
id = TextBox2.Value
With wBook.Sheets("database")
Set ws = wBook.Sheets("database")
' m = Application.Match(id, ws.[B:B], 0) 'try to match an existing row
m = Application.Match(id, 5, 0)
CurrentJob = TextBox2.Value
CurrentRow = Application.Match(CurrentJob, ws.Range("B:B"), 0)
CurrentCell = ws.Cells(CurrentRow, 1)
If IsError(CurrentRow) Then
iRow = .Range("A" & Application.Rows.Count).End(xlUp).Row + 1
.Range("A" & iRow).Value = TextBox1.Value 'Cell
.Range("B" & iRow).Value = TextBox2.Value 'workorder number
.Range("C" & iRow).Value = TextBox3.Value 'product number
.Range("D" & iRow).Value = TextBox4.Value 'Work order quanity
Else
MsgBox "JOB ALREADY ASSIGNED TO " & CurrentCell & vbNewLine & "DO YOU WANT TO KEEP IT THIER ", vbYesNo
If Result = vbNo Then
ws.Rows(CurrentRow).EntireRow.Delete
End If
End If
End With
wBook.Close Savechanges:=True
App.Quit
Set App = Nothing
'Reset the form
Call resetForm
Application.ScreenUpdating = True
End Sub
Related
Form 1
I am getting the code to wire to the database file but the check if the value from text box 2 is already in column B throw a message and exit is not working Also if the database is open I am not getting an error it just freezes.
Form 2
I am getting the spinning wheel. It is how it is supposed to work is if textbox1 value is already in column B add time data to column F of that row if it is textbox 1 value is not found in B throw a massage
Any help is appreciated
FORM 1 CODE
Private Sub CommandButton1_Click()
'check to see is all data is filled in
If TextBox1.Value = "" Or TextBox2.Value = "" Or _
TextBox3.Value = "" Or TextBox4.Value = "" Or TextBox5.Value = "" Then
MsgBox "YOU DID NOT FILL IN ALL THE INFO."
Exit Sub
End If
Call Submit_Data
Call resetForm
Unload Me
End Sub
Sub resetForm()
TextBox1.Value = ""
TextBox2.Value = ""
TextBox3.Value = ""
TextBox4.Value = ""
TextBox5.Value = ""
UserForm1.TextBox1.SetFocus
End Sub
Private Sub CommandButton2_Click()
Unload Me
End Sub
Private Sub UserForm_Click()
End Sub
Sub Submit_Data()
Application.ScreenUpdating = False
Dim App As New Excel.Application
Dim wBook As Excel.Workbook
Dim FileName As String
Dim iRow As Long
FileName = ThisWorkbook.Path & "\test.xlsm"
'Check File Exist or Not
'If Dir(FileName) = "" Then
'MsgBox "Database File is missing. Unable to proceed.", vbOKOnly vbCritical, "Error"
'Exit Sub
'End If
Set wBook = App.Workbooks.Open(FileName)
App.Visible = False
If wBook.ReadOnly = True Then
MsgBox "Database is in use. Please try after sometimes.", vbookonly + vbCritical, "error"
Exit Sub
End If
'Transfer the Data
id = TextBox2.Value
With wBook.Sheets("test")
Set ws = wBook.Sheets("test")
m = Application.Match(id, ws.Columns("B"), 0) 'try to match an existing row
If IsError(m) Then 'no match?
iRow = .Range("A" & Application.Rows.Count).End(xlUp).Row + 1
.Range("A" & iRow).Value = TextBox1.Value 'Cell
.Range("B" & iRow).Value = TextBox2.Value 'workorder number
.Range("C" & iRow).Value = TextBox3.Value 'product number
.Range("D" & iRow).Value = TextBox4.Value 'Work order quanity
.Range("E" & iRow).Value = Date 'date
.Range("F" & iRow).Value = Time 'time
.Range("M" & iRow).Value = TextBox5.Value 'crew size
Else
MsgBox "JOB ALREADY CLOCKED IN!"
Exit Sub
End If
End With
wBook.Close Savechanges:=True
App.Quit
Set App = Nothing
'Reset the form
Call resetForm
Application.ScreenUpdating = True
MsgBox "Data submitted successfully!"
End Sub
FORM 2 CODE
Private Sub CommandButton1_Click()
'check to see is all data is filled in
If TextBox1.Value = "" Then
MsgBox "YOU DID NOT ENTER WO."
Exit Sub
End If
Call Submit_Data
Call resetForm
Unload Me
End Sub
Private Sub CommandButton2_Click()
Unload Me
End Sub
Sub Submit_Data()
Application.ScreenUpdating = False
Dim App As New Excel.Application
Dim wBook As Excel.Workbook
Dim FileName As String
Dim iRow As Long
FileName = ThisWorkbook.Path & "\Database.xlsm"
'Check File Exist or Not
'If Dir(FileName) = "" Then
'MsgBox "Database File is missing. Unable to proceed.", vbOKOnly vbCritical, "Error"
'Exit Sub
'End If
Set wBook = App.Workbooks.Open(FileName)
App.Visible = False
If wBook.ReadOnly = True Then
MsgBox "Database is in use. Please try after sometimes.", vbookonly + vbCritical, "error"
Exit Sub
End If
'Transfer the Data
id = TextBox1.Value
With wBook.Sheets("Database")
m = Application.Match(id, ("B"), 0) 'try to match an existing row
If IsError(m) Then 'no match?
MsgBox "NEVER CLOCKED IN"
Exit Sub
End If
With ws.Rows(m)
.Columns("F").Value = Time
wBook.Close Savechanges:=True
App.Quit
Set App = Nothing
'Reset the form
Call resetForm
Application.ScreenUpdating = True
MsgBox "Data submitted successfully!"
End With
End With
End Sub
Sub resetForm()
TextBox1.Value = ""
UserForm1.TextBox1.SetFocus
End Sub
Private Sub UserForm_Click()
End Sub
If the ID values on your "database" sheet are numeric, you need to use a numeric input for Match(), so:
'Transfer the Data
id = CLng(TextBox2.Value) '<<< assuming the value is numeric: may want to add a check...
With wBook.Sheets("test")
Set ws = wBook.Sheets("test")
m = Application.Match(id, ws.Columns("B"), 0) 'try to match an existing row
If IsError(m) Then 'no match?
iRow = .Range("A" & Application.Rows.Count).End(xlUp).Row + 1
'etc
'etc
You don't need a separate instance of Excel to save the record - it's better to just open the file in the existing instance.
Also - if you're planning on not closing the file immediately after populating the data row, you need to check to see if it's already open when you perform the next save: opening a file which is already open can give unexpected results. See https://stackoverflow.com/a/56262538/478884
So currently i'm working on VBA forms(Product Master) , and got stuck across this problem. So basically, i have 3 buttons for my data i.e., Add, Update and Delete. Done with Add and Update button.
Just don't know how to delete my data from listbox which is in userform, and this user form is connected to a worksheet.
'''
Option Compare Text
Private Sub btn_ProductMaster_Add_Click()
If Me.txt_Product_Name.Value = "" Then
MsgBox "Please Enter Product Name", vbCritical
Exit Sub
End If
If IsNumeric(Me.txt_Purchase_Price) = False Then
MsgBox "Please Enter Product Price", vbCritical
Exit Sub
End If
If Me.txt_Product_colour.Value = "" Then
MsgBox "Please Enter Product Colour", vbCritical
Exit Sub
End If
Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Product_Master")
Dim lr As Integer
lr = Application.WorksheetFunction.CountA(sh.Range("A:A"))
Me.txt_id = StrConv(Me.txt_Product_Name.Value, vbProperCase) & "_" & StrConv(Me.txt_Product_colour.Value, vbProperCase)
If Application.WorksheetFunction.CountIf(sh.Range("B:B"), Me.txt_id.Value) > 0 Then
MsgBox "This Product is already Available in product master", vbCritical
Exit Sub
End If
sh.Range("A" & lr + 1).Value = lr
sh.Range("B" & lr + 1).Value = Me.txt_id.Value
sh.Range("C" & lr + 1).Value = StrConv(Me.txt_Product_Name.Value, vbProperCase)
sh.Range("D" & lr + 1).Value = StrConv(Me.txt_Product_colour.Value, vbProperCase)
sh.Range("E" & lr + 1).Value = Me.txt_Purchase_Price.Value
Me.txt_id.Value = ""
Me.txt_Product_Name.Value = ""
Me.txt_Product_colour.Value = ""
Me.txt_Purchase_Price.Value = ""
MsgBox "Product has been added", vbInformation
Call show_data
End Sub
Sub show_data()
Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Product_Master")
Dim lr As Integer
lr = Application.WorksheetFunction.CountA(sh.Range("A:A"))
If lr = 1 Then lr = 2
With Me.list_ProductMaster
.ColumnCount = 5
.ColumnHeads = True
.ColumnWidths = "40,110,110,80,80"
.RowSource = "Product_Master!A2:E" & lr
End With
End Sub
Private Sub btn_ProductMaster_Dlt_Click()
list_ProductMaster.SetFocus
Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Product_Master")
Dim lr As Integer
lr = Me.txt_srno.Value
MsgBox lr
sh.Cells(lr + 1, "A").EntireRow.Delete
Me.txt_srno.Value = ""
Me.txt_id.Value = ""
Me.txt_Product_Name.Value = ""
Me.txt_Product_colour.Value = ""
Me.txt_Purchase_Price.Value = ""
MsgBox "Product has been Deleted", vbInformation
Call show_data
End Sub
Private Sub btn_ProductMaster_Extract_Click()
Dim nwb As Workbook
Set nwb = Workbooks.Add
ThisWorkbook.Sheets("Product_Master").UsedRange.Copy nwb.Sheets(1).Range("a1")
End Sub
Private Sub btn_ProductMaster_Updt_Click()
If Me.txt_Product_Name.Value = "" Then
MsgBox "Please Enter Product Name", vbCritical
Exit Sub
End If
If IsNumeric(Me.txt_Purchase_Price) = False Then
MsgBox "Please Enter Product Price", vbCritical
Exit Sub
End If
If Me.txt_Product_colour.Value = "" Then
MsgBox "Please Enter Product Colour", vbCritical
Exit Sub
End If
Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Product_Master")
Dim lr As Integer
lr = Me.txt_srno.Value
Me.txt_id = StrConv(Me.txt_Product_Name.Value, vbProperCase) & "_" & StrConv(Me.txt_Product_colour.Value, vbProperCase)
sh.Range("A" & lr + 1).Value = lr
sh.Range("B" & lr + 1).Value = Me.txt_id.Value
sh.Range("C" & lr + 1).Value = StrConv(Me.txt_Product_Name.Value, vbProperCase)
sh.Range("D" & lr + 1).Value = StrConv(Me.txt_Product_colour.Value, vbProperCase)
sh.Range("E" & lr + 1).Value = Me.txt_Purchase_Price.Value
Me.txt_srno.Value = ""
Me.txt_id.Value = ""
Me.txt_Product_Name.Value = ""
Me.txt_Product_colour.Value = ""
Me.txt_Purchase_Price.Value = ""
MsgBox "Product has been Updated", vbInformation
Call show_data
End Sub
Private Sub list_ProductMaster_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Me.txt_srno.Value = Me.list_ProductMaster.List(Me.list_ProductMaster.ListIndex, 0)
Me.txt_id.Value = Me.list_ProductMaster.List(Me.list_ProductMaster.ListIndex, 1)
Me.txt_Product_Name.Value = Me.list_ProductMaster.List(Me.list_ProductMaster.ListIndex, 2)
Me.txt_Product_colour.Value = Me.list_ProductMaster.List(Me.list_ProductMaster.ListIndex, 3)
Me.txt_Purchase_Price.Value = Me.list_ProductMaster.List(Me.list_ProductMaster.ListIndex, 4)
End Sub
Private Sub UserForm_Activate()
Call show_data
End Sub
'''
I would like to make exports based on the boxes I checked
therefore with a lot of help I build the following code
Private Sub CommandButton1_Click()
Dim xSht As Worksheet, xFileDlg As FileDialog, xFolder As String, xYesorNo, I, xNum As Integer
Dim xOutlookObj As Object, xEmailObj As Object, xUsedRng As Range, xArrShetts As Variant
Dim xPDFNameAddress As String, xStr As String, rngExp As Range, lastRng As Range
xArrShetts = sheetsArr(Me) 'do not forget the keep the sheetsArr function...
For I = 0 To UBound(xArrShetts)
On Error Resume Next
Set xSht = Application.ActiveWorkbook.Worksheets(xArrShetts(I))
If xSht.Name <> xArrShetts(I) Then
MsgBox "Worksheet no found, exit operation:" & vbCrLf & vbCrLf & xArrShetts(I), vbInformation, "Kutools for Excel"
Exit Sub
End If
Next
Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
If xFileDlg.Show = True Then
xFolder = xFileDlg.SelectedItems(1)
Else
MsgBox "You must specify a folder to save the PDF into." & vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Must Specify Destination Folder"
Exit Sub
End If
'Check if file already exist
xYesorNo = MsgBox("If same name files exist in the destination folder, number suffix will be added to the file name automatically to distinguish the duplicates" & vbCrLf & vbCrLf & "Click Yes to continue, click No to cancel", _
vbYesNo + vbQuestion, "File Exists")
If xYesorNo <> vbYes Then Exit Sub
For I = 0 To UBound(xArrShetts)
Set xSht = Application.ActiveWorkbook.Worksheets(xArrShetts(I))
xStr = xFolder & "\" & xSht.Name & ".pdf"
xNum = 1
While Not (Dir(xStr, vbDirectory) = vbNullString)
xStr = xFolder & "\" & xSht.Name & "_" & xNum & ".pdf"
xNum = xNum + 1
Wend
Set xUsedRng = xSht.UsedRange
If Application.WorksheetFunction.CountA(xUsedRng.Cells) <> 0 Then
Set lastRng = xSht.Range("A" & xSht.Rows.Count).End(xlUp) 'determine the last cell in A:A
Set rngExp = xSht.Range(lastRng.Offset(-26), lastRng.Offset(, 7)) 'create the range to be exported as pdf
With xSht.PageSetup
.PaperSize = xlPaperA4
.PrintArea = rngExp.Address(0, 0)
.Orientation = xlLandscape
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
rngExp.ExportAsFixedFormat Type:=xlTypePDF, Filename:=xStr, Quality:=xlQualityStandard, IgnorePrintAreas:=False 'export the range, not the sheet
End If
xArrShetts(I) = xStr
Next
'Create Outlook email
Set xOutlookObj = CreateObject("Outlook.Application")
Set xEmailObj = xOutlookObj.CreateItem(0)
With xEmailObj
.Display
.To = ""
.cc = ""
.Subject = "????"
For I = 0 To UBound(xArrShetts)
.Attachments.Add xArrShetts(I)
Next
If .DisplayEmail = False Then
'.Send
End If
End With
End Sub
Private Function sheetsArr(uF As UserForm) As Variant
Dim c As MSForms.Control, strCBX As String, arrSh
For Each c In uF.Controls
If TypeOf c Is MSForms.CheckBox Then
If c.Value = True Then strCBX = strCBX & "," & c.Caption
End If
Next
sheetsArr = Split(Mid(strCBX, 2), ",") 'Mid(strCBX, 2) eliminates the first string character (",")
End Function
Private Sub CommandButton2_Click()
Unload basicUserform
End Sub
the problem is when I run the code no attachments show up or can be found in the destination map I choose earlier.
I also put the file here so you can see for yourself.:
https://easyupload.io/ufnmvr
I appreciate your help and time!
Added a check for valid range of 27 or more rows otherwise lastRng.Offset(-26) will fail and because On Error Resume Next was not cancelled with On Error Goto 0 it won't raise an error.
Private Sub CommandButton1_Click()
Dim xSht As Worksheet, xFileDlg As FileDialog
Dim xFolder As String, xYesorNo, I, xNum As Integer
Dim xOutlookObj As Object, xEmailObj As Object
Dim xUsedRng As Range, xArrShetts As Variant
Dim xPDFNameAddress As String, xStr As String
Dim rngExp As Range, lastRng As Range
xArrShetts = sheetsArr(Me) 'do not forget the keep the sheetsArr function...
If UBound(xArrShetts) < 0 Then
MsgBox "No sheets selected", vbExclamation
Exit Sub
End If
' check sheets exist
For I = 0 To UBound(xArrShetts)
On Error Resume Next
Set xSht = Application.ActiveWorkbook.Worksheets(xArrShetts(I))
If xSht.Name <> xArrShetts(I) Then
MsgBox "Worksheet no found, exit operation:" & vbCrLf & vbCrLf & _
xArrShetts(I), vbInformation
Exit Sub
End If
On Error GoTo 0
Next
Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
If xFileDlg.Show = True Then
xFolder = xFileDlg.SelectedItems(1)
Else
MsgBox "You must specify a folder to save the PDF into." & vbCrLf & vbCrLf & _
"Press OK to exit this macro.", vbCritical, "Must Specify Destination Folder"
Exit Sub
End If
'Check if filename already exist
xYesorNo = MsgBox("If same name files exist in the destination folder," & _
"number suffix will be added to the file name automatically " & _
"to distinguish the duplicates " & vbCrLf & vbCrLf & _
"Click Yes to continue, click No to cancel", _
vbYesNo + vbQuestion, "File Exists")
If xYesorNo <> vbYes Then Exit Sub
For I = 0 To UBound(xArrShetts)
Set xSht = Application.ActiveWorkbook.Worksheets(xArrShetts(I))
xStr = xFolder & "\" & xSht.Name & ".pdf"
xNum = 1
While Not (Dir(xStr, vbDirectory) = vbNullString)
xStr = xFolder & "\" & xSht.Name & "_" & xNum & ".pdf"
xNum = xNum + 1
Wend
Set xUsedRng = xSht.UsedRange
If Application.WorksheetFunction.CountA(xUsedRng.Cells) <> 0 Then
'determine the last cell in A:A
Set lastRng = xSht.Range("A" & xSht.Rows.Count).End(xlUp)
If lastRng.Row < 27 Then
MsgBox "Incorrect Start Row " & lastRng.Row, _
vbCritical, "ERROR on " & xSht.Name
Exit Sub
End If
'create the range to be exported as pdf
Set rngExp = xSht.Range(lastRng.Offset(-26), lastRng.Offset(, 7))
With xSht.PageSetup
.PaperSize = xlPaperA4
.PrintArea = rngExp.Address(0, 0)
.Orientation = xlLandscape
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
'export the range, not the sheet
rngExp.ExportAsFixedFormat Type:=xlTypePDF, Filename:=xStr, _
Quality:=xlQualityStandard, IgnorePrintAreas:=False
xArrShetts(I) = xStr
Else
' no file created
xArrShetts(I) = ""
End If
Next
'Create Outlook email
Set xOutlookObj = CreateObject("Outlook.Application")
Set xEmailObj = xOutlookObj.CreateItem(0)
With xEmailObj
.To = ""
.cc = ""
.Subject = "????"
For I = 0 To UBound(xArrShetts)
If Len(xArrShetts(I)) > 0 Then
.Attachments.Add xArrShetts(I)
End If
Next
.Display ' or ' Send
End With
End Sub
I'm trying to attach files and store them in cells G2 and on.
However, every time I input it gets input in G2. If a user decides to enter more data the input data will iterate into a new row but the attachment stays in row G2 and takes the place of the previous one.
textbox2 in userform gets skipped every time I press enter. I want my users to navigate with keyboards but if I'm done in textbox1 and press enter it will throw me to textbox3 rather than textbox2.
Private Sub SubmitButton_Click()
Dim iRow As Long
Dim wrkSht As Worksheet
Set wrkSht = Worksheets("Sheet1")
Dim emailApplication As Object
Dim emailItem As Object
iRow = wrkSht.Cells.Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
If Trim(RequesterBox.Value) = "" Then
RequesterBox.SetFocus
MsgBox "Please complete the form"
Exit Sub
End If
wrkSht.Cells(iRow, 1).Value = RequesterBox.Value
wrkSht.Cells(iRow, 2).Value = SquadronBox.Value
wrkSht.Cells(iRow, 3).Value = EmailBox.Value
wrkSht.Cells(iRow, 4).Value = PhoneBox.Value
wrkSht.Cells(iRow, 5).Value = LocationBox.Value
wrkSht.Cells(iRow, 6).Value = DescriptionBox.Value
MsgBox "Request has been added Succesfully. Thanks for you submition, someone will be contacting you shortly", vbOKOnly + vbInformation, "Thanks"
'----------------------- Send Email-----------------------'
Set emailApplication = CreateObject("Outlook.Application")
Set emailItem = emailApplication.CreateItem(0)
emailItem.To = ""
emailItem.Subject = "Facility Request"
emailItem.Body = "A request for " & LocationBox.Value & " has been submited with the following description: " & Chr(10) & _
DescriptionBox.Value
emailItem.Display
Set emailItem = Nothing
Set emailItemApplication = Nothing
RequesterBox.Value = ""
SquadronBox.Value = ""
EmailBox.Value = ""
PhoneBox.Value = ""
LocationBox.Value = ""
DescriptionBox.Value = ""
RequesterBox.SetFocus
End Sub
Private Sub AttachButton_Click()
Set wrkSht = Worksheets("Sheet1")
Dim LinksList As Range
Dim iRow As Long
Dim LinkAttached As Long
Set LinksList = Range("G2")
Sheet1.Range("G2").Select
'declare last row to insert link to
lastRowLink = WorksheetFunction.CountA(Sheets("Sheet1").Range("G:G"))
Sheets("Sheet1").Cells(lastRow + 1, 11).Value = LinkAttached
ChDrive "C:\"
ChDir "C:\"
Filt = "PNG Files(*.png),*.png ," & _
"Jpeg Files(*.jpeg),*.jpg ," & _
"PDF Files (*.pdf),*.pdf ," & _
"All Files (*.*),*.*"
FilterIndex = 1
Title = "Select a File to Hyperlink"
FileName = Application.GetOpenFilename _
(FileFilter:=Filt, _
FilterIndex:=FilterIndex, _
Title:=Title)
If FileName <> False Then
wrkSht.Hyperlinks.Add Anchor:=LinksList, _
Address:=FileName, _
TextToDisplay:=FileName
Else
MsgBox "No file was selected.", vbCritical, "Loading Error"
Exit Sub
End If
End Sub
Hy i hope it will help you
Private Sub AttachButton2_Click()
Dim lastRow As Long, nextId As Long
Dim ws As Worksheet
Dim newRecord As Range
Set ws = ThisWorkbook.Worksheets("Sheet1")
With ws
'getlcurrent last row
lastRow = .Cells(.Rows.Count, "G").End(xlUp).Row
'get next Id
nextId = Val(.Range("G" & lastRow).Value) + 1
'set new record
Set newRecord = .Range("G" & lastRow + 1)
'insert data
newRecord.Value = nextId
'select file
ChDrive "C:\"
ChDir "C:\"
Filt = "PNG Files(*.png),*.png ," & _
"Jpeg Files(*.jpeg),*.jpg ," & _
"PDF Files (*.pdf),*.pdf ," & _
"All Files (*.*),*.*"
FilterIndex = 1
Title = "Select a File to Hyperlink"
Filename = Application.GetOpenFilename _
(FileFilter:=Filt, _
FilterIndex:=FilterIndex, _
Title:=Title)
If Filename <> False Then
.Hyperlinks.Add Anchor:=newRecord, _
Address:=Filename, _
TextToDisplay:=Filename
Else
MsgBox "No file was selected.", vbCritical, "Loading Error"
Exit Sub
End If
End With
End Sub
I would like to use activeworkbook.changelink like this:
ActiveWorkbook.ChangeLink
Name:= *current workbook*
NewName:= *Open the folder of current workbook from where I can choose the new file*
If I have a link in a cell ("c:\Docs\example.xls") but I want to change it to something (I have more files in c:\Docs, like "example2.xls", "example3.xls",...) the macro should open the folder of c:\Docs\ (Browse dialog) from where I could chose the file I want to use.
Can you suggest me something? Many thanks!
Finally I got time to finish this one. It's working so I share it. Maybe it will be useful for somebody :)
Sub Linkchange()
Const RefText = "#REF"
Dim fd As Office.FileDialog
Dim txtFileName, Msg As String
Dim OldLink_num As Long
Dim ws As Worksheet
Dim FindRef As Range
Dim SheetLoop
Dim FirstAddress
Dim UserOption
alink = ThisWorkbook.LinkSources
If IsEmpty(alink) Then
Msgbox "Nothing is attached."
Else
For Idx = 1 To UBound(alink)
Msg = Msg & (Idx) & ". " & alink(Idx) & vbCrLf & vbNewLine
Next
Msgbox Msg
Linkchange_userform.Show
'Private Sub CommandButton1_Click()
'Dim a As Long
'a = ListBox1.Value
'Msgbox a & ". is chosen"
'Unload Me
'End Sub
'Private Sub ListBox1_Click()
'End Sub
'Private Sub UserForm_Initialize()
'Dim Idx As Long
'alink = ActiveWorkbook.LinkSources
'For Idx = 1 To UBound(alink)
' ListBox1.AddItem Idx
'Next
'ListBox1.ListIndex = 0
'End Sub
OldLink_num = Linkchange_userform.ListBox1.Value
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Pick a file!"
.InitialFileName = Left$(alink(OldLink_num), InStrRev(alink(OldLink_num), "\"))
.Filters.Clear
.Filters.Add "All Files", "*.*"
If .Show = True Then
txtFileName = .SelectedItems(1)
Else
Exit Sub
End If
End With
ActiveWorkbook.ChangeLink Name:=alink(OldLink_num), NewName:=txtFileName, Type:=xlLinkTypeExcelLinks
Msgbox "Ready!"
Application.ScreenUpdating = False
For SheetLoop = 1 To ThisWorkbook.Sheets.Count
Set FindRef = ThisWorkbook.Sheets(SheetLoop).Cells.Find(RefText, lookat:=xlPart, LookIn:=xlValues)
If Not FindRef Is Nothing Then
FirstAddress = FindRef.Address
While Not FindRef Is Nothing
UserOption = Msgbox("Fail at - " & ThisWorkbook.Sheets(SheetLoop).Name & ", cell " & FindRef.Address & vbNewLine & "To continue: OK" & vbNewLine & "To exit: Cancel", vbOKCancel)
If UserOption = vbCancel Then
Exit Sub
End If
Set FindRef = ThisWorkbook.Sheets(SheetLoop).Cells.FindNext(FindRef)
If FindRef.Address = FirstAddress Then
Set FindRef = Nothing
End If
Wend
End If
Next SheetLoop
Application.ScreenUpdating = True
End If
End Sub