将单元格中的信息插入代码

Inserting information from a cell into code

我一直在处理一个电子表格,我想要一个 VBA 代码来打开一个文档,现在这个文档可以是一个 word 或 excel 文档,但我想要代码使用来自单元格的信息。

Function FnPrint()
  Dim objWord
  Dim objDoc
  
  Set objWord = CreateObject("Word.Application")
  Set objDoc = objWord.Documents.Open("Y:\Master Documents\Sheet & Cut\W19-316 Allergen cleandown S&C line.docx")

  objWord.Visible = True
  objDoc.PrintOut
  objWord.Quit
End Function

这就是我的代码,现在它说 "Y:\Master Documents\Sheet & Cut\W19-316 Allergen cleandown S&C line.docx",我希望它根据特定的单元格实际改变,您可以在上图中看到。这是因为该单元格会根据在其他框中输入的变量而变化。

有什么想法吗?

..to open a document, now this document could be either a word or excel document

逻辑:

检查单元格中文件路径的文件扩展名,然后决定是否要打开 Excel 或 Word。

代码(未测试):

Option Explicit

Sub Sample()
    Dim rngDocInfo As Range
    Dim objApp As Object, objDoc As Object
    Dim myPath As String

    '~~> Change this to relevant sheet and cell which has the path        
    Set rngDocInfo = Sheet1.Range("O18")
    myPath = UCase(rngDocInfo.Value2)

    If Len(Dir(myPath)) = 0 Then
        MsgBox "Invalid filename. File does not exist"
        Exit Sub
    End If
    
    '~~> Get file extension and check if it is an Excel document
    If Right(myPath, Len(myPath) - InStrRev(myPath, ".")) Like "XLS*" Then
        Set objApp = CreateObject("Excel.Application")
        Set objDoc = objApp.Workbooks.Open(rngDocInfo.Value2)
        objApp.Visible = True
        
        '
        ' Rest of the code
        '
    '~~> Get file extension and check if it is a Word document
    ElseIf Right(myPath, Len(myPath) - InStrRev(myPath, ".")) Like "DOC*" Then
        Set objApp = CreateObject("Word.Application")
        Set objDoc = objApp.Documents.Open(rngDocInfo.Value2)
        objApp.Visible = True
        
        '
        ' Rest of the code
        '
    Else
        MsgBox "Unknown Document type"
    End If
End Sub

注意:我在上面的代码中没有处理Text/Csv个文件。如果你可以拥有这些文件类型,那么相应地修改上面的代码。