如何简化复制内容代码?

我有一系列的代码来跟踪文件path,并从多个Excel文件中追踪数据。

我想知道有什么办法可以修改代码,所以我不需要通过改变单元格值来保持复制和粘贴相同的代码?

这里是代码:

Sub FetchData() Dim shDestin As Worksheet Application.ScreenUpdating = False Set shDestin = ThisWorkbook.Sheets("Sheet1") CopyFileContent Range("B11").Value & shDestin.Range("A1").Value, _ shDestin, 11 CopyFileContent Range("B12").Value & shDestin.Range("A1").Value, _ shDestin, 12 CopyFileContent Range("B13").Value & shDestin.Range("A1").Value, _ shDestin, 13 CopyFileContent Range("B14").Value & shDestin.Range("A1").Value, _ shDestin, 14 CopyFileContent Range("B15").Value & shDestin.Range("A1").Value, _ shDestin, 15 CopyFileContent Range("B16").Value & shDestin.Range("A1").Value, _ shDestin, 16 CopyFileContent Range("B17").Value & shDestin.Range("A1").Value, _ shDestin, 17 CopyFileContent Range("B18").Value & shDestin.Range("A1").Value, _ shDestin, 18 CopyFileContent Range("B19").Value & shDestin.Range("A1").Value, _ shDestin, 19 

有什么方法可以设置范围如B11:B19然后shDestin 11:19 ? 这将是麻烦,因为在将来我可能有一个文件夹中的50多个文件来跟踪数据…

你也可以试试For Each ,我认为它更具可读性。

 Dim cel As Range For Each cel In Range("B11:B19") '~~> or any range you want CopyFileContent cel.Value & shDestin.Range("A1").Value _ , shDestin, cel.Row Next 
 For index As Integer = 11 To 19 CopyFileContent Range("B" & cstr(index) ).Value & shDestin.Range("A1").Value, shDestin, index Next i 

"B" & cstr(index)将在循环中转换为“B11”至“B19”