如何在Excel中转​​置不同的列?

时间:2018-07-25 02:04:02

标签: excel excel-vba excel-formula

enter image description here

我有很多像上面的行。

下表是理想的结果。

我曾经使用过v-lookup,没有运气的数据透视表。

有什么方法可以正确匹配不同的列?

2 个答案:

答案 0 :(得分:3)

If you want to get from this:

img1

...to this:

img2

Then what you want to do is called an Unpivot.

  1. Highlight your data and hit CTRL+T to make it into a table. (Check the "my data has headings" if there are headings, or un-check it if it does not, like your example.)
  2. On the DATA tab click FROM TABLE/RANGE. This will open PowerQuery.
  3. You need to select all columns EXCEPT for the first one, so click the 2nd column and then push and hold CTRL while you click each of the others to the right of it.
  4. on the TRANSFORM tab click UNPIVOT COLUMNS.
  5. Click the X in the top-right of the screen, and click "KEEP CHANGES"

You're Done! (...so easy that it's fun!)

Image

  • More example and links to more detailed information at my other answer here.

答案 1 :(得分:1)

Yes it can be done. Here is a vba-less approach. I am using two working columns, A and B (but these could be tucked away elsewhere and hidden). My entries start somewhere below your data lines, in my case on line 6, where in A6 through D6 I put column headers:

sourceline    sourcecol    country    city

Now in A7 I put the number 1 to say start in the first row. In A8 I put the following formula which I dragged down as far as needed. =if(1+countif(indirect("A7:A"&(row()-1)),A7)=(counta(indirect("A"&A7&":Z"&A7))),A7+1,A7). What does it do? Well, it says let us see how many times the number right above me has occurred. If it is the same as the number of cities (assumed <=25) in the corresponding row, it is time to add 1 and move on to the next row. Otherwise, keep going with that same row.

In B7 I put the following formula and dragged it on down. =if(A7=A6,1+B6,2) It says, If I am still in the same row as the preceding entry, move over a column, else restart at column 2 (B).

Once I have the row and the column, for the country I needed the following in C7 and dragged down =indirect(address(A7,1)) which says find me the value in the row mentioned here and column 1 (A).

Similarly in D7 and dragged on down I have =indirect(address(A7,B7)) to get the city. That produces your desired table (maybe two columns over, but you could adjust that).

By leaving at least one blank line between the inputs and the headers of my outputs, you also end up with blanks at the bottom of the table if you drag your formula a bit beyond where it is needed.

You could probably simplify the formulas a smidge using the OFFSET function.