我正在做一个从另一个文件中的某些列中提取数据的宏。我遇到了
的错误消息类型不匹配
在第Set row = Columns("O,Q,W")
行我知道这是不正确的,我也尝试过使用Union,但这也无效。
Sub ImportDatafromotherworksheet()
Dim wkbCrntWorkBook As Workbook
Dim wkbSourceBook As Workbook
Dim rngSourceRange As Range
Dim rngDestination As Range
Dim row As Range
Dim row1 As Integer
Dim hello As Range
Dim hello1 As Range
Dim lastRow As Long, i As Long
Dim CopyRange As Range
Set wkbCrntWorkBook = ActiveWorkbook
With Application.FileDialog(msoFileDialogOpen)
.Filters.Clear
.Filters.Add "Excel 2007-13", "*.xlsx; *.xlsm; *.xlsa"
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
Workbooks.Open .SelectedItems(1)
Set wkbSourceBook = Workbooks.Open(.SelectedItems(1))
With wkbSourceBook.Worksheets(1)
lastRow = .Range("A" & .Rows.Count).End(xlUp).row
For i = 4 To lastRow
If Len(Trim(.Range("A" & i).Value)) <> 0 Then
If CopyRange Is Nothing Then
Set CopyRange = .Rows(i)
Else
Set CopyRange = Union(CopyRange, .Rows(i))
Set row = Columns("O,Q,W")
End If
End If
Next
If Not CopyRange Is Nothing Then
wkbCrntWorkBook.Activate
Set rngDestination = Application.InputBox(Prompt:="Select destination cell", Title:="Select Destination", Default:="A1", Type:=8)
row.Copy rngDestination
rngDestination.CurrentRegion.EntirdoeColumn.AutoFit
wkbSourceBook.Close False
'~~> Change Sheet2 to relevant sheet name
End If
End With
End If
End With
End Sub
答案 0 :(得分:1)
使用此:
Set MyRange = Union(Columns(1), Columns(4))
将立即捕获多个列
答案 1 :(得分:0)
你不能那样使用Columns()
。同时避免使用Row
作为变量。这是一个保留字。
将其更改为
Set rw= .Range("O:O,Q:Q,W:W")
或者像@KKowalczyk建议的那样
Set rw = Union(.Columns(15), .Columns(17), .Columns(23))
忘了提一下,请同样限定你的细胞对象。注意它们之前的点?如果你不这样做,那么他们将解决Activesheet
,这可能是你真正认为的表格,也可能不是。{/ p>