使用variables在Excel VBA中按其编号声明工作表

晚上好。 我正在拼命写一些VBA代码。

Public TFOCUS As Integer ' Creates TFOCUS, which is the worksheet in focus Public RFOCUS As Integer ' Creates RFOCUS, which is the row in focus Public CFOCUS As String ' Creates CFOCUS, which is the column in focus Public RECORD As Integer ' Creates RECORD, wich is the row that is having the record written to FILEPATH.Worksheets(TFOCUS).Range(Cells(RFOCUS, B)).Value = Worksheets(3).Range(Cells(RECORD, A)).Value 'copies focus EmpID to destination FILEPATH.Worksheets(TFOCUS).Range(Cells(4, CFOCUS)).Value = Worksheets(3).Range(Cells(RECORD, B)).Value 'copies focus Course to destination FILEPATH.Worksheets(TFOCUS).Range(Cells(RFOCUS, CFOCUS)).Value = Worksheets(3).Range(Cells(RECORD, C)).Value 'copies focus Date to destination CFOCUS = CFOCUS + 1 'moves focus to next column RECORD = RECORD + 1 'creates next record 

FILEPATH设置为外部Excel工作簿的path。 在这种情况下,TFOCUS设置为1,RFOCUS设置为5,CFOCUS设置为“Q”,RECORD设置为1。

目的是将外部excel文档中的logging复制到活动电子表格中,并通过移动单元格内容来重新格式化它们。 这将被用于移动多个来源,并将不得不处理每个源文档中的每个选项卡(这可以被命名为不同的东西)。

我遇到的问题是在编译时在下面一行中收到运行时错误13:types不匹配错误:

 FILEPATH.Worksheets(TFOCUS).Range(Cells(RFOCUS, B)).Value = Worksheets(3).Range(Cells(RECORD, A)).Value 'copies focus EmpID to destination 

我假设这是要么使用TFOCUS作为整数或FILEPATH作为文件path。 有谁可以build议:

  • 究竟是什么错配呢?
  • 如果是因为使用工作表(TFOCUS),任何方式,我可以通过使用variables的选项卡顺序的编号引用工作表?
  • 还有其他build议吗?

在此先感谢您的帮助。

你没有向我们显示variables是在哪里分配的,但是…

 Public RFOCUS As Integer ' Creates RFOCUS, which is the row in focus Public CFOCUS As String ' Creates CFOCUS, which is the column in focus 

尝试将CFOCUS声明为Integer 。 或者更好,作为一个Long ,这样你的代码在第32767行之外工作( Integertypes是16位和有符号的,所以32768是一个溢出值)。

另外,如果FILEPATH是一个String ,那么你的代码不能工作:

FILEPATH设置为外部Excel工作簿的path。

 FILEPATH.Worksheets(TFOCUS) 

它应该是一个Workbook对象..但是那么你使用的标识符是非常混乱的。

 Dim wb As Workbook Set wb = Workbooks.Open(FILEPATH) wb.Worksheets(TFOCUS).Range(Cells(RFOCUS, B)).Value = Worksheets(3).Range(Cells(RECORD, A)).Value 'copies focus EmpID to destination wb.Worksheets(TFOCUS).Range(Cells(4, CFOCUS)).Value = Worksheets(3).Range(Cells(RECORD, B)).Value 'copies focus Course to destination wb.Worksheets(TFOCUS).Range(Cells(RFOCUS, CFOCUS)).Value = Worksheets(3).Range(Cells(RECORD, C)).Value 'copies focus Date to destination CFOCUS = CFOCUS + 1 'moves focus to next column RECORD = RECORD + 1 'creates next record 'save [wb] workbook? Close it? Set wb = Nothing 

我也可以build议保持YELLCASE为常量,并使用camelCase本地人和PascalCase的一切?

如果RFOCUS设置为“Q”,B和A是整数,则:

 FILEPATH.Worksheets(TFOCUS).Range(Cells(RFOCUS, B)).Value = Worksheets(3).Range(Cells(RECORD, A)).Value 

应该:

 FILEPATH.Worksheets(TFOCUS).Range(RFOCUS & B).Value = Worksheets(3).Cells(Record, A).Value 

这里是所有3行:

 FILEPATH.Worksheets(TFOCUS).Range(RFOCUS & B).Value = Worksheets(3).Cells(Record, A).Value FILEPATH.Worksheets(TFOCUS).Cells(4, CFOCUS).Value = Worksheets(3).Cells(Record, B).Value FILEPATH.Worksheets(TFOCUS).Range(RFOCUS & CFOCUS).Value = Worksheets(3).Cells(Record, C).Value