I have some code in VBA on Microsoft Word, I just want to save some text as a file in a specific folder.
Here's the relevant part of code (not including the rest as its all spaghetti code that doesn't even reference TextBox3 at all):
Dim foldername As String
foldername = TextBox3.Text
Dim Fileout As Object
Set Fileout = fso.CreateTextFile("C:\Users\JaneDoe\Desktop\" & foldername & "\" & myValue & ".html", True, True)
Fileout.Write finaltext
Fileout.Close
This code ONLY doesn't work when it references TextBox3.Text, if I change that to "testing123" it works perfectly, but I need to use the text from TextBox3
The error I'm getting is:
Run-time error '424':
Object required
And it references this line:
foldername = TextBox3.Text
Any and all help is greatly appreciated, do keep in mind I'm a bit of a noob to VBA though so yeah :)
Related
I am trying to do a very simple routine with SendKeys method in VBA to automate opening an app.
The problem is when I try to open a .exe ou .Ink (shortcut) file. The VBA compilation stops and the following message appears "Some files contain viruses that can be harmful to your computer...."
After that I need to select "Ok" or "Cancel" and the aplication doesn't work properly.
I researched a lot but couldn't find any solution. Are there any way to make the message not appear?
I have Windows 10 Home Single Language, Microsoft 365, Excel Version 2107.
See below the code please (The warning message appears in the line "SendKeys (strFile)"):
Sub Ligacao()
Dim strOrigem As String
Dim strExtensao As String
Dim strFile As String
Application.DisplayAlerts = False
strOrigem = ThisWorkbook.Path & "\"
strExtensao = ".lnk"
strFile = Dir(strOrigem & "*" & strExtensao)
Do While strFile <> ""
If Mid(strFile, 1, 3) = "Hat" Then
SendKeys (strFile)
End If
Loop
End Sub
I have VBA that, along with a whole lot of other stuff, saves an excel workbook to SharePoint (enterprise 2010 I think) and it works fine most of the time but every once in while, when a user runs the VBA, the Excel freezes with a pop up showing "Getting list of available content types and properties...". If the user selects cancel another pop up come up "Run-time error '1004': Method 'SaveAs' of object '_Workbook' failed. If the user selects 'Debug' the last line of VBA is highlighted as creating the error.
Dim fileName As String
Dim excelDirName As String
fileName = [c9]
excelDirName = [c16] & "/"
ThisWorkbook.SaveAs excelDirName & fileName & ".xls"
Since this works sometimes (and it worked for over 6 months without this happening) and not other times I am not sure what it could be and I am thinking something was updated in SharePoint.
I would write it a bit differently, so as to make it more robust:
With SomeSpecificSheet
Dim path As String
path = .Range("SavePath").Value
Dim fileName As String
fileName = .Range("SaveFileName").Value
End With
Debug.Assert Trim(path) <> vbNullString
Debug.Assert Trim(fileName) <> vbNullString
Dim savePath As String
savePath = path & "/" & fileName
ThisWorkbook.SaveAs savePath
Note:
Be explicit about the worksheet you're reading from - you're currently reading from whatever the active sheet is, and unless every single worksheet in ThisWorkbook has the expected values in $C$9 and $C$16, that's asking for trouble.
Use named ranges, so that if a user inserts a column before column C or a row before row 9, your code still refers to the correct cells.
Let SaveAs determine the file's extension.
Use Debug.Assert to verify assumptions (and break before you freeze). Alternatively, you can explicitly validate the values, for example:
If path = vbNullString Or fileName = vbNullString Then
MsgBox "I need a path!"
Exit Sub
End If
I have written a macro which when a file is created and the little save button is clicked the macro is triggered(as it overrides the default FileSave function). The macro extracts information from a table in my document, converts it to a string then cleanses that string of any carriage returns then uses that as the file name. An if statement then runs checking whether a hidden row in the table has a value of 1 and if not then it will set the value to 1 and save the document at the location specified with the new filename.
All of this works great except when I re-open the file to edit it, as my users will do, and click save again it tries to run everything again, completely ignoring my If statements first statement and will add a carriage return to the start of the filename effectively breaking the save function to SharePoint as it has an invalid character in it. If you then click save again it will seemingly run the macro as normal and save it by actually reading the if statement correctly. Am I doing something wrong here?
Here is the code:
Sub FileSave()
Dim strText As String
Dim strClean As String
Dim strFileName As String
Dim strLocation As String
Dim strSavedName As String
Dim strCleanSave As String
strText = ActiveDocument.Tables(1).Rows(1).Cells(2).Range.Text
strClean = Application.CleanString(strText)
strFileName = strClean + "_" + Format(Date, "yyyy-mm-dd")
strLocation = "[My SharePoint Site]"
If ActiveDocument.Tables(1).Rows(1).Cells(3).Range.Text = "1" Then
strSavedName = ActiveDocument.Name
strCleanSave = Application.CleanString(strSavedName)
ActiveDocument.SaveAs FileName:=strSavedName
Exit Sub
Else
ActiveDocument.Tables(1).Rows(1).Cells(3).Range.Text = "1"
ActiveDocument.SaveAs FileName:=strLocation & strFileName & ".docx"
End If
End Sub
Word table cell text ranges are terminated with two hidden chars, a carriage return (ASCII 13) and a bell (ASCII 7). Your IF condition returns false because it is testing the equivalence of "1" and "1" & Chr(13) & Chr(7).
In your case you can limit the test to the first char:
If Left$(ActiveDocument.Tables(1).Rows(1).Cells(3).Range.Text, 1) = "1" Then
More generally you can test the visible cell contents with a Len() - 2.
Hope that helps.
Right now I have a Word Document with the following text:
FullName
Position
Address
Each line is made as a separate bookmark. The bookmark name for each line is the same as the word (the bookmark for FullName is FullName).
When I iterate through the bookmarks and update the text of the three different bookmarks, the first two get deleted and I am just left with the address. I think some how the bookmarks are getting combined in the editing process somehow.
Here is the code I have:
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "Word|*.docx"
saveFileDialog1.Title = "Save your report file"
Dim FilePath = "C:\Users\Administrator.Laptop1\Desktop\TESTER.docx"
Dim myWordDoc As Microsoft.Office.Interop.Word.Document
Dim myWordApp As Microsoft.Office.Interop.Word.Application
Dim filepathname As Object = TryCast(FilePath, Object)
Dim missing As Object = Type.Missing
Dim objTrue As Object = TryCast(True, Object)
' create Word.Application object for the document
myWordApp = New Microsoft.Office.Interop.Word.Application
' open the document
myWordDoc = myWordApp.Documents.Open(filepathname, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing)
'update Opinion
myWordDoc.Bookmarks("SendDate").Range.Text = (Convert.ToDateTime(TextBox7.Text)).ToString("MMMM dd, yyyy")
myWordDoc.Bookmarks("FullName").Range.Text = TextBox4.Text & " " & TextBox5.Text & " " & TextBox6.Text & vbLf
myWordDoc.Bookmarks("Position").Range.Text = TextBox8.Text & vbLf
Instead of using Interop services and bookmarks to accomplish this, you should consider using DocumentFormat.OpenXml.Wordprocessing and simple replacements.
Its more stable and behaves better, doesn't hang word.
You could simply loop through the documents body descendants for things like "{FirstName}" and do replacements, rather than using bookmarks which may always haunt you.
I'm hoping for a bit of a sanity check. I'm adapting a Word add-in (written in VBA for Word 2010) for Mac, specifically, at this point, Word 2011. I'm aware of many of the differences, but one that I haven't been able to find much documentation on is the apparent lack of FileDialog. The closest I've come to an answer is here: http://www.rondebruin.nl/mac.htm where the author uses Application.GetOpenFilename. That method doesn't seem to exist for Word, though (the focus of that site is Excel).
Does anyone know how to use the file and folder picker dialogs that FileDialog makes available? I'm not familiar with Applescript, really, but I've had to learn a little in order to get around Word 2011's funky file management issues (Dir, FileCopy, etc.). So, if that's the answer, any sense of what the code might look like in Applescript would be greatly appreciated. (I more or less know how to translate that into VBA).
I believe you have to use Apple Script in order to do this a bit better on the Mac. The following code allows the user to select text files which is returned as an array from the function. You would simply be able to modify the Apple Script to return other file types and select directories, I'll leave that to you.
The code that calls the function and displays a message box with all the files:
Sub GetTextFilesOnMac()
Dim vFileName As Variant
'Call the function to return the files
vFileName = Select_File_Or_Files_Mac
'If it's empty then the user cancelled
If IsEmpty(vFileName) Then Exit Sub
'Loop through all the files specified
For ii = LBound(vFileName) To UBound(vFileName)
MsgBox vFileName(ii)
Next ii
End Sub
And the function that does the Apple Script work:
Function Select_File_Or_Files_Mac() As Variant
'Uses AppleScript to select files on a Mac
Dim MyPath As String, MyScript As String, MyFiles As String, MySplit As Variant
'Get the documents folder as a default
On Error Resume Next
MyPath = MacScript("return (path to documents folder) as String")
'Set up the Apple Script to look for text files
MyScript = "set applescript's text item delimiters to "","" " & vbNewLine & _
"set theFiles to (choose file of type " & " {""public.TEXT""} " & _
"with prompt ""Please select a file or files"" default location alias """ & _
MyPath & """ multiple selections allowed true) as string" & vbNewLine & _
"set applescript's text item delimiters to """" " & vbNewLine & _
"return theFiles"
'Run the Apple Script
MyFiles = MacScript(MyScript)
On Error GoTo 0
'If there are multiple files, split it into an array and return the results
If MyFiles <> "" Then
MySplit = Split(MyFiles, ",")
Select_File_Or_Files_Mac = MySplit
End If
End Function
Finally, it can be a bit of a pain specifying different file types, if you want to specify only Word documents, then replace public.TEXT with com.microsoft.word.doc, however this won't allow .docx or .docm files. You need to use org.openxmlformats.wordprocessingml.document and org.openxmlformats.wordprocessingml.document.macroenabled respectively for these. For more info on these see: https://developer.apple.com/library/mac/#documentation/FileManagement/Conceptual/understanding_utis/understand_utis_conc/understand_utis_conc.html