使用来自不同工作表的数据设置变量

问题描述:

我在代码的最后一行遇到问题。我相信问题在于我如何设置我的范围,但我不知道如何设置它。我试图通过确保用户表单中的所有字段在宏中继续之前被填充进来进行错误检查。使用来自不同工作表的数据设置变量

Dim emptyRowNumber As Long 
emptyRowNumber = Application.WorksheetFunction.CountA(Sheets("Leads").Range("a:a")) + 1 
. 
. 
. 
Dim filledCount As Integer 
filledCount = Application.WorksheetFunction.CountA(Sheets("Leads").Range(Cells(emptyRowNumber, 1), Cells(emptyRowNumber, 11))) 
+0

欢迎来到[so],请[参观],检查[问]并提供[mcve]。如果您遇到错误,请提供完整的错误消息。 – *er

+0

是不是活动工作表?在'Cells()'的两个实例之前添加'Sheets(“Leads”)。'。另外,发生了什么,你有错误吗?如果是这样,哪里出错? – BruceWayne

您需要将范围语句内的所有单元格和范围限定为同一工作表。

在此代码示例中,Cells(emptyRowNumber, 1)Cells(emptyRowNumber, 11)指的是ActiveSheet上的单元格,而不是Sheets("Leads")的单元格。

表( “信息”)。范围(将细胞(emptyRowNumber,1),将细胞(emptyRowNumber,11))

个人喜好I组在我的程序顶部的所有变量按字母顺序的数据类型(数字,字符串,对象等)。我还建议使用With语句来缩短您的代码。

Dim emptyRowNumber As Long, filledCount As Integer 

With Sheets("Leads") 
    emptyRowNumber = Application.WorksheetFunction.CountA(.Range("a:a")) + 1 
    filledCount = Application.WorksheetFunction.CountA(.Range(.Cells(emptyRowNumber, 1), .Cells(emptyRowNumber, 11))) 
End With 
+0

美丽。我在教自己的VBA,所以有些事情我知道我不会有效地做。谢谢。 –

+0

您应该在Youtube上观看本系列:[Excel VBA简介](https://www.youtube.com/watch?v=KHO5NIcZAc4&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5) – 2017-07-27 23:02:17