过去两周我沉浸在VBA中。它很棒,但自从上周以来我一直在努力解决以下错误: " VBA方法'对象范围' _Worksheet失败" 用这行代码:
wsSource.Range(Cells(7, ColumnNr), Cells(lrowSource, ColumnNr)).Copy
我无法找到解决方案。
这是整个VBA代码:
Sub CopyColums()
Application.ScreenUpdating = False
cPath = "H:\2017\"
ChDrive cPath
ChDir cPath
cFile = Application.GetOpenFilename("Excel files (*.xls*), *.xls*")
Workbooks.Open cFile, UpdateLinks:=3, ReadOnly:=False, Notify:=False, Password:="****"
Dim wsSource As Worksheet
Dim wsTarget As Worksheet
Dim lrowSource As Integer
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "import"
Set wsSource = Sheets(1)
Set wsTarget = Sheets("import")
wsTarget.Range("A1").Value = "header 1"
wsTarget.Range("B1").Value = "header 2"
wsTarget.Range("C1").Value = "header 3"
wsTarget.Range("D1").Value = "header 4"
wsTarget.Range("E1").Value = "header 5"
wsTarget.Range("F1").Value = "header 6"
wsTarget.Range("G1").Value = "header 7"
wsTarget.Range("H1").Value = "header 8"
wsTarget.Range("I1").Value = "header 9"
wsTarget.Range("J1").Value = "header 10"
wsTarget.Range("K1").Value = "header 11"
wsTarget.Range("L1").Value = "header 12"
wsTarget.Range("M1").Value = "header 13"
wsTarget.Range("N1").Value = "header 14"
lrowSource = wsSource.Cells(Rows.Count, "A").End(xlUp).Row
'A to A
wsTarget.Range("A2:A" & lrowSource - 5).NumberFormat = "d-m-yy;@"
wsSource.Range("A7:A" & lrowSource).Copy
wsTarget.Range("A2").PasteSpecial xlPasteValues
'E to B
wsSource.Range("E7:E" & lrowSource).Copy
wsTarget.Range("B2").PasteSpecial xlPasteValues
'F to C
wsSource.Range("F7:F" & lrowSource).Copy
wsTarget.Range("C2").PasteSpecial xlPasteValues
'O to D
wsSource.Range("O7:O" & lrowSource).Copy
wsTarget.Range("D2").PasteSpecial xlPasteValues
'Look for column and copy to I
ColumnNr = Application.Match("Total partner", Sheets(1).Rows(6), 0)
wsSource.Range(Cells(7, ColumnNr), Cells(lrowSource, ColumnNr)).Copy
wsTarget.Range("I2").PasteSpecial xlPasteValues
Application.CutCopyMode = False
'Save as CSV
NameImportFile= Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 5) 'to remove .xlsx
Filepath = cPath & NameImportFile& ".csv"
ActiveWorkbook.SaveAs Filename:=Filepath, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
End Sub
有人可以帮帮我吗?
亲切的问候, 理查德
答案 0 :(得分:2)
我猜测该行执行时if((cin >> a).good())
无效。
如果是这种情况,那么Sheets(1)
指向wsSource
而Sheets(1)
不符合其正在使用的工作表,因此它正在使用当前活动的工作表。
尝试使用:
Cells
。
作为编辑(接受答案后)我可能会改写程序:
wsSource.Range(wsSource.Cells(7, ColumnNr), wsSource.Cells(lrowSource, ColumnNr)).Copy