我正在尝试将信息从Excel数据库文件复制到Excel显示文件。我已经弄清楚如何复制这些信息,我有不同的宏,具体取决于我正在查看的不同信息。这些似乎是独立工作的。
但是我还想要包含一个下拉字段,然后允许用户选择他们想要查看的数据集(基本上是哪个客户)。我的代码如下,我是网站的新用户,所以如果格式不正确请告诉我,以便我可以改进它:)
Private Sub ComboBox1_Click()
Select Case ComboBox1.Value
Case "Acme"
'Acme Macro
' Pulls Acme Customer Information from Database for each Segment
Application.CutCopyMode = False
Windows("Product_List_Template.xlsx").Activate
Sheets("Segment1").Range("C1:C278").Copy
Windows("Tool V0A.xlsm").Activate
Sheets("Segment1").Range("J1:J278").Paste
Application.CutCopyMode = False
Windows("Product_List_Template.xlsx").Activate
Sheets("Segment2").Range("C1:C278").Copy
Windows("Tool V0A.xlsm").Activate
Sheets("Segment2").Range("J1:J278").Paste
Application.CutCopyMode = False
Sheets("Dashboard").Select
Application.CutCopyMode = False
Calculate
Case "Ball"
' Ball Macro
' Pulls Ball Customer Information from Database for each Segment
Windows("Product_List_Template.xlsx").Activate
Sheets("Segment1").Select
Range("D1:D278").Select
Selection.Copy
Windows("Tool V0A.xlsm").Activate
Sheets("Segment1").Select
Range("J1:J278").Select
ActiveSheet.Paste
Windows("Product_List_Template.xlsx").Activate
Sheets("Segment2").Select
Range("D1:D278").Select
Application.CutCopyMode = False
Selection.Copy
Windows("Tool V0A.xlsm").Activate
Sheets("Segment2").Select
Range("J1:J278").Select
ActiveSheet.Paste
Sheets("Dashboard").Select
Application.CutCopyMode = False
Calculate
Case Else
Exit Sub
End Select
End Sub
所以代码选择了正确的Case,然后当它开始进入指定的宏时,我遇到“运行时错误'1004':选择Range类的方法失败”弹出。当我去调试代码它有“范围(”D1:D278“)。选择”突出显示为失败时。我试过复制列,我尝试复制较小的范围,没有任何工作。该范围内的所有细胞都有信息,但由于某种原因它只是不起作用。我非常感谢任何人的帮助!
答案 0 :(得分:1)
Private Sub ComboBox1_Click()
Dim wbPlt As Workbook, wbTool As Workbook, sourceRange As String
Set wbPlt = Workbooks("Product_List_Template.xlsx")
Set wbTool = ThisWorkbook 'Workbooks("Tool V0A.xlsm")
Select Case ComboBox1.Value
Case "Acme": sourceRange = "C1:C278"
Case "Ball": sourceRange = "D1:D278"
Case Else: sourceRange = ""
End Select
'copy if have source range
If sourceRange <> "" Then
wbPlt.Sheets("Segment1").Range(sourceRange).Copy _
wbTool.Sheets("Segment1").Range("J1")
wbPlt.Sheets("Segment2").Range(sourceRange).Copy _
wbTool.Sheets("Segment2").Range("J1")
wbTool.Sheets("Dashboard").Select
Application.CutCopyMode = False
Calculate
End If
End Sub