由于我是VBA的新手,所以我创建了一个代码,该代码可以打开.csv文件并将数据从.csv复制到excel文件,而无需同时打开这两个文件。
实际上它适用于excel文件,但是当我使用.csv文件时,它向我显示一条错误消息“ SUBSCRIPT OUT OF RANGE”。如何解决此问题?谢谢!
Sub Copywb1()
Dim wkb1 As Workbook
Dim sht1 As Worksheet
Dim wkb2 As Workbook
Dim sht2 As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
Setwkb1 = ThisWorkbook
Setwkb2 = Workbooks.Open("C:\Desktop\AAA.xlsx")
Setwkb1 = Workbooks.Open("C\Reports\BBB.csv")
Setsht1 = wkb1.Sheets("Reports")
Setsht2 = wkb2.Sheets("Fees")
sht1.Range("A1:BM9").Copy
sht2.Range("A1").PasteSpecial xlPasteValues
Application.CutCopyMode = False
wkb2.Close True
wkb1.Close True
End Sub
答案 0 :(得分:0)
这是我的一个工作示例,您应该能够轻松地适应您的需求:
Sub demo_loadDataFromCSV()
Const csvFile = "x:\mypath\myfile.csv"
Dim ws As Worksheet, csv As Workbook, cCount As Long, cName As String
' Application.ScreenUpdating = False 'keep these commented-out until...
' Application.DisplayAlerts = False ' ...done testing/troubleshooting!
Set ws = ThisWorkbook.ActiveSheet 'remember where we parked
Workbooks.Open csvFile 'open the csv
Set csv = ActiveWorkbook 'create object of csv workbook
cName = csv.Name 'get name of csv while its open
ActiveSheet.Columns("A:B").Copy 'copy columns A and B
ws.Activate 'go back to the first sheet
ws.Range("A1").PasteSpecial xlPasteValues 'paste values
cCount = Selection.Cells.Count 'count pasted cells
csv.Close 'close CSV
Application.DisplayAlerts = True 're-enable alerts
Application.ScreenUpdating = True 'resume screen updates
MsgBox cCount & " cells were copied from " & cName _
& " to " & ws.Parent.Name, vbInformation, "Done"
End Sub