我想从工作簿中获取包含多个工作表的数据,并且不知道哪个工作表有数据。因此,需要检查工作簿的每个工作表的已用行数,并激活包含用于获取数据的最大已用行的工作表。使用以下代码的结构和任何建议将不胜感激。
Sub Maxdatasheet()
Dim wscount As Integer
Dim myArray() As Variant
wscount = ActiveWorkbook.Worksheets.Count
For i = 1 To wscount
myArray(i) = Worksheets(i).UsedRange.Rows.Count
Next
'need to activate the maximus rows of the sheet
End Sub
答案 0 :(得分:5)
一些变化:
- 没有数组,跟踪哪张表有最大值而不是
- 更改为For Each(即使您的代码在这方面完全没问题)
Sub Maxdatasheet()
Dim ws As Worksheet
Dim MaxRowSheet As Worksheet
Dim MaxRowCount As Long ' Do not use Integer, may be too small and cause overflow
wscount = ActiveWorkbook.Worksheets.Count
MaxRowCount = 0
For Each ws In ActiveWorkbook.Worksheets
If ws.UsedRange.Rows.Count > MaxRowCount Then
MaxRowCount = ws.UsedRange.Rows.Count
Set MaxRowSheet = ws
End If
Next
MaxRowSheet.Activate
End Sub
答案 1 :(得分:1)
获取每张表中已用行的计数 -
Sub Maxdatasheet()
Dim wscount As Integer
Dim myArray() As Variant
wscount = ActiveWorkbook.Worksheets.Count
ReDim myArray(1 To wscount)
For i = 1 To wscount
myArray(i) = Worksheets(i).UsedRange.Rows.Count
Debug.Print myArray(i)
Next
End Sub
答案 2 :(得分:1)
这是我前段时间为自己写的一些代码。 它计算所有工作表的所有行号,并在MsgBox中单独显示它们(总和也显示)。
Sub Datensätze_zählen()
'
' Datensätze_zählen Makro
' Zählt alle Datensätze, aller Blätter einer Excel-Datei und gibt diese in einer MsgBox aus
'
Dim all_rows As Long
Dim sheet_row As String
Dim all_array() As String
Dim max_row As Long
If ActiveWorkbook.Sheets.Count > 1 Then
ReDim all_array(ActiveWorkbook.Sheets.Count)
For i = 1 To ActiveWorkbook.Sheets.Count
ActiveWorkbook.Sheets(i).Activate
sheet_row = ActiveSheet.name & " " & CStr(ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).row) - 1 ' wenn es keine Überschrift gibt, dann ohne "- 1"
all_rows = all_rows + ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).row - 1 ' wenn es keine Überschrift gibt, dann ohne "- 1"
all_array(i - 1) = sheet_row
Next i
MsgBox (Join(all_array, vbCrLf) & vbCrLf & all_rows)
ElseIf ActiveWorkbook.Sheets.Count = 1 Then
ActiveWorkbook.Sheets(1).Activate
MsgBox (ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).row) - 1 ' wenn es keine Überschrift gibt, dann ohne "- 1"
Else
MsgBox ("In der ausgewählten Excel-Datei ist kein Worksheet vorhanden.")
End If
Erase all_array
End Sub
希望这就是你要找的东西
答案 3 :(得分:0)
Function CountRow(ColumnName As String, ws as Worksheet) As Long
CountRow = ws.Range(ColumnName& "65536").End(xlUp).row
End Function
Sub SelectMAX()
Dim ws as Worksheet, max as Worksheet
max = ThisWorkbook.Worksheet(1)
For Each ws in ThisWorkbook.Worksheets
if CountRoW("A", ws) > CountRow("A", max) then max = ws
Next
max.Activate
End Sub
希望这有帮助。
附:你可以改变" A"如果需要,可以到任何其他专栏。