【问题标题】:How to simplify the copy content code?如何简化复制内容代码?
【发布时间】:2014-05-27 02:43:10
【问题描述】:

我有一系列代码来跟踪文件路径并从多个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 多个文件来跟踪数据......

【问题讨论】:

    标签: excel excel-2010 export-to-excel vba


    【解决方案1】:

    您也可以尝试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
    

    【讨论】:

    • @Kimberly 实际上,如果您按照我在他的回答中评论的那样分别声明和初始化变量,VinhNT 的回答也会起作用。
    【解决方案2】:
    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”

    【讨论】:

    • 嗨,@VinhNT,它显示语法错误索引为整数 = 11 到 19
    • 这在 VBA 中不起作用。 VB.Net 允许在一行中声明和初始化变量,而不是 VBA。要修复,Dim i As Interger 然后在单独的行上 For i = 11 To 19
    • 谢谢~我已经修好了~
    猜你喜欢
    • 1970-01-01
    • 2016-11-16
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2017-07-08
    相关资源
    最近更新 更多