excel - 无法运行 vba 功能
问题描述
我一直在尝试运行此函数来计算当前工作簿中每张工作表中的行数。我从之前回答的问题中得到了这个功能。
但是,当我尝试运行它时,它要求我创建一个宏,当我这样做时它会创建一个“Sub ()”,当我将函数放入其中时,它会给我“Expected End Sub”的错误我'我不知道该怎么办。我尝试了各种重写代码的方法,但无济于事。
我是 vba 新手,不确定这里有什么问题。
Function Test_It()
For Each Sheet In ThisWorkbook.Sheets
Debug.Print Sheet.Name & vbTab & CountMyRows(Sheet.Name)
Next Sheet
End Function
Function CountMyRows(SName) As Long '# where SName is the name of a sheet
Dim rowCount As Long
rowCount = Worksheets(SName).UsedRange.Rows.Count
CountMyRows = rowCount
End Function
解决方案
Function
在 a 中使用Sub
- 请注意,
Sheets
(对象的)集合Workbook
还包括没有UsedRange
. - 在编写引用对象的函数时,最好将对象用作参数。例如,在您的函数版本中,您使用的是不合格的
Worksheets(SName)
,我们不知道它属于哪个工作簿。所以如果ThisWorkbook
inSub
不活跃,函数可能会失败或者可能无法写入正确的结果。
Option Explicit
Sub Test_It()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
Debug.Print ws.Name & vbTab & CountMyRows(ws)
' Without the function (the function is kind of useless):
'Debug.Print ws.Name & vbTab & ws.UsedRange.Rows.Count
Next ws
End Sub
Function CountMyRows(ByVal ws As Worksheet) As Long
If ws Is Nothing Then Exit Function
CountMyRows = ws.UsedRange.Rows.Count
End Function
编辑
一个更实际的例子
以下将工作表名称和ThisWorkbook
(包含此代码的工作簿)的相应“使用范围行数”写入新工作簿的第一个工作表。
Sub testRowsCount()
' Add a new (destination) workbook and create a reference
' to its first (destination) worksheet.
Dim dws As Worksheet: Set dws = Workbooks.Add.Worksheets(1)
' Write headers.
dws.Cells(1, "A").Value = "Name"
dws.Cells(1, "B").Value = "RowsCount"
' Define destination rows counter.
Dim n As Long: n = 1
Dim sws As Worksheet
' Loop through the worksheets collection (all worksheets)
' of the Source Workbook and write the names and used range
' rows counts to the Destination Worksheet.
For Each sws In ThisWorkbook.Worksheets
n = n + 1
dws.Cells(n, "A").Value = sws.Name
dws.Cells(n, "B").Value = CountMyRows(sws)
Next sws
dws.Parent.Saved = True ' for easy closing only.
End Sub
推荐阅读
- r - 如何将数据输入ggplots
- c - How do you continue to scan until new line C without using (fgets)
- c++ - C++ 结构默认调用值
- c - C相同的代码,VScode编译,VisualStudio没有
- google-apps-script - GDrive 禁用复制和下载
- javascript - 将 C# 内联变量传递给 ASP.Net 应用程序中的 Javascript 函数
- javascript - 修改此白名单函数,使其返回具有特定键值字段的对象
- python - 使用 .split() 函数后切片不起作用
- java - Java流将字符串列表排序为数字问题
- python - 无法保存具有透明背景的动画 gif (matplotlib.animation)