我在一个工作簿上创建了一个按钮,用于打开另一个无宏工作簿。 transposeDataMatrices
是将在打开的工作簿中的工作表上运行的子项:
Private Sub CommandButton21_Click()
Set BEEBook = ThisWorkbook
FileSelect = Application.GetOpenFilename(FileFilter:="Excel Files (*.xl*), *.xl*", Title:="Please select the report to import")
If FileSelect = "False" Then Exit Sub
Set ReportBook = Workbooks.Open(FileSelect)
transposeDataMatrices
End Sub
在transposeDataMatrices
中,以下是严重截断的代码(ReportBook
是trasposeDataMatrices
中正在处理的工作簿的全局变量; cArray
是全局数组):
Public Sub transposeDataMatrices()
ReportBook.Activate
rowCounter = finWkst.UsedRange.Rows.Count
For ii = 1 To wsCount
Worksheets(ii).Activate
pullModelData (ii) ' just pulls some data, off ii worksheet in ReportBook
ReDim indexIDArray(0 To 504) As Integer
Dim j as Integer: j = 0
For Each catName In cArray
Dim totRange As Range
Set catTitle = Worksheets(ii).UsedRange.Find(catName)
If Not catTitle Is Nothing Then
catTitle.Offset(2, 0).Offset(0, 1).Select
ReportBook.Worksheets(ii).Range(Selection, Selection.End(xlToRight).Offset(0, -1)).Select
ReportBook.Worksheets(ii).Range(Selection, Selection.End(xlDown)).Select
Set totRange = Selection
Else
Set totRange = Cells("A1")
EndIf
indexIDArray(j) = j
Next
equipModelVersion rowCounter, indexIDArray
rowCounter = finWkst.UsedRange.Rows.Count
Next ii
End Sub
Sub equipModelVersion(rowCounterDummy As Integer, indexArrayDummy() As String)
ReportBook.Activate
finWkst.Activate
iCol = 1:
Set indexRange = Range(Cells(rowCounterDummy + 1, iCol), Cells(rowCounterDummy + 1 + UBound(valueArrayDummy, 1), iCol))
Dim j As Integer: j = 0
For I = rowCounterDummy + 1 To rowCounterDummy + 1 + UBound(valueArrayDummy, 1)
Cells(I, iCol) = indexArrayDummy(j)
j = j + 1
Next
End Sub
Sub initializeWorkspace()
ReportBook.Activate
finWkst.Activate
Range("A1").Value = "IndexID"
Range("B1").Value = "ModelID"
Range("C1").Value = "UserVersion"
Range("D1").Value = "Equipment"
Range("E1").Value = "Date"
For ii = LBound(cArray) To UBound(cArray)
Cells(1, ii + 5).Value = cArray(ii)
Next
End Sub
我有两个问题:
首先,当equipModelVersion
运行时,它会将值存储在工作表的单元格中,而工作表位于按钮所在的位置,而不是打开的工作簿中,创建用于存储值的工作表。
我该如何纠正?
我尝试使用with语句激活该特定工作表,以及我在Stack Overflow上找到的其他一些快速的东西,但没有任何效果。
其次,当我调试transposeDataMatrices
并单独使用它时,以下行有效:
Set totRange = Range(Range(Selection, Selection.End(xlToRight).Offset(0, -1)), Selection.End(xlDown))
在我使用按钮转移到工作簿的宏中,它不再有效,所以我不得不解决它:
ReportBook.Worksheets(ii).Range(Selection, Selection.End(xlToRight).Offset(0, -1)).Select
ReportBook.Worksheets(ii).Range(Selection, Selection.End(xlDown)).Select
Set totRange = Selection
看起来很糟糕。
为什么VBA对它如此愚蠢,当代码完全是IDENTICAL,但是扩展了?
答案 0 :(得分:6)
VBA并不聪明,它只会做你所说的不做你认为你告诉它的事情。
我的猜测是ReportBook.Worksheets(ii)
正在失去焦点。
最好在使用对象时始终声明父级。简单的方法是声明父对象是一个变量。
在这种情况下:
Dim ws as worksheet
set ws = ReportBook.Worksheets(ii)
然后使用相同的两行使用with
语句
with ws
Set totRange =.Range(Selection, Selection.End(xlDown))
end with
您应该避免使用.select
命令。有关详细信息,请参阅here。使用它只会弄脏代码并使查找错误变得更加困难。