我有一個 word 檔案,它允許我們合并來自在線資料庫的資訊。我正在嘗試創建一個宏,該宏將獲取特定表格單元格中的值,并使用該值將檔案保存在特定目錄中。
我不精通 VBA,但嘗試通過從其他資源(例如此處)復制代碼來了解其他人所做的事情。
我找到了允許我選擇正確單元格的代碼,并且我能夠讓它作業。
我找到了其他代碼來保存檔案,并嘗試修改它以包含單元格值作為檔案名。
Sub SaveAsCellContent()
Dim Invoice As String
Dim directory As String
Invoice = ActiveDocument.Tables(1).Cell(2, 5)
directory = "D:\Dropbox (DRYBSMT)\~ DB Forms\Word Saves\"
wordApp.DisplayAlerts = False
WordDoc.SaveAs FileName = DIR & INV & ".docx", FileFormat:=wdFormatDocumentDefault
WordDoc.Close
wordApp.Quit
Set WordDoc = Nothing
Set wordApp = Nothing
End Sub
如所寫,我收到錯誤“編譯錯誤:型別不匹配”。
我花了好幾個小時試圖解決這個問題,我認為現在是尋求專家幫助的時候了。
我現在擁有的,它正在作業:
Sub SaveAsCellContent()
Dim Invoice As String
Dim Directory As String
Invoice = ActiveDocument.Tables(1).Cell(2, 5).Range.Text
Invoice = Left(Invoice, Len(Invoice) - 2)
Directory = "D:\Dropbox (DRYBSMT)\~ DB Forms\Word Saves\"
ActiveDocument.SaveAs Filename:=Directory & Invoice & "i.docx", fileformat:=wdFormatXMLDocument
End Sub
但我被告知我需要添加 Debug.Print。這就是我現在所處的位置。
uj5u.com熱心網友回復:
我在下面的作業代碼示例中包含了上述所有注釋,包括添加示例錯誤處理程式和 debug.print 陳述句,該陳述句將構建目錄 檔案名列印到立即(除錯)視窗。
Sub SaveAsCellContent()
Dim Invoice As String
Dim directory As String
' Get the filename that is in the 1st table in the document
Invoice = ActiveDocument.Tables(1).Cell(1, 1).Range.Text
' so the Invoice string is always at least 2 characters long
' because a cell's value contains the cell boundary characters
' remove the cell boundary characters as they cannot be used for the file name
Invoice = Left(Invoice, Len(Invoice) - 2)
' no file name specified
If Len(Invoice) = 0 Then
Invoice = "default filename"
End If
' build the directory filename to use in the saveas
directory = "D:\Dropbox (DRYBSMT)\~ DB Forms\Word Saves\"
' adding the file extension .docx is not needed
' is determined by the FileFormat parametes
Dim fileNm As Variant
fileNm = directory & Invoice
' print to the Immediate window for testing purposes
Debug.Print ("File name: " & fileNm)
On Error GoTo saveError
ActiveDocument.SaveAs FileName:=fileNm,
FileFormat:=WdSaveFormat.wdFormatDocumentDefault
saveError:
If Err.Number > 0 Then
MsgBox ("Some error occurred:" & vbCrLf & Err.Number)
End If
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/394320.html
