将字符串分配给对象时出错

时间:2015-04-02 06:20:49

标签: excel vba

我正在尝试使用名称为Division_Application_Partner.xlsx的d:\文件夹中搜索文件,其中Division Application和Partner是包含字符串值的变量。

这是我给出的代码:

Set WorkbookPath = Dir(path & Division + "_" + Application + "_" + TradingPartner + ".xlsx")`enter code here`

它抛出一个错误,说“编译错误:输入Mismtach”

文件的名称是错误的

以下是代码:

Dim WorkbookPath As WorkBook
Dim path as String
Division = Range("C11").Value
Application = Range("C15").Value
TradingPartner = Range("C19").Value
path = "d:\"

'MsgBox (path)
'MsgBox (Division)
'MsgBox (Application)
MsgBox (TradingPartner)


  If Len(Dir(path & Division & "_" & Application & "_" & TradingPartner & ".xlsx")) = 0 Then

  Set  WorkbookPath = Division & "_" & Application & "_" & TradingPartner & ".xlsx"



  End If

我尝试连接使用&像你建议的那样。它仍显示相同的错误。

3 个答案:

答案 0 :(得分:0)

我首先将&专门用于字符串连接。 +的使用主要用于添加数字,但可以连接字符串。但是,当使用option strict等时,有各种各样的注意事项,所以你最好不要使用预期的内容。

你应该做的另一件事是在尝试连接或传递给Dir之前输出所有这些变量。类似的东西:

MsgBox "[" & path & "]"

也为所有其他人重复。输出可能很好地指出问题。

答案 1 :(得分:0)

您尝试将字符串分配给对象,这就是您收到错误的原因

  

Dim WorkbookPath As WorkBook

更好的尝试

Dim myWkb as Workbook 
Set myWkb = Workbooks.Open(your_concat_string)

并且不要使用保留字

  

应用

最后

Sub test()
Dim wkbExternWorkbook As Workbook
Dim strPath As String
Dim strDivision As String, strApplication As String, strTradingPartner As String

strDivision = Range("C11").Value
strApplication = Range("C15").Value
strTradingPartner = Range("C19").Value
strPath = "D:\"

If Len(Dir(strPath & strDivision & "_" & strApplication & "_" & strTradingPartner & ".xlsx")) <> 0 Then
    Set wkbExternWorkbook = Workbooks.Open(strPath & strDivision & "_" & strApplication & "_" & strTradingPartner & ".xlsx")
End If

End Sub

答案 2 :(得分:0)

试试这个:

Sub test()
Dim application As Variant
Dim division As Variant
Dim WorkbookPath As String
Dim tradingpartner As Variant
Dim path As String
division = Range("C11").Value
application = Range("C15").Value
tradingpartner = Range("C19").Value
path = "d:\"

'MsgBox (path)
'MsgBox (Division)
'MsgBox (Application)
MsgBox (tradingpartner)

If Len(Dir(path & division & "_" & application & "_" & tradingpartner &   ".xlsx")) = 0 Then
    Workbooks.Add
    ActiveWorkbook.SaveAs division & "_" & application & "_" & tradingpartner & ".xlsx"
End If
End Sub

首先添加工作簿,然后使用创建的名称保存它。