2017-03-27 63 views
1

正如你在下面看到的,我已經使用fileName作爲字符串變量,它在URL中使用。 當我運行代碼時,出現錯誤,提示 '運行時錯誤'-2147217376(80041020) 系統找不到指定的對象。' 實際上,我想將.cg文件中的數據複製到Excel中。 任何替代方法也可以。 請幫忙。是否可以在Excel VBA中使用字符串變量作爲URL?

「我的代碼

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 

回答

1

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

+0

您好好友感謝您的答覆,但串聯是在這一步完成fileName = Dir(目錄&「* .cg ??」) –

2

目錄變量和URL需要一些修正

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 
+0

你好巴迪謝謝你的解決方案,它的工作就像它想要的那樣。 –

相關問題