简单的VBA投掷对象错误1004

时间:2017-07-05 14:40:47

标签: excel vba excel-vba

循环遍历每个工作表并插入VLOOKUP公式(引用已关闭的工作簿)。代码将从第一个工作表开始,查找并打开相应的工作簿,然后执行VLOOKUP,然后执行下一个工作表/相应的工作簿。一切正常,直到我点击.Cells,这是我遇到对象错误。我错过了什么?我从原始工作簿运行此宏,然后打开外部工作簿

For Each ws In ThisWorkbook.Worksheets
    If (ws.Name <> "Sheet1") And (ws.Name <> "Sheet2") Then
        Set wbPath2 = Workbooks.Open("C:\MyDirectory\MyFile1.csv") 
        sourceSheet = "[MySheet.csv]"

        With ws
            .Cells(Application.WorksheetFunction.Match("Account1", .Range("A:A"), 0), Application.WorksheetFunction.Match(ComboBox1.Value & " " & Year(Date), .Range("A6:BZ6"), 0)).Formula = "=VLOOKUP(""Account1 Service"",'" & Root & sourceSheet & ws.Name & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$A:$G,4,FALSE)"

2 个答案:

答案 0 :(得分:0)

对象似乎是ComboBox1.Value。 在表格代码中,可以使用组合框。但在模块中,这是不可能的。所以使用obleObject和链接单元格。并获得单元格值。

Dim ws As Worksheet
Dim obj As OLEObject
Dim strCombo As String
For Each ws In ThisWorkbook.Worksheets
    If (ws.Name = "Sheet1") Or (ws.Name = "Sheet2") Then
    Else
        Set wbPath2 = Workbooks.Open("C:\MyDirectory\MyFile1.csv")
        sourceSheet = "[MySheet.csv]"

        With ws
            k = .Name
            Set obj = .OLEObjects("ComboBox1")
            obj.LinkedCell = "q1" 'your  blank cell link ; this link "q1" cell
            strCombo = .Range("q1")
            .Cells(Application.WorksheetFunction.Match("Account1", .Range("A:A"), 0), Application.WorksheetFunction.Match(strCombo & " " & Year(Date), .Range("A6:BZ6"), 0)).Formula = "=VLOOKUP(""Account1 Service"",'" & Root & sourceSheet & ws.Name & " " & monthNumber & "." & lastDay & "." & Format(Now(), "yy") & "'!$A:$G,4,FALSE)"
            .Range("q1").Clear
        End With
    End If

Next

答案 1 :(得分:0)

事实证明我忘了在我的文件路径指针中连接一些东西。感谢@Jordan的调试技巧。