我是VBA的新手,我一直在尝试将一些文件中的一些数据粘贴到我的活动文件中。不幸的是,我一直在收到错误13 - Type Mismatch。我已经尝试更改每个变量定义,甚至将它们声明为Variant
,但没有任何帮助。代码中最相关的部分如下,星号之间有错误。
dim i, j, k, CompShtStartNum, CompShtQty as integer
dim OldFile as variant
dim WCompWS, WCOl, NumEntryCol, ShtName as string
dim InputsSht as worksheet
dim NumEntryColRange, OldEntryCount as range
'Paste data from Entry Label columns into comparison sheets
'Paste in the data from the old file
For i = CompShtStartNum To CompShtStartNum + CompShtQty - 1
ShtName = ThisWorkbook.Sheets(i).Name
Set OldSht = OldFile.Sheets(ShtName)
Set OldEntryCount = Range(OldSht.Cells(2, 1), OldSht.Cells(Rows.Count, 1).End(xlDown))
For j = 1 To CompShtStartNum - i + 1
For k = 1 To InputsSht.Range(WCol & 12 + j - 1).Value
If OldFile.Sheets(i).Cells(1, k).Value = Sheets(i).Cells(1, k).Value Then
***Sheets(i).Cells(2, k).Resize(OldEntryCount.Rows.Count, 1).Value = Application.Transpose(OldEntryCount.Value)***
End If
Next k
Next j
Next i
对于上下文,这是完整的代码:
Set OldFile = Application.Workbooks("Old Input File.xlsx")
Let WCompWS = "E"
Let WCol = "F"
Let CompShtStartNum = 2
Set InputsSht = ThisWorkbook.Sheets("Inputs")
Let CompShtQty = InputsSht.Range(WCompWS & 12, InputsSht.Range(WCompWS & 12).End(xlDown)).Count
'Loop thru each sheet and have the user determine the last column of labels. Paste result on Inputs sheet.
For i = CompShtStartNum To CompShtStartNum + CompShtQty - 1
ShtName = ThisWorkbook.Sheets(i).Name
Sheets(ShtName).Activate
NumEntryCol = Application.InputBox("How many columns (from the left-hand side) contain entry labels?" & vbNewLine & "(Examples of entry labels: Library #, Entry #, etc.)" & vbNewLine & vbNewLine & "Please type your answer numerically.", ShtName)
InputsSht.Range(WCol & 12 + i - CompShtStartNum).Value = NumEntryCol
Next i
Set NumEntryColRange = InputsSht.Range(WCol & 12, InputsSht.Range(WCol & 12).End(xlDown))
InputsSht.Activate
'Paste data from Entry Label columns into comparison sheets
'Paste in the data from the old file
For i = CompShtStartNum To CompShtStartNum + CompShtQty - 1
ShtName = ThisWorkbook.Sheets(i).Name
Set OldSht = OldFile.Sheets(ShtName)
Set OldEntryCount = Range(OldSht.Cells(2, 1), OldSht.Cells(Rows.Count, 1).End(xlDown))
For j = 1 To CompShtStartNum - i + 1
For k = 1 To InputsSht.Range(WCol & 12 + j - 1).Value
If OldFile.Sheets(i).Cells(1, k).Value = Sheets(i).Cells(1, k).Value Then
***Sheets(i).Cells(2, k).Resize(OldEntryCount.Rows.Count, 1).Value = Application.Transpose(OldEntryCount.Value)***
End If
Next k
Next j
Next i
非常感谢任何帮助或建议!!
答案 0 :(得分:0)
但是,结果只是A2中的值被粘贴到活动文件表上的A2:A7中。如何将A2:A7中的每个值粘贴到我的活动工作表上各自的单元格中?
试试这个
Sheets(i).Cells(2, k).Resize(OldEntryCount.Rows.Count, 1).Value = _
OldEntryCount.Value
这是一个简短的演示。假设我们的工作表看起来像这样
现在假设我们希望A1:A5
中的B1:B5
Sheet1
的值
只需尝试这个
Sub Sample()
Dim OldEntryCount As Range
With ThisWorkbook.Sheets("Sheet1")
Set OldEntryCount = .Range("A1:A5")
.Range("B1").Resize(OldEntryCount.Rows.Count, 1).Value = _
OldEntryCount.Value
End With
End Sub
你会得到结果