简体   繁体   English

将VBA中范围的第一行设置为基于单元格值

[英]Setting top row of range in vba to be based on a cell value

I'm new to vba coding and am trying to write code at my current job that will combine multiple excel spreadsheets into one (by appending them). 我是vba编码的新手,正在尝试在当前工作中编写代码,该代码会将多个excel电子表格合并为一个(通过附加)。 The main problem is that the # of rows as well as the starting row for the ranges that I need to copy from each spreadsheet differ across files. 主要问题是我需要从每个电子表格复制的范围的行数和起始行在文件之间不同。

Specifics: My datasets each have a header, "Opportunity Name," that is in column A and that can typically be found in row 17 but it can vary. 详细信息:我的数据集每个都有一个标题“机会名称”,该标题位于A列中,通常可以在第17行中找到,但可以有所不同。 I want the top row of my range to start in the row immediately below Opportunity Name so my best guess is to try and get the code to search for that value, find the row number + 1, and perhaps store that as an object (FirstRow in the below example?) to be used in the range function. 我希望范围的第一行从商机名称下面的行开始,所以我最好的猜测是尝试获取代码以搜索该值,找到行号+ 1,然后将其存储为对象(FirstRow在下面的示例中?)将在范围函数中使用。 But as you can see in the code below, the only range syntax I've been able to run starts in A17 each time. 但是,正如您在下面的代码中看到的那样,我每次能够运行的唯一范围语法都是从A17开始的。 Please help point me in the right direction to change that A17 to be variable or if there's a better way to go about this. 请帮我指出正确的方向,以将A17更改为可变的,或者是否有更好的方法来解决此问题。

For nfile = LBound(SelectedFiles) To UBound(SelectedFiles)
    FileName = SelectedFiles(nfile)
    Set wb = Workbooks.Open(FileName)
    LastRow = wb.Worksheets(1).Cells(Rows.Count, "A").End(xlUp).Row
    FirstRow = wb.Worksheets(1).Cells.Find("Opportunity Name").End(xlUp).Row
    Set SourceRange = wb.Worksheets(1).Range("**A17**:AB" & LastRow)
    Set DestRange = Sheet1.Range("A" & nrow)
    Set DestRange = DestRange.Resize(SourceRange.Rows.Count, SourceRange.Columns.Count)

    DestRange.Value = SourceRange.Value

    nrow = DestRange.Rows.Count + nrow

    wb.Close savechanges = False

Next nfile

Thanks, 谢谢,

Thomas 托马斯

You don't need .End(xlUp).Row when you're finding FirstRow . 找到FirstRow时,不需要.End(xlUp).Row

...
FirstRow = wb.Worksheets(1).Cells.Find("Opportunity Name").Row + 1
Set SourceRange = wb.Worksheets(1).Range("A" & FirstRow & ":AB" & LastRow)
...

NB You could also add error checking to make sure that "Opportunity Name" is found. 注意:您也可以添加错误检查,以确保找到了“商机名称”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM