Use a generic pathway as default - vba

I have a small program that creates a load of files and saves to a folder specified by the user. Currently the top of the userform looks like the following when initialised:
I'd prefer if when the userform opens and also when the dialog for choosing a appears (via the Destination button) that a general default is already shown:
Can the program find the pathway to a user's desktop?

To get the path to the users desktop, use:
PathToDesktop = Environ("USERPROFILE") & "\Desktop"

If you are doing this in excel-vba, the following code would save the current workbook as a copy to the user's desktop... you can probably figure out what you're doing from there.
Dim DesktopPath As String
DesktopPath = CreateObject("WScript.Shell").SpecialFolders("Desktop") & Application.PathSeparator
ActiveWorkbook.SaveAs DesktopPath & "filename.xls"

Related

How to use the relative path in SQL - ODBC?

I have a problem with Excel (ODBC / Access). I would like to refresh data from any folder in my computer. I have file which I use from Desktop, but I would like to refresh data from the same file when it will be move to documents, etc. Please could you provide what I should do?
I have a file connection as below:
DSN=Excel Files;DBQ=C:\Users\User\Desktop\Task1\SalesBudget2018.xlsx;DefaultDir=C:\Users\User\Desktop\Task1;DriverId=1046;MaxBufferSize=2048;PageTimeout=5;
Thank you.
EDIT1: Thank you. I tried use your solution and I received error: "run time error 2147467259 Database or object is read-only", my code below. The bug is related to ".Open" line:
Sub RefreshData()
Dim CreateNew As Object
Dim RunSELECT As Object
Dim Data As String
Dim SQL As String
FolderPath = ActiveWorkbook.path
Path = Left(FolderPath, InStrRev(FolderPath, "\") - 1)
Set CreateNew = CreateObject("ADODB.Connection")
With CreateNew
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & Path & "\SalesBudget2018.xlsx" & ";" & "Extended Properties=""Excel 12.0 Xml;HDR=YES;"";"
.Open
End With
'Run SQL
SQL = "SELECT * FROM [twRynki$]"
Set RunSELECT = cn.Execute(SQL)
Do
output = output & RunSELECT(0) & ";" & RunSELECT(1) & ";" & RunSELECT(2) & vbNewLine
Debug.Print RunSELECT(0); ";" & RunSELECT(1) & ";" & RunSELECT(2)
rs.Movenext
Loop Until rs.EOF
End Sub
Your path actually is not relative at all. But ACE/JET data engine does not support relative paths anyway.
A relative path would be
\Data\mydb.mdb
So, above would be one folder up called data from current location. And one folder down using relative would be:
..\Data\mydb.mdb
However, with ACE/Access relative paths are not supported. However, what we do when we want software to work say from the current folder? We simple get and use the full path name ON APPLICATION start up. So, you can get/grab the current folder. In Excel VBA you can use this:
ActiveWorkbook.Path
So above will give you the current path. And thus you use that in code to set the connection string. So, even in access, if we want the software to work in any folder? We simply get/grab the full path name on startup. As a result, the software works in any folder and you effective get relative address in that you "don't care" where the software is placed, since you always get/grab the full path name anyway. So, with above, you could append a folder name called data
ActiveWorkbook.Path & "\Data\Mydb.accdb"
So, from the current workbook location, you could always have a folder called data, and inside that folder you can have your database. So, in effect you do get relative addressing, but you always pulling the full path name of the current workbook as per above.
The end result is you don't miss not having some form of relative addressing since you don't need to with this approach.
The above is for Excel VBA. To get current path from Access VBA? You can use this:
currentproject.Path
So, your connection string to Excel could be this:
dim strExcelPath as string
strExcelPath = CurrentProject.Path & "\Task1\SalesBudget2018.xlsx"
It not clear if the access application is in the SAME folder as task1?
Assuming yes, then this would work:
strExcelPath = CurrentProject.Path & "\SalesBudget2018.xlsx"
So, now the folder can be on the desktop, my documents - it will not matter. You can thus use above as part of your connection string. It not clear if you linking to Excel (linked table), or you using VBA and say ADO code. However, it really don't matter. On application startup, you get the above connection string, check it against the linked table -- if same then do nothing. If different, then you re-link that one table. Thus you ONLY re-link one time if the folder been moved. And no matter where you move the folder? As long as you assume the Excel sheet is in the same folder as the access app, then you good to go. And as noted, you could add a sub folder say ExcelSheets to above. And once again, no matter where you move this folder with the Access part, as long as the sub folder is in the same dir/folder, then this will work - despite you not having relative addressing.

Local copy of word document loaded from shared drive not working with VBA saveas PDF method. Doesn't save the document

I have a macro that works fine in the shared drive when it is only accessed by one/first person. When it is accessed by the second person while the first person still has it open, it says it's already open. When I click "create a local copy and merge changes later" the macro will work up until it saves the file.
The macro basically invokes a userform to collect information, fill in the document, and then it should save the document as a PDF to the desktop. The PDF isn't saving in the local copy version for some reason. When the "Follow hyperlink" comes up, it says "Error 4198, command failed". I check my desktop and the file isn't there, leading me to believe that this error is in relation to the file not being created....
I just need the macro to allow the document to be saved to their desktop as a pdf, whether they're in the normal version, or the local copy created as a byproduct of the shared drive rules.
Main_Form.hide
enviro = CStr(Environ("USERPROFILE"))
sName = Format(Date, "mm-dd-yyyy") & " Denial Letter - Invoice " & Invoice_Text.Value & ".pdf"
sPath = enviro & "\Desktop\"
ThisDocument.SaveAs2 FileName:=sPath & sName, fileformat:=wdFormatPDF
fullName = sPath & sName
ThisDocument.FollowHyperlink fullName
ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
Use a template (dotm), not a document. Create new documents from the template, that way there will be no document "lock".
Also, don't use ThisDocumentas that means specifically the document in which the VBA code is located, use ActiveDocument, instead.

Change Web Image via Excel Macro

I am using Excel macros to drive image changes for a webpage. If I want an image to change on the page, I execute the macro, which grabs the desired image and replaces the file the webpage is using, and the webpage refreshes automatically.
It works perfectly in a local machine, but the intent is for remote users to pull up the webpage and see the new image as I control the macro.
Here is the excel macro:
Sub update_image()
newName = "C:\Cases\Nominal\new_image_to_show.png"
oldName = "C:\Cases\Images\updated_image.png"
FileCopy newName, oldName
End Sub
When I replace the file locations with the web locations, the macro stops working. The web space is an internal location within my organization, and two options I tried were:
newName = "https:://location_of_content\Cases\Nominal\new_image_to_show.png"
oldName = "https:://location_of_content\Cases\Images\updated_image.png"
and
newName = "file://///location_of_content\Cases\Nominal\new_image_to_show.png"
oldName = "file://///location_of_content\Cases\Images\updated_image.png"
I also tried relative path nomenclature,
newName = ThisWorkbook.Path & "\Cases\Nominal\new_image_to_show.png"
but in both cases I get
Run Time Error '52'
Any ideas on how I can rename the paths? Or alternatives to Excel Macros?

Macro (VBA) in Excel is failing on colleagues PC but works on mine when colleague is logged in

I'm developing VBA tools to automate a series of long winded administration tasks, the code runs fine in the following circumstances.
When I am logged into my PC
When my colleague is logged into my PC
When I am logged into my colleagues PC
However it fails to complete correctly, when my colleague runs it on her PC.
The specific area it is failing in is:
'creates 2 dims for location of the two files that need opening based on the critera set on the home page
Dim newdata As String
newdata = Range("f11").Value
Dim olddata As String
olddata = Range("f12").Value
Dim fileextension As String
fileextension = Range("f14").Value
Dim fulllocationolddata As String
fulllocationolddata = Range("f13") & olddata & fileextension
Dim fulllocationnewdata As String
fulllocationnewdata = Range("f13") & newdata & fileextension
'open file containing OLDDATA c&p previous days data to the conversion tool
'then shuts the old data workbook
Workbooks.Open Filename:=fulllocationolddata
Workbooks(olddata).Activate
Worksheets("sheet1").Select
Range("A1").CurrentRegion.Copy
Workbooks("Stockfile Conversion Tool.xlsm").Activate
Sheets("OLD STOCK").Activate
Range("A3").Select
Selection.PasteSpecial
Workbooks(olddata).Activate
Worksheets("sheet1").Select
Workbooks(olddata).Close SaveChanges:=False
The final line (Workbooks(olddata).Close SaveChanges:=False) does not shut the workbook, then later in the macro I open another workbook of the same name but as it's already open it just activates the window and the rest of the code falls apart.
If anyone has any ideas where I'm going wrong it would be appreciated.
Thanks in advance for your assistance
Plan303
Making my comments to an answer here:
Whether Workbooks("Name of the Workbook") is working or not depends on the settings in System control - Folder Options - View - [ x ] Hide extensions for known file types.
If this is set, then Excel's file extensions .xlsx, .xlsm, ... are not visible in Explorer or other file listings. Only the file names of the Excel files are visible. If so, then Workbooks("Name of the Workbook") will work.
If Hide extensions for known file types is not set, then Excel's file extensions .xlsx, .xlsm, ... are visible in Explorer or other file listings. If so, then Workbooks("Name of the Workbook") will not work. Then only Workbooks("Name of the Workbook.xlsx"), giving the name and the extension, will work.
But Workbooks("Name of the Workbook.xlsx") will also work if Hide extensions for known file types is set. So using the full name inclusive extension should be preferred.
So for the concrete question:
If olddata only contains the name of the workbook and not the file extension then Workbooks(olddata) will only work if Hide extensions for known file types is set in Folder Options. It will fail, if that option is not set and the file extensions are visible in Explorer. But Workbooks("Stockfile Conversion Tool.xlsm") will always work independent of whether Hide extensions for known file types is set or not. So Workbooks(olddata & fileextension) should also always work if olddata only contains the name of the workbook and fileextension contains .xlsx for example.

Printing to PDF with correct file path and with correct file name

I have written a small macro that takes an daily Excel report and prints it to a specific printer (printing to PDF). When I run the macro, I am still missing the final steps. Running it as is, I still need to click the "save" button that pops up, and have to navigate to the correct file path. Is there a way to have it automatically hit the save button for me, and save the file into the correct folder (as seen in the code below)?
Sub printToPDF()
'declare variable for my file path
Dim filePath As String
'declare variable for my file name
Dim fileName As String
fileName = "Operations_Daily_Outage_Report_" & Format(Date, "yyyy-mm-dd")
filePath = "M:\Daily_Outage_Report\Active"
Worksheets("general_report").PageSetup.CenterVertically = False
ActiveWindow.SelectedSheets.PrintOut Copies:=1, ActivePrinter:="Foxit Reader PDF Printer"
End Sub
I think everyone is trying to give you answers that you can try out. I'm not sure why you can't just test it and tell us if it works for you?
If you have a reasonably new version of Access (within last 10 years), then you should be able to use the built-in Office PDF converter
Change this line:
ActiveWindow.SelectedSheets.PrintOut Copies:=1, ActivePrinter:="Foxit Reader PDF Printer"
To This:
Worksheets("general_report").ExportAsFixedFormat Type:=xlTypePDF _
FileName:=filePath & "\" & fileName Quality:=xlQualityStandard
Come back and tell us if it worked for you.