从封闭的工作簿中复制单元格。

时间:2013-11-14 15:36:34

标签: excel excel-vba vbscript excel-2007 xlm vba

我正在尝试将数据从已关闭的工作簿中的单元格复制到另一个工作簿而不打开原始工作簿。

我已经显示的代码...工作但我需要能够将数据写入打开的工作簿上的某个单元格。

Private Function GetValue(path, file, sheet, ref)
'   Retrieves a value from a closed workbook
    Dim arg As String
'   Make sure the file exists
    If Right(path, 1) <> "\" Then path = path & "\"
    If Dir(path & file) = "" Then
        GetValue = "File Not Found"
        Exit Function
    End If
'   Create the argument
    arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
      Range(ref).Range("A1").Address(, , xlR1C1)
'   Execute an XLM macro
    GetValue = ExecuteExcel4Macro(arg)
End Function

Sub TestGetValue2()
    p = "F:\excel_Project"
    f = "Book1.xlsx"
    s = "Sheet1"
    a = "A1"
 GetValue(p, f, s, a) = ("A1")

End Sub

2 个答案:

答案 0 :(得分:1)

如果要将单元格的值设置为GetValue函数返回的任何值,则执行以下操作

Range("A1") = GetValue(p, f, s, a)

但是,您需要确保您的目的地(即您要写的地方GetValue)与GetValue的尺寸/尺寸相同。例如,如果GetValue是一个单元格,那么上面的内容将按预期工作。但是,如果GetValue是一个1x2范围的单元格并且您使用上述代码,则只会A1填充GetValue

中的值(第一个值)

答案 1 :(得分:0)

我需要从工作表单元格中存储的已关闭文件的动态列表中检索单元格。

在循环之外,我尝试使用公式来解决问题

这对我有用:

print(bool(0))

万一有人需要对文件列表做同样的事情...

Range("A1").Formula ="='F:\excel_Project\[Book1.xlsb]Sheet1'!$A1"