VBA userform从sheet获取文件路径

时间:2016-04-17 06:18:20

标签: vba excel-vba excel

我有一个用户表单,我需要将信息发送到多个工作簿,这很好。

然而,这些工作簿每月都会更改,我想将文件路径放在一个单元格中并在我的代码中进行更改,以便不需要每月更改代码。只是单元格中的文件路径。 谢谢您的帮助!

Dim wb As Workbook
            Dim ws As Worksheet

                Set wb = Workbooks.Open(Filename:="Link1")
                    Set ws = wb.Worksheets("Sheet test")



                    ws.Cells(2, 3).Value = Me.T1.Value
                    ws.Cells(2, 4).Value = Me.T2.Value
                    ws.Cells(2, 5).Value = Me.T3.Value
                    ws.Cells(2, 6).Value = Me.T4.Value
                    ws.Cells(2, 7).Value = Me.T5.Value
                    ws.Cells(2, 8).Value = Me.T6.Value
                    ws.Cells(2, 9).Value = Me.T7.Value

1 个答案:

答案 0 :(得分:2)

如果单元格只有文件路径(Ex: C:\Temp\),请使用此

Sub Sample()
    Dim wb As Workbook
    Dim flName As String, flPath As String

    '~~> Let's say the path is in Cell A1 of Sheet1
    '~~> Change as applicable
    flPath = ThisWorkbook.Sheets("Sheet1").Range("A1").Value

    If Right(flPath, 1) <> "\" Then flPath = flPath & "\"

    '~~> This is the file name
    flName = "Sample.xlsx"

    Set wb = Workbooks.Open(Filename:=flPath & flName)

    With wb
        '~~> Do your stuff
    End With
End Sub

如果单元格有文件名和路径(Ex: C:\Temp\MyFile.xlsx),那么使用此

Sub Sample()
    Dim wb As Workbook
    Dim flName As String

    '~~> Let's say the name & path is in Cell A1 of Sheet1
    '~~> Change as applicable
    flName = ThisWorkbook.Sheets("Sheet1").Range("A1").Value

    Set wb = Workbooks.Open(Filename:=flName)

    With wb
        '~~> Do your stuff
    End With
End Sub