繁体   English   中英

如何根据Inputbox和单元格坐标从另一个工作簿复制数据?

[英]How to copy data from another workbook according to Inputbox and cell coordinates?

我是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 = 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

暂无
暂无

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

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