【问题标题】:How to copy data from another workbook according to Inputbox and cell coordinates?如何根据输入框和单元格坐标从另一个工作簿复制数据?
【发布时间】:2019-06-24 14:44:06
【问题描述】:

我对 VBA 非常陌生,需要帮助来编写可以自动合成来自其他工作簿的数据的代码。

我的想法是我每个月都有不同的文件(例如 2019-04),并且在每个文件中都有几个工作簿,用于我需要处理的不同投资组合。

我希望通过以下方式合成数据:每一行代表一个投资组合,列代表我希望从其他文件复制的数据。每 7 列特定于一个特定的月份。

在我目前的代码中,我提示用户在以下表格中输入投资组合的日期:YYYY-MM;然后我想找到具有这个特定日期的单元格的列(这部分我还没有弄清楚)。

然后我使用一个循环来打开我要从中复制信息的每个工作簿。

最后,它将根据投资组合的行和日期的列从每个工作簿中复制数据。

任何帮助都将不胜感激,因为我刚刚发现了 VBA,所以我还不是很熟悉所有的技巧和技巧。

这是我目前所拥有的(注意我没有输入我想要复制的所有 7 个值):

Sub StressTest()

Dim index As Integer
Dim dateColumn As Integer
Dim portfolioName As Variant
Dim portfolioDate As Variant

portfolioDate = InputBox("Please enter date under the following form : YYYY-MM", "Date at the time of Stress Test", "Type Here")
For index = 3 To 39

portfolioName = Range("A" & index & " ").Value

Workbooks.Open "G:\Risk\Risk Reports\VaR-Stress test\" & portfolioDate & "\" & portfolioName & ""

Cells(index, dateColumn).Value = Workbooks("" & portfolioName & "").Worksheets("VaR Comparison").Range("B19") / Workbooks("" & portfolioName & "").Worksheets("Holdings - Main View").Range("E11")

Cells(index, dateColumn + 1).Value = (Cells(index, dateColumn) - Cells(index, dateColumn + 6)) / Cells(index, dateColumn + 6)

Cells(index, dateColumn + 2).Value = Workbooks("" & portfolioName & "").Worksheets("Holdings - Main View").Range("E11")

Cells(index, dateColumn + 3).Value = (Cells(index, dateColumn + 2) - Cells(index, dateColumn + 9)) / Cells(index, dateColumn + 9)



Next index

End Sub

【问题讨论】:

  • 那么缺少的是 datecolumn 的值吗?您希望该列与用户输入的日期相对应吗?
  • 没错,当我在输入框中输入日期时,我想选择值与日期匹配的单元格并将其列号分配给 dateColumn。

标签: excel vba


【解决方案1】:

有多种方法可以找到具有匹配标题的列。为简单起见,这里是蛮力方法。它假定活动表是带有标题的表,并且它们位于第一行。使用“datecolumn = matchheader(portfoliodate)”获取列号

Function MatchHeader(strSearch As String) As Long
Dim myRight As Long, Colcount As Long
myRight = ActiveSheet.Cells(1, ActiveSheet.Columns.Count).End(xlToLeft).Column
For Colcount = 1 To myRight
    If ActiveSheet.Cells(1, Colcount) = strSearch Then
        MatchHeader = Colcount
        Exit For
    End If
Next Colcount
End Function

【讨论】:

    猜你喜欢
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多