VB macro - run-time error '13' on for each loop
i know there might have been questions like this. But i'm really unfamiliar with VB, so i need help please. Here is the part of the code:
Sub Convert_to_Digi()
Dim SrcWkb As Workbook
Dim csvWkb As Workbook
Dim srcSheet As Worksheet
Dim StartRow As开发者_运维百科 Long
Dim wkbname As Variant
Dim xlsFiles As Variant
Dim MyRange As Range
Dim NewName As Variant
Dim csvName As String
StartRow = 2
' Get the workbooks to open
xlsFiles = Application.GetOpenFilename(FileFilter:="Excel files (*.xls), *.xls", MultiSelect:=True)
If VarType(xlsFiles) = vbBoolean Then Exit Sub
' Loop through each workbook and copy the data to this CSV
For Each wkbname In xlsFiles
Set SrcWkb = Workbooks.Open(Filename:=wkbname, ReadOnly:=False)
Set srcSheet = SrcWkb.Worksheets("export_label_conf")
' Get used range on sheet
Set MyRange = srcSheet.UsedRange
' Adjust to exclude top row
Set MyRange = MyRange.Offset(1, 0).Resize(MyRange.Rows.Count - 1)
NewName = srcSheet.Cells(2, 10) & ".csv"
If MyRange.Row + MyRange.Rows.Count - 1 >= StartRow Then
Set csvWkb = Workbooks.Open(Filename:="C:\DIGITAL\template.csv", ReadOnly:=False)
' copy column A
MyRange.Columns(1).Copy
' paste into CSV template file, column I
csvWkb.ActiveSheet.Cells(2, 9).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
' and save template as new CSV with barcode as name
csvName = "C:\DIGITAL\" & NewName
csvWkb.SaveAs Filename:=csvName, FileFormat:=xlCSV, CreateBackup:=False
End If
SrcWkb.Close
Next wkbname
End Sub
i get this error on For Each wkbname In xlsFiles line. wkbname is empty, while xlsFiles contains name of a file to open (but only 1, while it should have few...)
and only a short while ago it was working fine! i undone all i could remember i done, but didn't solve the problem....
I'd suggest you to do as follows:
- Try compile your code. Sounds dummy, but might point a problem somewhere else that could be impacting in this piece of code.
- Change the variable names. If there's an Excel problem happening for any reason (variant confusion) it could solve the problem.
- Check the project's References. If there's a missing reference, VBA doesn't work as usual.
Just tried the below code here and worked fine... and it's pretty much the same as yours (besides variable names).
Public Sub OpenExcelFiles()
Dim vFiles As Variant
Dim vFile As Variant
Dim oXLFile As Excel.Workbooks
vFiles = Application.GetOpenFilename(FileFilter:="Excel files (*.xls), *.xls", MultiSelect:=True)
If VarType(xlsFiles) = vbBoolean Then Exit Sub
For Each vFile In vFiles
Set oXLFile = Workbooks.Open(vFile)
Next vFile
End Sub
精彩评论