0

使用有效的代码更新问题:

我希望能够让一个 .xlsm 文件使用 VBA for Excel 将 csv 数据放入第二个 .xlsm 文件。后一个文件可能在多台计算机中打开。下面是 Excel 中一个按钮后面的代码,试图实现这一点:

Sub bad_boy()
Dim wb As Workbook, strFile As String, ws As Worksheet

Set wb = Workbooks.Open("C:\Temp\TestFolder\son1.xlsm") 'set to current worksheet name

Set ws = wb.ActiveSheet

strFile = Application.GetOpenFilename("Text Files (*.csv),*.csv", , "Please select text file...")

With ws.QueryTables.Add(Connection:="TEXT;" & strFile, Destination:=ws.Range("A1"))
     .TextFileParseType = xlDelimited
     .TextFileCommaDelimiter = True
     .Refresh
End With
End Sub

该代码应该使用户能够从他/她的计算机中浏览和选择一个 csv 文件。

4

2 回答 2

1

You have declared ws as a Worksheet object:

Dim ws As Worksheet, strFile As String

But you are attempting to assign it a Workbook object. This will always raise a mismatch error.

Set ws = Workbooks.Open("C:\Temp\TestFolder\son1.xlsm") 

Try changing that line to:

Dim wb as Workbook
Set wb = Workbooks.Open("C:\Temp\TestFolder\son1.xlsm")
Set ws = wb.ActiveSheet

Then remove the line Set ws = ActiveSheet

于 2013-08-23T14:29:05.847 回答
1

您正在尝试将工作表对象设置为等于字符串常量。这导致了错误消息。

于 2013-08-23T13:07:33.057 回答