是否可以在excel VBA中使用字符串变量作为URL?

时间:2017-03-27 12:11:04

标签: excel vba

如下所示,我使用fileName作为字符串变量,在URL中使用。 当我运行代码时,我得到一个错误说明 '运行时错误'-2147217376(80041020) 系统找不到指定的对象。 实际上,我想将.cg文件中的数据复制到Excel。 任何替代方法也会这样做。 请帮忙。

'我的代码

Sub ImportCG()

Dim directory As String, fileName As String

   directory = "D:\CG FILE"
  fileName = Dir(directory & "*.cg??")

ActiveWorkbook.Worksheets.Add
   ActiveWorkbook.XmlImport Url:= _
        "D:\CG FILE\filename" _
        , ImportMap:=Nothing, Overwrite:=True, Destination:=Range("$A$1")

     'Add CG_List
    Set NewSheet = Sheets.Add(Type:=xlWorksheet)
    ActiveSheet.Name = "CG_List"

    'Copy contents to Component Type List
    Columns("D:D").Select
    Selection.Copy
    Sheets("ComponentTypeList").Select
    Columns("A:A").Select
    ActiveSheet.Paste
    Sheets("CG_List").Select
    ActiveWindow.ScrollColumn = 2
    ActiveWindow.ScrollColumn = 3
    Columns("G:G").Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("ComponentTypeList").Select
    Columns("B:B").Select
    ActiveSheet.Paste
    Range("B15").Select

End Sub

2 个答案:

答案 0 :(得分:2)

您的目录变量和网址需要一些更正

Sub ImportCG()

Dim directory As String, fileName As String

   directory = "D:\CG FILE\"
  fileName = Dir(directory & "*.cg??")

ActiveWorkbook.Worksheets.Add
   ActiveWorkbook.XmlImport Url:= _
        directory & filename _
        , ImportMap:=Nothing, Overwrite:=True, Destination:=Range("$A$1")

     'Add CG_List
    Set NewSheet = Sheets.Add(Type:=xlWorksheet)
    ActiveSheet.Name = "CG_List"

    'Copy contents to Component Type List
    Columns("D:D").Select
    Selection.Copy
    Sheets("ComponentTypeList").Select
    Columns("A:A").Select
    ActiveSheet.Paste
    Sheets("CG_List").Select
    ActiveWindow.ScrollColumn = 2
    ActiveWindow.ScrollColumn = 3
    Columns("G:G").Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("ComponentTypeList").Select
    Columns("B:B").Select
    ActiveSheet.Paste
    Range("B15").Select

End Sub

答案 1 :(得分:1)

"D:\CG FILE\" & filename你需要连接2