我想知道的是为什么我引用范围的某些不同方式无法正常工作。需要说明的是,下面的代码并不完整,它更像是我最终要做的事情的踏脚石,但是在你走路之前,宝贝步骤,对吗?
如果有人能帮助我理解为什么最后几行代码不起作用,我将不胜感激。至于我对范围和细胞的理解,我认为它们应该。单击命令按钮后,子进程将从UserForm运行。
Option Explicit
Dim arrCatalogNum() As String
Dim strUserInput As String
Dim strCatNum As String
Dim rCatNum As Range
Dim rRow As Range
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim currRow As Long
Dim lastCol As Long
Sub GetCatalogArray()
'Assign value to strUserInput
strUserInput = UserForm1.Catalog_List.Value
'Make array arrCatalogNum() from strUserInput
arrCatalogNum = Split(strUserInput, ",")
MsgBox "GetCatalogArray: strUserInput is " & strUserInput
'Confirm bounds of the array
MsgBox "LBound and UBound of arrCatalogNum is " & LBound(arrCatalogNum) & " and " & UBound(arrCatalogNum) & ", respectively."
End Sub
Sub TransferCatalogInformation()
'Using ActiveWorkbook is tricky if you switch between different workbooks!
Set ws1 = ThisWorkbook.Worksheets(1)
Set ws2 = ThisWorkbook.Worksheets(2)
'Get index of the last column with data in it
lastCol = ws1.Cells.Find(What:="*", _
After:=ws1.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
MsgBox "TransferCatalogInformation: lastCol is " & lastCol
'Counter for For statement
Dim i As Integer
With ws1
For i = 0 To 0 'LBound(arrCatalogNum) To UBound(arrCatalogNum)
'Set the cell range of rCatNum
Set rCatNum = Range("A:A").Find(What:=arrCatalogNum(i))
'Assign the variable currRow a value
currRow = rCatNum.Row
'Set the range of rRow as the entire row up to the last column with data in it
Set rRow = Range(rCatNum, Cells(currRow, lastCol))
'Display what the cell address is
MsgBox "TransferCatalogInformation: rCatNum cell address is: " & rCatNum.Address
'Confirm what rRow range is
MsgBox "rRow range is " & rRow.Address
'Trying to copy from ws1 to ws2 of same workbook
rRow.Copy Destination:=ws2.Cells(currRow, 1) 'WORKS
rRow.Copy Destination:=ws2.Range("A1") 'WORKS
rRow.Copy Destination:=ws2.Range(rCatNum, Cells(currRow, lastCol)) 'DOES NOT WORK. I believe I know why.
rRow.Copy Destination:=ws2.Range(Cells(12, 1), Cells(12, 10)) 'DOES NOT WORK. I don't know why.
rRow.Copy Destination:=ws2.Range(Cells(currRow, 1), Cells(currRow, lastCol)) 'DOES NOT WORK. I don't know why.
Next i
End With
End Sub
答案 0 :(得分:0)
您正在使用ActiveSheet property的隐式引用,该引用可能是也可能不是 ws2 引用的工作表。
rRow.Copy Destination:=ws2.Range(rCatNum, Cells(currRow, lastCol))
'should be
rRow.Copy Destination:=ws2.Range(rCatNum, ws2.Cells(currRow, lastCol))